微信紅包的使用已經很廣泛,本篇文章介紹了微信發紅包的實例,需要有認證的公眾號,且開通了微信支付,商戶平臺且開通了現金紅包的權限即可。
https://pay.weixin.qq.com商戶登陸地址。選擇查看營銷中心的現金紅包
https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1 現金紅包的官網文檔說明
先看幾個圖 簡單的測試。前提需要你去商戶平臺先充值。不支持預支付。本文只是總結微信現金紅包接口的調用與實現。具體要根據自己的業務去實現如何調用該接口。
https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3 文檔中普通紅包有關于所有的講解。 調用必須有商戶平臺的證書。
需要的參數也都有列出。根據自己需求來決定。
1.java封裝一個紅包對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/** * 紅包對象 * @author 小帥帥丶 * @date 2016-8-17上午11:12:19 * @開源中國 http://my.oschina.net/xshuai */ public class RedPack implements Serializable{ private String sign; //根據屬性生成的驗證 private String mch_billno; //訂單號 private String mch_id; //商戶號 private String wxappid; // 微信appid private String send_name; // 商戶名稱 private String re_openid; // 用戶openid private String total_amount; // 付款金額 private String total_num; //紅包接收人數 現金紅包只能是 1 private String wishing; // 紅包祝福語 private String client_ip; // 調用接口機器的IP private String act_name; // 活動名稱 private String remark; // 備注 private String nonce_str; // 隨機字符串 //set get省略 } |
2.需要用的工具類 createBillNo是生成商戶訂單號 官網文檔要求如下:
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
26
27
28
29
30
31
32
33
34
35
36
37
|
/** * 紅包工具類 * @author 小帥帥丶 * @date 2016-8-17上午11:12:19 * @開源中國 http://my.oschina.net/xshuai */ public class RedPackUtil { /** * 生成商戶訂單號 * @param mch_id 商戶號 * @param userId 該用戶的userID * @return */ public static String createBillNo(){ //組成: mch_id+yyyymmdd+10位一天內不能重復的數字 //10位一天內不能重復的數字實現方法如下: //因為每個用戶綁定了userId,他們的userId不同,加上隨機生成的(10-length(userId))可保證這10位數字不一樣 Date dt= new Date(); SimpleDateFormat df = new SimpleDateFormat( "yyyymmdd" ); String nowTime= df.format(dt); int length = 10 ; return WXConstants.MCH_ID + nowTime + getRandomNum(length); } /** * 生成特定位數的隨機數字 * @param length * @return */ public static String getRandomNum( int length) { String val = "" ; Random random = new Random(); for ( int i = 0 ; i < length; i++) { val += String.valueOf(random.nextInt( 10 )); } return val; } } |
3.前面工作很簡單需要的證書和商戶號有。且商戶平臺有金額即可測試現金紅包接口
1
2
3
4
|
RedPack pack = new RedPack( null //第一次為空, RedPackUtil.createBillNo()//商戶訂單號, "你自己的商戶號" , "公眾號的appid" , "名稱" , "要發送用戶的openid" , "發送金額 單位是分 例如100 則是1元RMB" , "只能是1" , "9" , "127.0.0.1" , "活動名稱" , "備注" , "隨機字符串" ); |
測試中除了sign為空。其他都可以填充?,F在我們生成sign簽名;根據pack對象中的參數去生成sign;
具體簽名算法https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3 官網給出的地址
https://pay.weixin.qq.com/wiki/tools/signverify/可以在這個測試頁面進行對比看加密后是否一致。
1
2
3
4
5
|
String signs = Signature.getSign(pack); //生成的signset到pack對象中 pack.setSign(signs); //將對象轉為xml格式 微信要求xml格式 String xml = XmlUtil.objToXml(pack,RedPack. class , "xml" ); |
4.發送紅包
1
2
|
RedPackService service = new RedPacService(); String result = service.redpackOrder(xml); //請求返回的數據是否成功 |
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
public class RedPackService{ /** * 紅包接口地址 */ private final static String REDP_ORDER_PATH= "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack" ; /** * 紅包 * 需要證書 * @param paramXml * @return */ public static String redpackOrder(String paramXml){ try { WXBaseService service= new WXBaseService(REDP_ORDER_PATH); return service.sendPost(paramXml); } catch (Exception e) { log.error(e.toString()); } return null ; } } /** * 通過Https往API post xml數據 * * @param url API地址 * @param xmlObj 要提交的XML數據對象 * @return API回包的實際數據 * @throws IOException * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public String sendPost(String url, String postDataXML) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException { if (!hasInit) { init(); } String result = null ; HttpPost httpPost = new HttpPost(url); //解決XStream對出現雙下劃線的bug // XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_"))); //將要提交給API的數據對象轉換成XML格式數據Post給API // String postDataXML = xStreamForRequestPostData.toXML(xmlObj); Util.log( "API,POST過去的數據是:" ); Util.log(postDataXML); //得指明使用UTF-8編碼,否則到API服務器XML的中文不能被成功識別 StringEntity postEntity = new StringEntity(postDataXML, "UTF-8" ); httpPost.addHeader( "Content-Type" , "text/xml" ); httpPost.setEntity(postEntity); //設置請求器的配置 httpPost.setConfig(requestConfig); Util.log( "executing request" + httpPost.getRequestLine()); try { HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity, "UTF-8" ); } catch (ConnectionPoolTimeoutException e) { log.e( "http get throw ConnectionPoolTimeoutException(wait time out)" ); } catch (ConnectTimeoutException e) { log.e( "http get throw ConnectTimeoutException" ); } catch (SocketTimeoutException e) { log.e( "http get throw SocketTimeoutException" ); } catch (Exception e) { log.e( "http get throw Exception" ); } finally { httpPost.abort(); } return result; } |
5.返回的xml看是否成功 由于只充值了1元 前幾天已經測試發送 所以返回如下信息
1
2
3
4
5
6
7
8
9
10
11
12
|
< xml > < return_code > <![CDATA[SUCCESS]]> </ return_code > < return_msg > <![CDATA[帳號余額不足,請到商戶平臺充值后再重試]]> </ return_msg > < result_code > <![CDATA[FAIL]]> </ result_code > < err_code > <![CDATA[NOTENOUGH]]> </ err_code > < err_code_des > <![CDATA[帳號余額不足,請到商戶平臺充值后再重試]]> </ err_code_des > < mch_billno > <![CDATA[1371729102201629220149762756]]> </ mch_billno > < mch_id > <![CDATA[這里是商戶號為了保密刪除了]]> </ mch_id > < wxappid > <![CDATA[微信公眾號appid]]> </ wxappid > < re_openid > <![CDATA[od5qQw8E_LbiAW9sZzuD-2xHtmvx這個是用戶的openid]]> </ re_openid > < total_amount >100</ total_amount > </ xml > |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。