Java快速对接微信现金红包

工具包:

import com.king.kong.tzj.util.MD5Util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.*;

/**
 * 微信现金红包
 */
public class WXRedPack {

    public static final String KEY = "--------密钥--------";  
    public static final String MCH_ID = "--------商户号--------";              
    public static final String WXAPPID = "--------公众号appid--------";            


    /**
     * @param mch_billno   商户订单号
     * @param openId       用户openid
     * @param send_name    商户名称
     * @param total_amount 付款金额
     * @param total_num    红包发放总人数
     * @param wishing      红包祝福语
     * @param act_name     活动名称
     * @param remark       备注
     * @param client_ip    Ip地址
     * @throws Exception
     */
    public static void sendRedPack(String mch_billno,String openId,String send_name,String total_amount,String total_num,String wishing,String act_name,String remark,String client_ip) throws Exception{
        SortedMap<Object, Object> p = new TreeMap<Object, Object>();
        p.put("nonce_str", String.valueOf(new Date().getTime()));
        p.put("mch_billno", mch_billno);
        p.put("mch_id", MCH_ID);  //商户号
        p.put("wxappid", WXAPPID);     //公众账号appid
        p.put("re_openid", openId);
        p.put("total_amount", total_amount);
        p.put("total_num", "1");
        p.put("client_ip", client_ip);
        p.put("act_name",act_name);
        p.put("send_name", send_name);
        p.put("wishing", wishing);
        p.put("remark",remark);
        //发放红包使用场景,红包金额大于200或者小于1元时必传
        if (Integer.valueOf(total_amount).intValue() > 200 || Integer.valueOf(total_amount).intValue() < 1 ){
            p.put("scene_id","PRODUCT_1");
        }
        //生成签名
        sign(p);
        //封装数据
        String reuqestXml = getRequestXml(p);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File("------微信证书地址------"));
        try {
            keyStore.load(instream, MCH_ID.toCharArray());
        } finally {
            instream.close();
        }

        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
                MCH_ID.toCharArray()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf).build();
        try {

            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");

            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            System.out.println("executing request" + httpPost.getRequestLine());
            //请求的xml需转码为iso8859-1编码,否则易出现签名错误或红包上的文字显示有误
            StringEntity reqEntity = new StringEntity(new String(reuqestXml.getBytes(), "ISO8859-1"));
            // 设置类型
            httpPost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        System.out.println(text);
                    }
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    /**
     * 封装数据
     * @param params
     * @return
     */
    public static String getRequestXml(SortedMap<Object, Object> params) {
        StringBuffer sb = new StringBuffer();
        sb.append("");
        Set es = params.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("nick_name".equalsIgnoreCase(k) || "send_name".equalsIgnoreCase(k) || "wishing".equalsIgnoreCase(k) || "act_name".equalsIgnoreCase(k) || "remark".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + " + v + "]]> + k + ">");
            } else {
                sb.append("<" + k + ">" + v + " + k + ">");
            }
        }
        sb.append("");
        return sb.toString();
    }

    /**
     * 对请求参数名ASCII码从小到大排序后签名
     */
    public static void sign(SortedMap<Object, Object> params) {
        Set<Map.Entry<Object, Object>> entrys = params.entrySet();
        Iterator<Map.Entry<Object, Object>> it = entrys.iterator();
        String result = "";
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = it.next();
            result += entry.getKey() + "=" + entry.getValue() + "&";
        }
        result += "key=" + KEY;
        String sign = null;
        try {
            sign = MD5Util.encrypt(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("sign", sign);
    }

}

调用举例:

WXRedPack.sendRedPack(order.getOrderNo(),userInfo.getWxid(),"--项目名称--",String.valueOf(value),String.valueOf(1),"感谢您使用****,欢迎再次使用!","**红包","24小时后未领取则红包自动退回","139.9.191.218");

微信现金红包开发文档地址:
https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1

你可能感兴趣的:(Java)