调用微信现金红包接口发放红包

可紊 提交于 2020-03-10 19:25:01

1.通过code获取到用户的openid.

引导用户到指定的授权页面

例如:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=redirect_uri&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

参考文章:http://www.cnblogs.com/ansiboy/p/3755158.html

redirect_uri  为微信调用地址,返回code,然后用code通过下面的地址去换取openid

地址: "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxid&secret=secret&code="
            + code + "&grant_type=authorization_code";

公众号需获取网页授权获取用户基本信息权限。

 

2.通过openid及用户相关信息向用户发放红包。

      地址:"https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"

需要发放商户号用户openid等相关信息,需要注意的是签名信息与随机字符串

代码如下:

1. public static String createSendRedPackOrderSign(WeixinRedPacket redPack){
            StringBuffer sign = new StringBuffer();
            sign.append("act_name=").append(redPack.getAct_name());
            sign.append("&client_ip=").append(redPack.getClient_ip());
            sign.append("&mch_billno=").append(redPack.getMch_billno());
            sign.append("&mch_id=").append(redPack.getMch_id());
            sign.append("&nonce_str=").append(redPack.getNonce_str());
            sign.append("&re_openid=").append(redPack.getRe_openid());
            sign.append("&remark=").append(redPack.getRemark());
            sign.append("&send_name=").append(redPack.getSend_name());
            sign.append("&total_amount=").append(redPack.getTotal_amount());
            sign.append("&total_num=").append(redPack.getTotal_num());
            sign.append("&wishing=").append(redPack.getWishing());
            sign.append("&wxappid=").append(redPack.getWxappid());
            sign.append("&key=").append("abcdefg123456789abcdefg123456789");
            return DigestUtils.md5Hex(getContentBytes(sign.toString(), "utf-8")).toUpperCase();
        }
      private static String create_nonce_str() {
            return UUID.randomUUID().toString();
        }

 

2.需要注意上传证书及将所有信息发放给微信,这里还需要使用微信给出的开发包,在微信上下载即可。

 

 Map<String ,String> maps =  new HashMap<String, String>();           //分享任务完成后,调用发红包接口,需要传入商户订单号,openid,发放金额三个参数           WeixinRedPacket bean = new WeixinRedPacket();             bean.setNonce_str(create_nonce_str().substring(0, 31));             bean.setMch_billno(mch_billno);             bean.setMch_id(PayConst.WX_MCH_ID);             bean.setWxappid(PayConst.WX_APPID);             bean.setSend_name(PayConst.WX_SEND_NAME);             bean.setRe_openid(openid);             bean.setTotal_amount(amount);//金额分             bean.setTotal_num(PayConst.WX_TOTAL_NUM);//发送人数             bean.setWishing(PayConst.WX_WISHING);             bean.setClient_ip(PayConst.WX_CLIENT_IP);             bean.setAct_name(PayConst.WX_ACT_NAME);             bean.setRemark(PayConst.WX_REMARK);                  bean.setSign(createSendRedPackOrderSign(bean));            String requestJson = "<xml>"               +"<sign><![CDATA[" + bean.getSign() + "]]></sign>"               +"<mch_billno><![CDATA[" + bean.getMch_billno() + "]]></mch_billno>"               +"<mch_id><![CDATA[" + bean.getMch_id() + "]]></mch_id>"               +"<wxappid><![CDATA[" + bean.getWxappid() + "]]></wxappid>"               +"<send_name><![CDATA["+ bean.getSend_name() +"]]></send_name>"               +"<re_openid><![CDATA[" + bean.getRe_openid() + "]]></re_openid>"               +"<total_amount><![CDATA[" + bean.getTotal_amount() + "]]></total_amount>"               +"<total_num><![CDATA[" + bean.getTotal_num() + "]]></total_num>"               +"<wishing><![CDATA[" + bean.getWishing() + "]]></wishing>"               +"<client_ip><![CDATA[" + bean.getClient_ip() + "]]></client_ip>"               +"<act_name><![CDATA[" + bean.getAct_name() + "]]></act_name>"               +"<remark><![CDATA[" + bean.getRemark() + "]]></remark>"               +"<nonce_str><![CDATA[" + bean.getNonce_str() + "]]></nonce_str>"               +"</xml>";           KeyStore keyStore  = KeyStore.getInstance("PKCS12");
           FileInputStream instream = new FileInputStream(new File("D:\\certs\\apiclient_cert.p12"));
           try {
               keyStore.load(instream, "123".toCharArray());//123为商户号
           } finally {
               instream.close();
           }

           // Trust own CA and all self-signed certs
           SSLContext sslcontext = SSLContexts.custom()
                   .loadKeyMaterial(keyStore, "123".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 httppost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");
               StringEntity s = new StringEntity(requestJson,"UTF-8");
               s.setContentEncoding("UTF-8");
               s.setContentType("text/xml");//发送json数据需要设置contentType
               httppost.setEntity(s);
               CloseableHttpResponse resp = httpclient.execute(httppost);
               try {
                   HttpEntity entity = resp.getEntity();

                   if (entity != null) {
                       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"utf-8"));
                       String text;
                       String xmlString = "";
                       while ((text = bufferedReader.readLine()) != null) {
                           xmlString += text;
                       }
                       
                       //return_code与result_code都为success代表发放红包成功
                       maps = XmlParseUtil.parse(xmlString);
                   }
                   EntityUtils.consume(entity);
               } finally {
                   resp.close();
               }
           } finally {
               httpclient.close();
           }

 

 

微信官方文档地址:https://pay.weixin.qq.com/helper/cashredopenapi_V2.pdf

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!