Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Java Wechat official account payment developer how to realize cash red packet

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "java Wechat official account payment development how to achieve cash red envelope", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "java Wechat official account payment development how to achieve cash red envelope" this article.

Let's first take a look at the effect of official accounts handing out cash red envelopes:

The API of the merchant platform needs to be called. The rules for issuing the API are as follows:

1. Send frequency limit-default 1800/min

two。 Maximum number of messages sent-calculated according to the default 1800/min

3. Upper limit of amount-depending on the default limit of id for different scenarios, you can set and apply in the product settings of merchant platform, with a maximum of no more than 4999 CNY / unit.

4. What are the other "quantity" restrictions? -- the maximum number of times users receive on the day. The default is 10.

5. If the quantity can not meet our needs, how to raise each upper limit? -- the upper limit of the amount and the number of times users receive on the same day can be set on the merchant platform.

Note-when the amount of red packet is greater than 200, the request parameter scene_id must be passed. For more information on the parameters, please see below.

Note 2-according to the regulatory requirements, new applicants need to meet two conditions for using cash red packets: 1, the residence time is more than 90 days, and 30 days of continuous normal transactions.

Request Url https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack

Whether a certificate is required (for details of the certificate and instructions for use, please see the merchant certificate)

Request method POST

Example of request data:

Posttime%3d123123412%26clientversion%3d234134%26mobile%3d122344545%26deviceid%3dIOS

The API needs to call the certificate of the merchant platform, which needs to be downloaded from the merchant platform:

Then use the certificate in the interface. First, we create a new WeixinSSL class.

@ Componentpublic class WeiXinSSL {/ * Certificate Type * / @ Value ("${werchant.storekey}") private String storekey; / * File path * / @ Value ("${werchant.ssLfile}") private String ssLfile; / * Merchant number * / @ Value ("${werchant.merchantNumber}") private String merchantNumber; public String getStorekey () {return storekey } public void setStorekey (String storekey) {this.storekey = storekey;} public String getSsLfile () {return ssLfile;} public void setSsLfile (String ssLfile) {this.ssLfile = ssLfile;} public String getMerchantNumber () {return merchantNumber;} public void setMerchantNumber (String merchantNumber) {this.merchantNumber = merchantNumber;}}

Encapsulate HttpClientSSL class to implement https request to add certificate:

