Récemment, le projet nécessite un paiement WeChat, puis j'ai examiné le paiement officiel de WeChat. Bien que ce ne soit pas difficile, les détails doivent encore être prêts attention. J'ai passé la majeure partie de la journée à écrire une démo et à tester complètement le processus de paiement. Partageons l'expérience du paiement officiel de WeChat ci-dessous.
1. Configurer le paiement du compte officiel
Nous devons configurer l'adresse de paiement officiel de WeChat et tester la liste blanche.
Par exemple: l'adresse de la page JS de paiement est http://www.xxx.com/shop/pay/
Ensuite, voici www.xxx.com/shop/pay/
2. Processus de développement
Empruntez le compte officiel de WeChat pour payer l'API (adresse http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=7_4), que nous devons développer est marqué en rouge. comme suit:
3. Passez une commande avec le serveur WeChat
Appelez l'interface unique unifiée afin que vous puissiez obtenir le prépaiement_id de WECHAT Payment (http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=9_1).
Avant d'appeler cette interface, il y a plusieurs champs qui sont OpenIDS qui doivent être remplis pour le paiement H5.
3.1 OpenId
Vous pouvez utiliser le formulaire d'autorisation Web (http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html)
Envoyez le lien suivant dans WeChat
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=url&response_type=code&scope=SnSapi_Base&state=123#wechat_redIrect
3.2 Placez une commande pour obtenir un prépaiement_id
Le code est le suivant, qui envoie réellement un fichier XML via la publication pour obtenir le prepay_id envoyé à partir du serveur WeChat.
Importer java.io.ByteArrayInputStream; Importer JavaioIoIoException; Importer JavaioInputStream; Importer JavaiounsupportEnCodingException; importer javauddate; Importer JavautilhashMap; importer Javautiliterator; importer javautilmap; importer javautilmapentry; importer javautilrandom; Importer JavaxServLethTTPHTTTPServLetRequest; Importer JavaxServLethTTPHTTTPServletResponse; import orgapachecommonscodecdigestdigestUtils; import orgspringframeworkstereotypeController; import orgspringframeworkwebbindannotationRequestMapping; import orgxmlpullvxmlpullParser; import orgxmlpullvxmlpullParsErexception; import orgxmlpullvxmlpullParserFactory; Importer ComfasterXmljackSondatAbindjSonNode; Importer ComgsonoAuthoAuth; importer comgsonoauthpay; import comgsonutilhttpkit; Importer ComSyutildateTimeutil; importer comsyutiljsonutil; @Controller @RequestMapping ("/ Pay") public class wxpayController {@RequestMapping (value = "wxprepaydo") public void jspay (httpSservletRequest request, httpServletResponse réponse, string callback) lance l'exception {// get openId String OpenID = sessionUtLegetAtt (request, "openID"); if (openId == null) {openId = getUserOpenID (request); } String appid = "wx16691fcb0523c1a4"; String Paternerkey = "ININGFENG1234567FDFWFDFD1SS234567"; String out_trade_no = getTradeno (); Map <string, string> paramap = new hashmap <string, string> (); paramapput ("appid", appid); paramapput ("attacher", "test"); paramapput ("corps", "test d'achat de test"); paramapput ("mch_id", "10283271"); paramapput ("nonce_str", create_nonce_str ()); ParamApput ("OpenID", OpenID); paramapput ("out_trade_no", out_trade_no); ParamApput ("SPBILL_CREATE_IP", getAdDrip (demande)); paramapput ("total_fee", "1"); ParamApput ("Trade_Type", "JSAPI"); paramapput ("notify_url", "http: // wwwxxxco / bank / page / wxnotify"); String Sign = getSign (paramap, Paternerkey); paramapput ("signe", signe); // Ordre unifié https: // apimchweixinqcom / pay / unifieDorder String url = "https: // apimchweixinqcom / pay / unifieDorSor"; String xml = arraytoxml (paramap); String xmlstr = httpkitPost (URL, xml); // chaîne d'ID de produit prépayée prépay_id = ""; if (xmlStIndexof ("Success")! = -1) {map <string, string> map = doxmlparse (xmlstr); prepay_id = (string) mapget ("prepay_id"); } Map <string, string> PayMap = new HashMap <String, String> (); PayMapput ("appid", appid); PayMapput ("TimeStamp", Create_timestamp ()); PayMapput ("nonCestr", create_nonce_str ()); PayMapput ("SignType", "MD5"); PayMapput ("package", "prepay_id =" + prepay_id); String paysign = getSign (PayMap, Paternerkey); PayMapput ("PG", Préparer_id); PayMapput ("paysign", paysign); WebutilResponse (réponse, webutilpackjsonp (callback, jsonUtilwarpjsonNoDeResSon (jsonUtilObjectTojsonNode (PayMap)) toString ())); } / ** * Map à xml * * @param arr * @return * / public String arraytoxml (map <string, string> arr) {String xml = "<xml>"; Iterator <entrée <string, string >> iter = arrentrySet () iterator (); while (iterHasnext ()) {entrée <string, string> entry = iterNExt (); String key = entryGeTey (); String val = entryGeTValue (); xml + = "<" + key + ">" + val + "</" + key + ">"; } xml + = "</ xml>"; retour xml; } // Get OpenId Private String getUserOpenID (demande httpServleRequest) lance l'exception {String code = requestGetParameter ("code"); if (code == null) {string openId = requestGetParameter ("openId"); return openId; } OAuth o = new oAuth (); String token = ogetToken (code); JSONNODE Node = JSONUtilStringTojSonNode (Token); String openId = nodeget ("openId") astext (); return openId; } chaîne privée create_nonce_str () {String Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String res = ""; for (int i = 0; i <16; i ++) {random rd = new random (); res + = charsCharat (rdNextint (charsLength () - 1)); } return res; } chaîne privée getAdDrip (requête httpsservletRequest) {return requestGetRoMoteaddr (); } chaîne privée create_timestamp () {return longToString (systemCurrentTimemillis () / 1000); } String privé getTradeno () {String TimeStamp = DateTimeUtilFormatDate (new Date (), DateTimeUtilDateTime_Pattern); retourner "hzno" + horodatage; } private String getsign (map <string, string> Params, String Paternerkey) lève unportdencodingException {String String1 = PayCreatSign (params, false); String stringSignTemp = String1 + "& key =" + PaternerKey; String SignValue = digestUtilSMD5HEX (StringSignTemp) ToupperCase (); return SignValue; } Private Map <String, String> doxmlParse (String xml) lève xmlPullParseRexception, ioException {inputStream inputStream = new ByTeRayInputStream (xmlGetBytes ()); Map <string, string> map = null; XmlPullParser pullParser = xmlPullParserFactoryNewInstance () newPullParser (); PullParseSeSeTinput (InputStream, "UTF-8"); // Définissez les données XML à analyser pour XML int EventType = pullParserGetEventType (); while (eventType! = xmlPullParseRend_Document) {switch (EventType) {case xmlpullParserSERSTart_Document: map = new hashmap <string, string> (); casser; Case xmlPullParserSERSTART_TAG: String key = pullParserGetName (); if (keyequals ("xml")) casser; String value = pullParserNextText (); Maput (clé, valeur); casser; cas xmlpullParserend_tag: break; } eventType = pullParserNext (); } retour de la carte; }}4. H5 Paiement
Le paiement H5 est en fait très simple. Il vous suffit d'appeler la méthode JS du navigateur intégré WeChat (http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=7_7)
<% @ Page Language = "Java" ContentType = "Text / Html; charSet = UTF-8" Pageencoding = "UTF-8"%> <% @ Taglib Prefix = "Spring" URI = "http: // wwwspringframeworkorg / tags"%> <% String path) String basepath = requestgetscheme () + ": //" + requestGetServerName () + ":" + requestGetServerport () + path + "/"; %> <! Doctype html public "- // w3c // dtd html 01 transitional // en" "http: // wwworg / tr / html4 / loosedtd"> <html> <adworg> <meta charset = "utf-8" /> <méta-name = "Viewport" contenu = "width = device-width, initial-sec = 0," width = device-width = 0, 0, "width = width = device-width, initial = 0," width = devineth = 0, 0, "width = devineth = 0, 0," width = width = Device-width, initial-scy maximum-scale = 0, user-scalable = 0 "/> <meta name =" Apple-mobile-web-app-capable "contenu =" oui "/> <meta name =" Apple-Mobile-web-app-statut-style "contenu =" noir "/> <meta name =" Apple-Mobile-web-app-stat-style "content =" Black "/> <META-DETTECT content = "téléphone = no" /> <itle> test de paiement </ title> <link href = "/ css / csss? v = 0" rel = "stylesheet" type = "text / css"> </ head> <body> <div> <v> wechat js test de paiement </ div> <v> <ul> <li> <pan> Test des informations de paiement </pandé> </ li> </ ul> <p> <p> <span> Test des informations de paiement </pande> href = "javascript: pay ();"> payer maintenant </a> </p> </ div> </ div> <script type = "text / javaScript" src = "/ js / zeptominjs"> </ script> <script type = "text / javascript" src = "/ js / communicyjs"> </cript> <script type = "text / javascrip UrlParameter ("appid"); var horodatramp = urlParamètre ("horodat"); var noncestr = urlParamètre ("nonCest"); var pg = urlparamètre ("pg"); var SignType = urlParamètre ("signalpe"); var paysign = urlParamètre ("paysign"); fonction onBridgeready () {weixinjsbridgeinvoke ('getBrandwcpayRequest', {"appid": appid, // le nom du compte officiel, passé en "horodat": horodat Méthode SignType, // WECKAT Signature: "Paysign": Paysign // WECKAT Signature}, fonction (res) {if (reserr_msg == "get_brand_wcpay_request: OK") {alert ("Payer réussi"); réussit, mais il ne garantit pas qu'il est absolument fiable. } function pay () {if (typeof weixinjsbridge == "undefined") {if (documentAdDeventListener) {documentAdDeventListener ('weixinjsbridgeready', onBridGeread, false); } else if (documentAttachevent) {documentAttachevent ('weixinjsbridgeready', onBridGeready); DocumentAttachevent ('onweixinjsbridgeready', onBridgeready); }} else {onBridgerAy (); }} </ script> </ body> </html> L'effet est le suivant
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.