Cet article partage des informations pertinentes sur le paiement JSAPI + les messages de modèle d'envoi pour votre référence. Le contenu spécifique est le suivant
1. Outils
Voir la catégorie des outils: WeChat Pay Java Version du paiement natif
2. Paramètres de compte public
3. Implémentation du code
OpenID: OpenID est l'indication unique entre l'utilisateur et le compte public. Les classes suivantes impliquent la génération de jetons, la fermeture des appels d'interface de commande, l'obtention d'informations de fichier de configuration et les classes d'outils. Il existe des implémentations de code spécifiques dans d'autres articles.
package com.zhrd.bussins.platform.controller.rest; import java.io.file; import java.io.fileinputstream; import java.io.inputstream; import java.security.keystore; import java.text.simpledateFormat; import java.util.arraylist; import java.util.date; import; java.util.hashmap; import java.util.list; import java.util.map; import javax.net.ssl.sslcontext; import javax.servlet.http.httpservletRequest; importation navax.sf.json.json. org.apache.http.httpentity; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.sslconnection socketfactory; importation; import; org.apache.http.oncon org.apache.http.util.entityutils; import org.dom4j.document; import org.dom4j.documenthelper; import org.dom4j.element; import org.dom4j.io.saxreader; import org.springframework.beans.factory.annotation.autowired; Import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestMethod; import org.springframework.web.bind.annotation.Responsebody com.zhrd.bussins.platform.bo.jspay; import com.zhrd.bussinss.platform.bo.payhist; import com.zhrd.bussins.platform.constants.payhistorypaystatus; import com.zhrd.bussins.platform.constants.payhistorypaytype; com.zhrd.bussins.platform.service.getweixinaccesstokenService; import com.zhrd.bussins.platform.service.weixinpayservice; import com.zhrd.bussins.platform.utils.closeweixinOrderUtils; import; com.zhrd.bussins.platform.utils.customatedPropertyPlaceHolderConfigurer; import com.zhrd.bussins.platform.weixinpayutils.clientcustomssl; @ restController @ requestmapping ("/ rest / weixeSessage") weixinsendmessagerestfulController { WeixinPayService; @Autowired getweixinAccessTokenService getweixinaccesstokenService; Standard standard statique privé = 1662652800000L; / ** * WeChat Envoyer un message * @param demande * @param réponse * @return * / @requestmapping (value = "/ weixinsend", méthode = requestMethod.get) @ResponseBody Object Public Object WeixinSend (HttpServletRequest Request, httpservletResponse Réponse, String OrderNo, String OpenID) { System.out.println ("========================================================= ============================================================================. ============================================================================. ===============================================================================. ============================================================================. ============================================================================. ============================================================================. ===============================================================================. PersumedPropertyPlaceHolderConfigurer.getContextProperty (WX.CERT "). TOSTRING ()); SslContex.custom (). LoadKeyMaterial (Keystore, "10061401" .toCharArray ()). Build (); // Autoriser le protocole TLSV1 uniquement SSLConnectionSocketFactory SSLSF = new SSLConnectionSocketFactory (sslContext, new String [] {"tlsv1"}, null, sslconnections bancarfactory.allow_all_all_hostname_verifier); CloseableHttpClient httpClient = httpClients.Custom () .SetsSLSocketFactory (sslsf) .build (); // httpget httpget = new // httpget ("https://api.mch.weixin.qq.com/secapi/pay/refund"); // Pour plus de détails sur l'obtention de jetons, consultez l'article sur l'obtention du token httppost httppost = new httppost ("https://api.weixin.qq.com/cgi-bin/mesage/template/send?access_token=" + getweixinaccesstokenShip.AccessToken ()); PHIST PAYHIST PH = NULL; List <map <string, objet >> td = weixinpayservice.getTrade (orderNo); Date dt = new Date (); SimpledateFormat sdf = new SimpledateFormat ("yyyymmddhhmmss"); String nonCestr = sdf.format (dt) .toString (); Date maintenant = new Date (); String TradePayNo = OrderNo + String.Format ("% 10D", StandardTime - Now.GetTime ()). Substring (0, 10); System.out.println ("Order Label OrderNo ============================================================================= numéro =================== "+ string.format ("% 10d ", standardtime - maintenant.getTime ()). substring (0, 10)); string price = math.round (float.valueof (td.get (0) .get (" Price "). Tostring () * 100)" "; Veuillez vous référer à l'article sur l'obtention d'informations sur le fichier de configuration. SimpledateFormat ("yyyymmddhhmms"); String TimeExpire = DTSDF.Format (DttimeExPire) .toString (); System.out.println ("timestart ==" + nonCest); JSONObject resultJSpay = (JSONObject) getJSpay (noncestr, "Order", TradePayNo, Price, NONCESTR, TimeExpire, OpenID); resultJspay.getString ("prepayid"); System.out.println ("================ 222PREPAY_ID222 ===========================" + ResultJspay.getString ("AdPayId"). TOSTRING ()); Liste <map <string, map <string, string >>> data = new ArrayList <map <string, map <string, string >>> (); Map <string, map <string, string >> firstParam = new hashmap <string, map <string, string >> (); Map <string, string> vallueparam = new hashmap <string, string> (); ValueParam.put ("Value", td.get (0) .get ("Buyername") + "(Mr./ms.) Order"); vallueparam.put ("couleur", "# 173177"); Map <string, string> vallueparam1 = new hashmap <string, string> (); vallueparam1.put ("valeur", ordonnance); ValueParam1.put ("Color", "# 173177"); Map <string, string> valueparam2 = new hashmap <string, string> (); ValueParam2.put ("Valeur", "Smart Community Love Fresh Order"); ValueParam2.put ("Color", "# 173177"); Map <string, string> vallueparam3 = new hashmap <string, string> (); ValueParam3.put ("Value", td.get (0) .get ("Price") + "Meta"); ValueParam3.put ("Color", "# 173177"); Map <string, string> valueparam4 = new hashmap <string, string> (); ValueParam4.put ("valeur", "attendre le paiement"); ValueParam4.put ("Color", "# 173177"); Map <string, string> vallueParam5 = new HashMap <String, String> (); vallueparam5.put ("valeur", "cliquez pour payer"); ValueParam5.put ("Color", "# 173177"); FirstParam.put ("First", ValueParam); FirstParam.put ("Keyword1", ValueParam1); FirstParam.put ("Keyword2", ValuEParam2); FirstParam.put ("Keyword3", ValuEParam3); FirstParam.put ("Keyword4", ValuEParam4); FirstParam.put ("Remarque", ValueParam5); data.add (FirstParam); Jspay jp = new jspay (); jp.setTouser (openID); jp.setTemplate_id ("miexd4-4uqrfmdjnvqmjh0egfypm16r5dpdt6p9gpgg"); jp.setTopColor ("# 173177"); jp.setUrl ("http: // lien pour les paramètres du compte public / weixin_jspay / weixinjspay / init.action? packageValue =" + resultjspay.getString ("prepayid"). toString ()); jp.setData (données); JSONObject JSONObject = JSONObject.FromObject (JP); String str = new String (jsonObject.ToString (). GetBytes ("UTF-8"), "ISO8859-1"); // String xml = clientCustomSSL.RefundNativePackage (WeixinRefundService.getTradePayNo (OrderNo), NONCESTR, TOTALFEE, REFUDFEE, NONCESTR); try { System.out.println("data============================================================================================== ClientCustomSSL.RefundnativePackage (WeixinRefundService.getTradePayNo (OrderNo), NONCETR, NONCESTR); Httpentity Entity = réponse. } in.close (); JSONObject.FromObject (new String (B, 0, Len)); Ph.SetTradePayUrl (""); Ph.SetPayTradeno (OrderNo); Ph.SetTradePayno (TradePayNo); Ph.SetPayStatus (PayHistoryPayStatus.wechat_pay_status_wait); Ph.SetPayType (PayHistoryPayType.wechat_js_pay); List <Asshist> PayHistList = weixinpayService.getPayHist (OrderNo, "WeChat", ""); if (payhistList == null || PayHistList.size () == 0) {WeixinPayService.addpayHist (Ph); } else {// Pour plus de détails sur les commandes de clôture, consultez l'article sur l'annulation des commandes. JsonObject strStatus = (jsonObject) closeweixinOrderUtils.closeweixinOrder (PayHistList.get (0) .getTradePayNo ()); if (strStatus.getString ("Status"). Equals ("Success")) {System.out.println (Ph.getTradePayNo ()); weixinpayService.updatePayHist (pH); }}} Retour Résultat; } EntityUtils.consume (entité); } enfin {réponsentry.close (); }} enfin {httpclient.close (); } return null; } catch (exception e) {e.printStackTrace (); JsonObject result = new JSONObject (); result.put ("statut", "erreur"); result.put ("msg", e.getMessage ()); Résultat de retour; }} public static objet getjSpay (String nonCestr, String OrderDescribe, String OrderNo, String Price, String timeStart, String timeExpire, String openId) {try {Keystore keystore = keystore.getInstance ("pkcs12"); FileInputStream InsideRam = new FileInputStream (nouveau fichier (personnaliséPropertyPlaceHolderConfigurer.getContextProperty ("wx.cert"). ToString ())); try {keystore.load (insimem, "10061401" .tocharArray ()); } enfin {enterStream.close (); } // Trust Own CA et tous les certificats auto-signés sslcontext sslContext = sslcontex.custom (). LoadKeyMaterial (keystore, "voir email" .tocharArray ()). Build (); // Autoriser le protocole TLSV1 uniquement SSLConnectionSocketFactory SSLSF = new SSLConnectionSocketFactory (sslContext, new String [] {"tlsv1"}, null, sslconnections bancarfactory.allow_all_all_hostname_verifier); CloseableHttpClient httpClient = httpClients.Custom () .SetsSLSocketFactory (sslsf) .build (); // httpget httpget = new // httpget ("https://api.mch.weixin.qq.com/secapi/pay/refund"); Httppost httppost = new httppost ("https://api.mch.weixin.qq.com/pay/UnifiedOrder"); String xml = clientCustomSSL.CreateJsapipackage (NONCESTR, ORDANDDESCRIME, ORDERNO, Price, TimeStart, TimeExpire, OpenID); try {stritNtity se = new stringEntity (xml); httppost.SetEntity (SE); System.out.println ("Exécution de la demande" + httppost.getRequestline ()); CloseableHttpResponse Responsentry = httpClient.Execute (httppost); try {httpentity entity = réponseTry.getEntity (); System.out.println ("----------------------------------------"); System.out.println (réponsentry.getStatusline ()); if (entité! = null) {System.out.println ("Longueur du contenu de la réponse:" + entité.getContentLength ()); SaxReader saxReader = new saxReader (); Document document = saxReader.read (entity.getContent ()); Element rootElt = document.getRootelement (); Document documentXml = documentHelper.parseText (xml); Élément rootEltxml = documentXml.getRootelement (); System.out.println ("Node racine:" + rootElt.getName ()); System.out.println ("===" + rootElt.ElementText ("result_code")); System.out.println ("===" + rootElt.ElementText ("return_msg")); String resultCode = rootElt.ElementText ("result_code"); JsonObject result = new JSONObject (); if (resultCode.equals ("Success")) {System.out.println ("================ PREPAY_ID =======================================================================================================================================================================================. result.put ("prepayId", rootElt.ElementText ("prepay_id")); result.put ("signe", rootEltxml.ElementText ("signe")); result.put ("statut", "succès"); result.put ("msg", "succès"); } else {result.put ("status", "false"); result.put ("msg", rootElt.ElementText ("err_code_des")); } Retour Résultat; } EntityUtils.consume (entité); } enfin {réponsentry.close (); }} enfin {httpclient.close (); } return null; } catch (exception e) {e.printStackTrace (); JsonObject result = new JSONObject (); result.put ("statut", "erreur"); result.put ("msg", e.getMessage ()); Résultat de retour; }}} 4. Le code de couche de contrôle d'implémentation du code dans le projet WEIXIN_JSPAY
package com.weixin.jspay.controller; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; import org.springframework.sterreotype.contrelleur; import org.springframework.web.bind.annotation.requestmaping; org.springframework.web.bind.annotation.requestMethod; @ contrôleur @ requestmapping ("/ weixinjspay") classe publique weixinjspayController {@RequestMapping (value = "/ initit", méthode = requestMethod.get) public init (httpserverest requers paysign) {System.out.println ("================== 微信 Jspay 开始 ==============="); System.out.println ("PackageValue ==============" + PackageValue); System.out.println ("paysign ====================" + PaySign); request.setAttribute ("packageValue", "prepay_id =" + packageValue); request.setAttribute ("paysign", paysign); System.out.println ("================== 微信 JSPAY 页面跳转开始 ==============="); retourner "Weixin"; }}
Code JSP
<% @ Page Language = "Java" ContentType = "Text / Html; charSet = UTF-8" Pageencoding = "UTF-8"%> <! Doctype HTML Public "- // W3C // DTD HTML 4.01 Transitional // en" "http://www.w3.org/tr/html4/loose.dtd"><html><head><script type =" text / javascrip '$ {packageValue}'; var paysign = '$ {paysign}'; alert ("packageValue ==========" + packageValue); alert ("paysign ===============" + paysign); var signstring = "appid = voir le compte public & nonCestr = Random String & package =" + packageValue + "& paysign =" + paysign + "& signtype = md5 & timestamp = time"; // alerte (sistString); var md5signValue = ("" + cryptojs.md5 (signstring)). touppercase (); // alerte (md5signValue); WeixinJSBridge.invoke('getBrandWCPayRequest',{ "appId" : "<span style="font-family: Arial, Helvetica, sans-serif;">See the public account</span>", "timeStamp" : "1395712654", "nonceStr" : "123456", "package" : packageValue, "signType" : "MD5", "paysign": md5signValue}, fonction (res) {alert (res.err_msg); "get_brand_wcpay_request: annuler") {alert ("Paiement d'annulation de l'utilisateur");} else {alert ("Button Type =" Button "OnClick =" CallPay "). </ body> </html>Paiement WeChat MD5.JS: MD5.JS et WeChat Payment Development Document: Adresse de téléchargement
Cet article a été compilé dans "Résumé des compétences de développement de JavaScript WeChat", et tout le monde est le bienvenu pour apprendre et lire.
Je recommande un tutoriel sur les applets WeChat qui sont très préoccupés maintenant: l'éditeur du "tutoriel de développement de programme WeChat Mini" l'a soigneusement compilé pour tout le monde, j'espère que vous l'aimez.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.