@ Componentpublic class HttpClientSSL {@ Autowired private WeiXinSSL weiXinSSL; / / request timeout (Ms) 5 seconds public static RequestConfig requestConfig; / / response timeout (Ms) 60 seconds public static int HTTP_RESPONSE_TIMEOUT = 60 * 1000; / / httpClient character encoding public static String encoding = "UTF-8"; public static RequestConfig getRequestConfig () {return RequestConfig.custom (). SetConnectTimeout (5 * 1000) .setConnectionRequestTimeout (HTTP_RESPONSE_TIMEOUT). Build () } public static void setRequestConfig (RequestConfig requestConfig) {HttpClientSSL.requestConfig = requestConfig;} / * https request forgery certificate * @ return * / public CloseableHttpClient defaultSSLClient () {SSLContext sslContext = null; try {new SSLContextBuilder () .loadTrustMaterial (null,new TrustStrategy () {@ Override public boolean isTrusted (X509Certificate [] chain, String authType) throws java.security.cert.CertificateException {return false) }});} catch (NoSuchAlgorithmException | KeyStoreException e) {e.printStackTrace ();} SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory (sslContext); return HttpClients.custom (). SetSSLSocketFactory (factory). Build ();} / * * https request to add certificate * @ return * / public CloseableHttpClient defaultSSLClientFile () {if (this.weiXinSSL = null) {return this.defaultSSLClient ();} FileInputStream inputStream = null KeyStore keyStore = null; try {/ / ssl type keyStore = KeyStore.getInstance (weiXinSSL.getStorekey ()); / / ssl file inputStream = new FileInputStream (weiXinSSL.getSsLfile ()); / / set ssl password keyStore.load (inputStream,weiXinSSL.getMerchantNumber (). ToCharArray ());} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException E1) {e1.printStackTrace () } finally {try {inputStream.close ();} catch (IOException e) {e.printStackTrace ();}} SSLContext sslContext = null; try {sslContext = SSLContexts.custom (). LoadKeyMaterial (keyStore,weiXinSSL.getMerchantNumber (). ToCharArray ()). Build ();} catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {e.printStackTrace () } SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory (sslContext, new String [] {"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); return HttpClients.custom (). SetSSLSocketFactory (factory). Build ();} / * * Encapsulation method for sending requests * @ throws UnsupportedEncodingException * / public String send (String url, String data, CloseableHttpClient closeableHttpClient) throws UnsupportedEncodingException {CloseableHttpClient client = closeableHttpClient HttpPost httpPost = new HttpPost (URLDecoder.decode (url, encoding)); httpPost.addHeader ("Connection", "keep-alive"); httpPost.addHeader ("Accept", "* / *"); httpPost.addHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); httpPost.addHeader ("Host", "api.mch.weixin.qq.com"); httpPost.addHeader ("X-Requested-With", "XMLHttpRequest") HttpPost.addHeader ("Cache-Control", "max-age=0"); httpPost.addHeader ("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"); httpPost.setConfig (this.getRequestConfig ()); / / set the timeout CloseableHttpResponse response = null; / / parameter into StringEntity entity = new StringEntity (data, encoding); entity.setContentEncoding (encoding); entity.setContentType ("application/xml") HttpPost.setEntity (entity); try {response = client.execute (httpPost); if (response.getStatusLine (). GetStatusCode () = 200) {HttpEntity httpEntity = (HttpEntity) response.getEntity (); if (response! = null) {return EntityUtils.toString (httpEntity,encoding);}} catch (IOException e) {e.printStackTrace ();} return null;}}

In this way, we encapsulate an entity class with a https request with a certificate, and then we generate the request WeChat red packet API:

Parameter signature of https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack:

/ * Red packet parameter entity class * @ throws UnsupportedEncodingException * / @ Componentpublic class SendRedPack implements Serializable {/ * / private static final long serialVersionUID =-1000489228099916099L; private String nonce_str;// random string private String sign;// signature private String mch_billno;// merchant order number private String mch_id;// merchant number private String wxappid;// public account private String send_name / / merchant name private String re_openid;// user private int total_amount;// payment amount unit: total number of private int total_num;// red packets issued private String wishing;// red packet blessing words private String client_ip;// Ip address private String act_name;// activity name private String remark;// remarks public String getNonce_str () {return nonce_str } public void setNonce_str (String nonce_str) {this.nonce_str = nonce_str;} public String getSign () {return sign;} public void setSign (String sign) {this.sign = sign;} public String getMch_billno () {return mch_billno;} public void setMch_billno (String mch_billno) {this.mch_billno = mch_billno;} public String getMch_id () {return mch_id } public void setMch_id (String mch_id) {this.mch_id = mch_id;} public String getWxappid () {return wxappid;} public void setWxappid (String wxappid) {this.wxappid = wxappid;} public String getSend_name () {return send_name;} public void setSend_name (String send_name) {this.send_name = send_name;} public String getRe_openid () {return re_openid } public void setRe_openid (String re_openid) {this.re_openid = re_openid;} public int getTotal_amount () {return total_amount;} public void setTotal_amount (int total_amount) {this.total_amount = total_amount;} public int getTotal_num () {return total_num;} public void setTotal_num (int total_num) {this.total_num = total_num } public String getWishing () {return wishing;} public void setWishing (String wishing) {this.wishing = wishing;} public String getClient_ip () {return client_ip;} public void setClient_ip (String client_ip) {this.client_ip = client_ip;} public String getAct_name () {return act_name;} public void setAct_name (String act_name) {this.act_name = act_name } public String getRemark () {return remark;} public void setRemark (String remark) {this.remark = remark;}}

Next is the controller that sends the red packet:

/ * * Red packet Controller * @ author zengliang * / @ Controller@RequestMapping (value= "/ redenveLopesReceive") public class RedEnvelopesReceiveController {/ / Wechat unique ID @ Value ("${weixin.appid}") private String appid; / / Wechat developer password ID @ Value ("${weixin.appsecret}") public String appsecret; @ Autowired private SendRedPack sendredpack; @ Autowired private HttpClientSSL httpclientssl / * * send XML parameter * @ author zengliang * / @ ResponseBody @ RequestMapping (value= "/ sendXml") public String sendXml (String openid,Long redenveLopes_id, String mch_billno) {RedenveLopes redenve = redenveLopesService.findOne (redenveLopes_id); XMLUtil xmlUtil= new XMLUtil (); sendredpack.setAct_name (redenve.getAct_name ()); sendredpack.setNonce_str (xmlUtil.random ()); sendredpack.setRe_openid (openid) Sendredpack.setClient_ip (redenve.getClient_ip ()); sendredpack.setMch_billno (mch_billno); sendredpack.setMch_id (redenve.getMch_id ()); String xx = redenve.getRemark (); sendredpack.setRemark (StringUtils.isEmpty (xx) = = false?xx: "empty"); sendredpack.setSend_name (redenve.getSend_name ()); sendredpack.setTotal_amount (redenve.getTotal_amount ()); sendredpack.setTotal_num (redenve.getTotal_num ()) Sendredpack.setWishing (redenve.getWishing ()); sendredpack.setWxappid (redenve.getWxappidxx ()); / / generate signature String params = this.createSendRedPackOrderSign (sendredpack,redenve.getStore_key ()); sendredpack.setSign (params); xmlUtil.xstream (). Alias ("xml", sendredpack.getClass ()); / / extend xstream to support CDATA blocks String requestXml = xmlUtil.xstream (). ToXML (sendredpack); String result Try {result = httpclientssl.send ("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack",requestXml,httpclientssl.defaultSSLClientFile()); System.out.println (" successful return value + result "); return result;} catch (UnsupportedEncodingException e) {e.printStackTrace ();} return null } / * generate signature * @ param redPack * @ return * / public String createSendRedPackOrderSign (SendRedPack redPack,String storekey) {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 (storekey); return DigestUtils.md5Hex (sign.toString ()). ToUpperCase ();}}

Then we need to parse the XML returned by Wechat with a utility class that parses XML

/ * * parse XML utility class * @ author zengliang * / @ Componentpublic class XMLUtil {* parse XML * @ param xml * @ return * @ throws Exception * / @ SuppressWarnings ("unchecked") public Map parseXml (String xml) throws Exception {Map map = new HashMap (); Document doc = null; try {doc = DocumentHelper.parseText (xml) / / convert the string to XML Element rootElt = doc.getRootElement (); / / get the root node List list = rootElt.elements (); / / get all nodes under the root node for (Element element: list) {/ / traversal node map.put (element.getName (), element.getText ()) / / the key,text of the node whose name is map is value of map}} catch (DocumentException e) {e.printStackTrace ();} catch (Exception e) {e.printStackTrace ();} return map } / * extend xstream to support CDATA block * / private XStream xstream = new XStream (new XppDriver (new NoNameCoder () {@ Override public HierarchicalStreamWriter createWriter (Writer out) {return new PrettyPrintWriter (out) {/ / add the CDATA tag boolean cdata = true to the conversion of all xml nodes @ Override @ SuppressWarnings ("rawtypes") public void startNode (String name, Class clazz) {super.startNode (name, clazz);} @ Override public String encodeNode (String name) {return name } @ Override protected void writeText (QuickWriter writer, String text) {if (cdata) {writer.write (");} else {writer.write (text);};}}) Private XStream inclueUnderlineXstream = new XStream (new DomDriver (null,new XmlFriendlyNameCoder ("_ -", "_")); public XStream getXstreamInclueUnderline () {return inclueUnderlineXstream;} public XStream xstream () {return xstream;} / * * generate random number * @ return * / public String random () {String random = UUID.randomUUID (). ToString (). Replace ("-", "); return random;}}

Then we can send red packets to the user by calling the official account of the sendXML method.

The above is all the contents of the article "how to achieve cash red envelopes in the development of java Wechat official account". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report