微信公众号发红包实现

近期做微信公众号开发,用到了企业向微信用户个人发现金红包的功能,相比之前微信支付功能的实现,多了证书的验证,实现过程总结如下。

  • 数据示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<xml>
<sign><![CDATA[E1EE61A91C8E90F299DE6AE075D60A2D]]></sign>
<mch_billno><![CDATA[0010010404201411170000046545]]></mch_billno>
<mch_id><![CDATA[888]]></mch_id>
<wxappid><![CDATA[wxcbda96de0b165486]]></wxappid>
<send_name><![CDATA[send_name]]></send_name>
<re_openid><![CDATA[onqOjjmM1tad-3ROpncN-yUfa6uI]]></re_openid>
<total_amount><![CDATA[200]]></total_amount>
<total_num><![CDATA[1]]></total_num>
<wishing><![CDATA[恭喜发财]]></wishing>
<client_ip><![CDATA[127.0.0.1]]></client_ip>
<act_name><![CDATA[新年红包]]></act_name>
<remark><![CDATA[新年红包]]></remark>
<nonce_str><![CDATA[50780e0cca98c8c8e814883e5caa672e]]></nonce_str>
</xml>
  • 带证书的请求java代码实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("/../123XXXXXXXX.p12"));
try
{
keyStore.load(instream, "123XXXXXXXX".toCharArray());
}
finally
{
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1236829802".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();
String xml = getPackage();
StringEntity stringEntity;
try
{
HttpPost httppost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack");
stringEntity = new StringEntity(xml, "utf-8");
httppost.setEntity(stringEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
}
...