この記事では、JSAPI支払い +参照のテンプレートメッセージの送信に関する関連情報を共有しています。特定のコンテンツは次のとおりです
1。ツール
ツールカテゴリを参照してください:WeChat Pay Javaバージョンのネイティブ支払い
2。パブリックアカウント設定
3。コード実装
OpenID:OpenIDは、ユーザーとパブリックアカウントの間のユニークな兆候です。次のクラスでは、トークンの生成、注文インターフェイスコールの閉じ、構成ファイル情報の取得、およびツールクラスが含まれます。他の記事には特定のコード実装があります。
パッケージcom.zhrd.bussinss.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.util.util.util.util.util.util.util.util.util.itil. java.util.HashMap;import java.util.List;import java.util.Map;import javax.net.ssl.SSLContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import apache.http.httpentity; import org.apache.http.client.methods.closablehttpresponse; Import org.apache.http.client.methods.httppost; Import org.apache.http.conn.conn.sl.sslconnectionsocketory; org.apache.http.conn.ssl.sslcontexts; Import org.apache.http.entity.stringentity; Import org.apache.http.impl.client.closablehttpclient; Import org.apache.http.impl.impl.httpclient; Import; Import; 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.Annotation.Autowired; org.springframework.web.bind.annotation.requestmapping; Import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.ansponsebody; import org.springframework.web.notation. anntomation.Restcontrull com.zhrd.bussinss.platform.bo.jspay;インポートcom.zhrd.bussinss.platform.bo.payhist; Import com.zhrd.bussinss.platform.constants.payhistorypaystatus; Import com.zhrd.bussinss.platform.constants.payhistorypaytype; com.zhrd.bussinss.platform.service.getweixinaccesstokenservice; Import com.zhrd.bussinss.platform.service.weixinpayservice; Import com.zhrd.bussinss.platform.utils.closeweixinorutils; immort; com.zhrd.bussinss.platform.utils.customizedplopertyplaceholderconfigurer; import com.zhrd.bussinss.platform.weixinpayutils.clientcustomssl;@restcontroller@requestmapping( "/rest/weixinsendmessage" weixinpayservice weixinpayservice; @autowired getWeixinAcsTokenService getWeixinAccesStokenService; Private Static Long StandardTime = 1662652800000L; /** * wechat送信メッセージ * @param request * @param Response * @return */@requestMapping(value = "/weixinsend"、method = requestmethod.get)@responsebodyパブリックオブジェクトweixinsend(httpservletrequest request、httpservletresponse応答、弦楽System.out.println( "===================================================== ============================================================================= ============================================================================= ============================================================================ ============================================================================= ============================================================================= ============================================================================= ============================================================================カスタマイズされたPlaceHolderConfigurer.getContextProperty( "wx.cert")。 sslcontexts.custom()。loadkeymaterial(keystore、 "10061401" .tochararray())。build(); // TLSV1プロトコルのみを許可するSSLConnectionSocketFactory SSLSF = new SSLConnectionSocketFactory(SSLContext、new String [] {"Tlsv1"}、null、sslConnectionSocketSocketFactory.Allow_all_hostname_verifier); closeablehttpclient httpclient = httpclient.custom().setsslsocketfactory(sslsf).build(); // httpget httpget = new // httpget( "https://api.mch.weixin.qq.com/secapi/pay/refund"); //トークンを取得する詳細については、トークンhttppost httppost = new httppost( "https://api.weixin.qqq.com/cgi-bin/message/template/send?access_token ="+getweixinaccestokenservice.accestoken()); Payhist ph = null; List <Map <String、object >> td = weixinpayservice.getTrade(orderno);日付dt = new date(); SimpleDateFormat sdf = new SimpledateFormat( "yyyymmddhhmmss"); string noncestr = sdf.format(dt).toString();日付= new date(); string tredepayno = orderno+string.format( "%10d"、StandardTime -now.getTime())。サブストリング(0、10); System.out.println( "Order Label Orderno =======================================================; System.out.Out.Println(" 10ビットランダム number==================="+String.format("%10d",standardTime - now.getTime()).substring(0, 10)); String price = Math.round(Float.valueOf(td.get(0).get("price").toString())*100)+""; Long timeExpireStrOld = dt.getTime(); //For詳細は、Configurationファイル情報の取得について参照してください。 simpledateformat dtsdf = new simpledateformat( "yyyymmdhhmmss"); system.out.println( "price =="+system.out.println( "timestart ==+noncestrn); jsonobject resultjspay =(jsonobject)getJspay(noncestr "ord"、tradepayno、rice、noncestr、timexpire、openid); resultjspay.getString( "prepayid"); System.out.println( "================= 222PREPAY_ID2222 ======================="+resultJspay.getString( "prepayid")。toString()); List <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> valueparam = new hashmap <string、string>(); ValueParam.put( "value"、td.get(0).get( "BuyName")+"(Mr./ms。)Order"); ValueParam.put( "color"、 "#173177"); map <string、string> valueparam1 = new hashmap <string、string>(); ValueParam1.put( "Value"、Orderno); ValueParam1.put( "color"、 "#173177"); map <string、string> valueparam2 = new hashmap <string、string>(); ValueParam2.put( "Value"、 "Smart Community Love Fresh Order"); ValueParam2.put( "color"、 "#173177"); map <string、string> valueparam3 = 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( "value"、 "wait for payment"); ValueParam4.put( "color"、 "#173177"); map <string、string> valueparam5 = new hashmap <string、string>(); ValueParam5.put( "Value"、 "Click to pay"); 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( "arem"、valueparam5); data.Add(FirstParam); jspay jp = new jspay(); jp.settouser(openid); jp.settemplate_id( "miexd4-4uqrfmdjnvqmjh0egfypm16r5dpdt6pgg"); jp.settopcolor( "#173177"); jp.seturl( "http://パブリックアカウント設定のリンク/weixin_jspay/weixinjspay/init.action?packagevalue ="+resultjspay.getString( "preayid")。toString()); jp.setdata(data); 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、refundfee、noncestr); {System.out.println( "data ============================================================================================================================= client -customsSl.RefundNativePackage(weixinrefundservice.gettradepayno、system.out.println) httpentity enterty.getContent.getContent(); len ++} close(); jsonobject.fromobject(new String(b、0、len)); ph.settradepayurl( ""); Ph.SetPaytradeno(Orderno); ph.settradepayno(tredepayno); Ph.SetPayStatus(PayHistoryPayStatus.Wechat_Pay_status_Wait); ph.setPayType(PayHistoryPayType.Wechat_js_Pay);リスト<Payhist> PayhistList = weixinpayservice.getPayhist(orderno、 "wechat"、 ""); if(payhistlist == null || payhistlist.size()== 0){weixinpayservice.addpayhist(ph); } else {//閉じる注文の詳細については、注文のキャンセルに関する記事を参照してください。 jsonobject strstatus =(jsonobject)closeweixinordutils.closeweixinorder(fayhistlist.get(0).gettradepayno()); if(strstatus.getString( "status")。equals( "success")){system.out.println(ph.gettradepayno()); weixinpayservice.updatepayhist(ph); }}} return result; } entityutils.consume(entity); }最後に{ResponseTentry.Close(); }}最後に{httpclient.close(); } nullを返します。 } catch(Exception e){e.printstacktrace(); jsonObject result = new jsonobject(); result.put( "status"、 "error"); result.put( "msg"、e.getmessage());返品結果; }} public staticオブジェクトgetJspay(string noncestr、string orderdescribe、string orderno、文字列価格、string timestart、string timeexpire、string openid){try {keystore keystore = keystore.getinstance( "pkcs12"); fileInputStream entream = new FileInputStream(new File(customizedPropertyPlaceHolderConfigurer.getContextProperty( "wx.cert")。toString())); try {keystore.load(instream、 "10061401" .tochararray()); }最後に{enterstream.close(); } //信頼しているCAおよびすべての自己署名証明書SSLCONTEXT SSLCONTEXT = SSLCONTEXTS.CUSTOM()。loadKeymaterial(keystore、 "email" .tochararray())。build(); // TLSV1プロトコルのみを許可するSSLConnectionSocketFactory SSLSF = new SSLConnectionSocketFactory(SSLContext、new String [] {"Tlsv1"}、null、sslConnectionSocketSocketFactory.Allow_all_hostname_verifier); closeablehttpclient httpclient = httpclient.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/unidedorder"); string xml = client -customssl.createjsapipackage(noncestr、orderdescribe、orderno、rice、timestart、timexpire、openid); try {Stringentity SE = new Stringentity(XML); httppost.setentity(se); system.out.println( "requestの実行" + httppost.getRequestline()); CLOSEABLEHTTPRESPONSE RESPONSENENTRY = HTTPCLIENT.EXECUTE(HTTPPOST); try {httpentity entity = responsentry.getEntity(); System.out.println("----------------------------------------"); system.out.println(ResponseTentry.getStatusline()); if(entity!= null){system.out.println( "応答コンテンツ長:" + entity.getContentLength()); saxreader saxreader = new saxreader(); document document = saxreader.read(entity.getContent());要素rootelt = document.getRootelement(); documentxml = documenthelper.parsetext(xml);要素rooteltxml = documentxml.getRootelement(); System.out.println( "root node:" + 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( "========================================================================================= result.put( "prepayid"、rootelt.elementText( "prepay_id")); result.put( "sign"、rooteltxml.elementText( "sign")); result.put( "status"、 "success"); result.put( "msg"、 "success"); } else {result.put( "status"、 "false"); result.put( "msg"、rootelt.elementText( "err_code_des")); } return result; } entityutils.consume(entity); }最後に{ResponseTentry.Close(); }}最後に{httpclient.close(); } nullを返します。 } catch(Exception e){e.printstacktrace(); jsonObject result = new jsonobject(); result.put( "status"、 "error"); result.put( "msg"、e.getmessage());返品結果; }}} 4。weixin_jspayプロジェクトのコード実装制御レイヤーコード
パッケージcom.weixin.jspay.controller; import javax.servlet.http.httpservletrequest; Import javax.servlet.http.httpservletresponse; Import org.springframework.streeotype.controller; Import org.springframework.web.bind.annotation. springframework.web.bind.annotation.requestmethod;@controller@requestmapping( "/weixinjspay")public class weixinjspaycontroller {@requestmapping(value = "/init"、method = requestmethod.get)public string init、httpsrequest request、httpservletedpedreconse、httpsrequest request string {system.out.println( "=================== System.out.println( "packageValue =============================================================== system.out.println( "paysign ================================================================================= request.setattribute( "packagevalue"、 "prepay_id =" + packagevalue); request.setattribute( "Paysign"、Paysign); System.out.println( "================= 「weixin」を返します。 }}
JSPコード
<%@ page Language = "Java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> < "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <script type =" text/javascript "src ="/weixin_jspay/js/md5.js "> </script> <script =" javascript "> windolololy '$ {packageValue}'; var paysign = '$ {paysign}'; alert( "packagevalue ========="+packageValue); alert( "paysign ===================================== var signString = "appid = publicアカウント&noncestr = random string&package ="+packagevalue+"&paysign ="+paysign+"&signtype = md5&timestamp = time"; // alert(signstring); var md5signvalue =( "" + cryptojs.md5(signstring))。touppercase(); // alert(md5signvalue); weixinjsbridge.invoke( 'getbrandwcpayrequest'、{"appid": "<span style =" font-family:arial、helvetica、sans-serif; ">パブリックアカウント</span>"、 "Timestamp": "1395712654"、 "Package": "123456": "1395712654": "1395712654" 「MD5」、「PAYSIGN」:MD5SIGNVALUE}、function(res.err_msg); 「get_brand_wcpay_request:cancel "){alert(" user cancelation painy "); </body> </html>Wechat Payment Md5.js:Md5.jsおよびWechat Payment Development Document:ダウンロードアドレス
この記事は「JavaScript Wechat Development Skillsの要約」にまとめられており、誰もが学習して読むことを歓迎します。
「Wechat Mini Program Development Tutorial」の編集者が皆のために慎重にコンパイルしているWechatアプレットに関するチュートリアルをお勧めします。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。