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("<xml>");
        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 + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
5.1 注册账号 ......................................................................................................................... 7 SDK 使用说明 .................................................................................................................... 8 5.2 获取企业实名认证地址 ................................................................................................. 9 SDK 使用说明 .................................................................................................................. 12 5.3 获取个人实名认证地址 ............................................................................................... 13 SDK 使用说明 .................................................................................................................. 16 5.4 实名证书申请 ............................................................................................................... 16 SDK 使用说明 .................................................................................................................. 17 5.5 印章上传 ....................................................................................................................... 17 SDK 使用说明 .................................................................................................................. 18 5.6 自定义印章 ................................................................................................................... 19 SDK 使用说明 .................................................................................................................. 20 5.7 合同上传 ....................................................................................................................... 20 SDK 使用说明 .................................................................................................................. 21 5.8 模板上传 ....................................................................................................................... 22 SDK 使用说明 ..........................................

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值