Java:微信公众号:现金红包支付

依据:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3

有不明白的地方,可以评论问我

1.传参:

    // 发送红包接口
    public static String sendRedPack(String openId, String sendName, String wishing, String actName, String remark, String totalAmount) throws UnknownHostException {

        String orderNNo =  WXRedPackUtils.getOrderNo() ; 
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nonce_str", WXRedPackUtils.buildRandom());//随机字符串
        map.put("mch_billno", orderNNo);//商户订单
        map.put("mch_id", mchId);//商户号
        map.put("wxappid", "wxxxxxxxxxxxxxxx");//公众号appid
        map.put("send_name", sendName);//发送名
        map.put("re_openid", openId);//用户openid
        map.put("total_amount", totalAmount);//付款金额 单位分 
        map.put("total_num", 1);//红包发送总人数
        map.put("wishing", wishing);//红包祝福语
        map.put("client_ip", InetAddress.getLocalHost());//发送端ip地址
        map.put("act_name", actName);//活动名称
        map.put("remark", remark);//备注
        //map.put("scene_id","PRODUCT_1"); //红包金额大于200时,选择使用场景 1-8
        map.put("sign", WXRedPackUtils.createSign(map));//签名

        String result = "";
        try {
            result = WXRedPackUtils.doSendMoney(url, WXRedPackUtils.createXML(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("result:"+result);
        String resultMsg = result.substring(result.indexOf("<return_msg><![CDATA[")+21, result.lastIndexOf("]]></return_msg>"));
        return resultMsg;
    }

2.签名:

第一步,设所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA

第二步,在stringA最后拼接上key得到stringSignTemp字符串,并对stringSignTemp进行MD5运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。

    private static String charset = "UTF-8";

    //微信支付商户号
    private static String partner = "填自己的"; 

    //微信支付平台API密钥
    private static String partnerkey = "填自己的";

    //证件存储路径
    private static String KEYSTORE_FILE = "填自己的";

    //默认为微信支付商户号
    private static String KEYSTORE_PASSWORD = "填自己的";

    public static String createSign(Map<String, Object> map) {
        SortedMap<String, String> packageParams = new TreeMap<String, String>();

        for (Map.Entry<String, Object> m : map.entrySet()) {
            packageParams.put(m.getKey(), m.getValue().toString());
        }

        StringBuffer sb = new StringBuffer();
        Set<?> es = packageParams.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 (!StringUtils.isEmpty(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + partnerkey);

        String sign = MD5Util.MD5Encode(sb.toString(), charset).toUpperCase();
        return sign;
    }

3.调用证书,并发送:

public static String doSendMoney(String url, String data) throws Exception {
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(KEYSTORE_FILE));//P12文件目录
        //InputStream instream = RedPackUtils.class.getResourceAsStream("/apiclient_cert.p12");
        try {
            keyStore.load(instream, KEYSTORE_PASSWORD.toCharArray());//默认密码为微信支付商户号
        } finally {
            instream.close();
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, KEYSTORE_PASSWORD.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
            HttpPost httpost = new HttpPost(url);
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity(),"UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

3.还有一些在你传参的时候要用到的方法:

    //随机16为数值
    public static String buildRandom() {

        //生成3位随机数
        int rRum = new java.util.Random().nextInt(900)+100;

        //当前时间的13位数
        String time = String.valueOf(System.currentTimeMillis())+String.valueOf(rRum);

        return time;
    }

    //生成订单号
    public static String getOrderNo() {
        String order = partner
                + new SimpleDateFormat("yyyyMMdd").format(new Date());
        Random r = new Random();
        for (int i = 0; i < 10; i++) {
            order += r.nextInt(9);
        }
        return order;
    }

    //创建签名所需要的参数xml格式
    public static String createXML(Map<String, Object> map){
        String xml = "<xml>";
        Set<String> set = map.keySet();
        Iterator<String> i = set.iterator();
        while(i.hasNext()){
            String str = i.next();
            xml+="<"+str+">"+"<![CDATA["+map.get(str)+"]]>"+"</"+str+">";
        }
        xml+="</xml>";
        return xml;
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值