The use of WeChat red envelopes is already very wide. This article introduces examples of sending red envelopes on WeChat. You need a certified public account, and you can open WeChat payment and merchant platform and enable cash red envelope permissions.
https://pay.weixin.qq.com merchant login address. Choose to view the cash red packets in the marketing center
https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1 Official website document description of cash red envelopes
Let’s look at a few simple tests first. The premise is that you need to recharge first on the merchant platform. Prepayment is not supported. This article only summarizes the calls and implementation of the WeChat cash red envelope interface. Specifically, you need to implement how to call this interface based on your own business.
https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3 There are all explanations for ordinary red envelopes in the document. The call must have a certificate from the merchant platform.
The required parameters are also listed. Decide according to your needs.
1.java encapsulate a red envelope object
/** * Red envelope object* @author Xiao Shuai Shuai* @date 2016-8-17 11:12:19 am * @Open Source China http://my.oschina.net/xshuai */public class RedPack implements Serializable{ private String sign; //Verification generated based on attributes private String mch_billno; //Order number private String mch_id; //Merchant number private String wxappid; //WeChat appid private String send_name;// Merchant name private String re_openid;// User openid private String total_amount;// Payment amount private String total_num;//The number of red envelope recipients cash red envelope can only be 1 private String wishing;// Red envelope blessing private String client_ip;// Call the IP of the interface machine private String act_name;// Activity name private String remark;// Remark private String nonce_str;// Random string // Set get omitted} 2. The required tool class createBillNo is to generate the merchant order number. The official website document requirements are as follows:
/** * Red envelope tool class* @author Xiao Shuai Shuai* @date 2016-8-17 11:12:19 am * @Open Source China http://my.oschina.net/xshuai */public class RedPackUtil { /** * Generate merchant order number* @param mch_id Merchant number* @param userId userID of this user * @return */ public static String createBillNo(){ //Composition: mch_id+yyyymmdd+10-digit numbers that cannot be repeated within one day//10-digit numbers that cannot be repeated within one day are as follows: //Because each user is bound to userId, their userId is different, plus the randomly generated (10-length(userId)) can ensure that these 10 digits are different Date dt=new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyymmdd"); String nowTime= df.format(dt); int length = 10 ; return WXConstants.MCH_ID + nowTime + getRandomNum(length); } /** * Generate random numbers with specific digits* @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. The previous work is very simple and requires a certificate and merchant number. And if the merchant platform has an amount, you can test the cash red envelope interface
RedPack pack = new RedPack(null//The first time is empty, RedPackUtil.createBillNo()//Merchant order number, "Your own merchant number", "Appid of the official account", "Name", "Openid of the user to be sent", "The sending amount unit is for example 100, which is RMB 1", "can only be 1", "9", "127.0.0.1", "Activity name", "Note", "Random string");
Except for sign in the test, it is empty. Everything else can be filled. Now we generate a sign signature; generate a sign according to the parameters in the pack object;
Specific signature algorithm https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3 Address given by the official website
https://pay.weixin.qq.com/wiki/tools/signverify/ You can compare it on this test page to see if the encryption is consistent.
String signs = Signature.getSign(pack);//The generated signset is packed into the pack object.setSign(signs);//Convert the object to xml format WeChat requires xml format String xml = XmlUtil.objToXml(pack,RedPack.class,"xml");
4. Send red packets
RedPackService service = new RedPacService(); String result = service.redpackOrder(xml);//Is the data returned by the request successful?
public class RedPackService{ /** * Red Packet Interface Address*/ private final static String REDP_ORDER_PATH="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; /** * Red Packet* Certificate required* @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; }} /** * Go to API post xml data via Https* * @param url API address* @param xmlObj XML data object to submit* @return API return the actual data of the package* @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); //Solve the bug of double underscores for XStream// XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_"))); //Convert the data object to submit to the API into XML format data Post to the API// String postDataXML = xStreamForRequestPostData.toXML(xmlObj); Util.log("API, POST's past data is: "); Util.log(postDataXML); //It must indicate that UTF-8 encoding is used, otherwise the Chinese text to the API server XML cannot be successfully identified StringEntity postEntity = new StringEntity(postDataXML, "UTF-8"); httpPost.addHeader("Content-Type", "text/xml"); httpPost.setEntity(postEntity); //Set the requestor's configuration 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 throw Exception"); } finally { httpPost.abort(); } return result; } 5. The returned xml is successful. Since it only recharged 1 yuan, it has been tested and sent a few days ago. So the following information is returned.
<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[account balance is insufficient, please recharge on the merchant platform and try again]]></return_msg><result_code><![CDATA[FAIL]]></result_code><err_code><![CDATA[NOTENOUGH]]></err_code><err_code_des><![CDATA[account balance is insufficient, please recharge on the merchant platform and try again]]></err_code_des><mch _billno><![CDATA[1371729102201629220149762756]]></mch_billno><mch_id><![CDATA[This is the merchant number deleted for confidentiality]]></mch_id><wxappid><![CDATA[WeChat official account appid]]></wxappid><re_openid><![CDATA[od5qQw8E_LbiAW9sZzuD-2xHtmvx This is the user's openid]]></re_openid><total_amount>100</total_amount></xml>
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.