Recently, the development of the WeChat public account payment has been explored for a few days because it has been done for the first time, and it has only reached the level of implementation function. Essence
The overall payment of the WeChat public account is actually very simple, and it is roughly divided into three steps. The first step needs to be obtained by user authorization; the second step is to call the single interface to obtain the pre -payment ID; the third step H5 adjusts the built -in JS of WeChat payment. The following introduces the development process of each step.
First of all, it is necessary to clarify that the WeChat public account payment is a web version payment, so it is necessary to one step more WeChat authorization than the APP directly retrieved WeChat payment. That is, you need to obtain the user's Openid. The type of transaction used by WeChat public account is JSAPI, so the document of the unified order interface is clearly written to
Therefore, we must get Openid, and at the same time we can handle some logic we need. There are two ways to obtain user authorization: 1.scope = snsapi_base; 2.Scope = snsapi_userinfo. I use snsapi_base
Scope is SNSAPI_BASE
https://open.weixin.qq.com/connect/oAuth2/authorize?appid=wx520c15F417810387&RDirect_uri=http%2FChong.qq.com%2FPHPPHP%2FINDEX.PHP %3fd%3d%26c%3dwxadapter%26m% 3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
Scope is Snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
WeChat's official document also has a detailed explanation of each parameter, and I will carefully explain the key parameters. First of all, the Appid is not much to say that the Appid of your WeChat public account is fixed to death. The Redirect_uri parameter is the most important. This address is the interface address of your processing. You can stitch the parameters you need on this link. Generally, you have to pass the amount of the order to this interface. When you visit this link, WeChat will give you code It performs Urlencode processing. State parameters can be understood as extended fields. Other parameters are fixed writing and do not introduce more. The following is the code clip of OpenID.
// Get OpenID HTTPClientutil Util = httpClientutil.getInstance (); Map <string, Map = New HashMap <string, String> (); Map.put ("APPID", WXPAY Config.appid); MAP.PUT ("Secret ", Wxpayconfig.appsecret); Map.put (" code ", code); Map.put (" Grant_type ", wxpayconfig.Grant_type); String ReturnStr = Util.dopostthstringstring (" H ttps: //api.weixin.qq.com /SNS/OAUTH2/Access_token ", NULL, MAP); Logger.info (" ReturnStr: [" + ReturnStr +"] "); AccessStoken at = JSON.PARSEOBJECT (RETURNSTR, AccessStoken.c Lass);Accesstoken.java
public class accessstoken {private string access_token; private string expires_in; private string; private string openid; Private String e; E; Public String Getaccess_token () {Return Access_token;} Public Void Setacles_tring Access_token_tring cess_token = Access_token;} Public String Getexpires_in () {Return Expires_in;} Public void setexpires_in (string expires_in) {this.expires_in = expires_in; Public String getrefresh_token () {Return Refresh_token;} Public void Setrefresh_token (String Refresh_token) {this.refresh_token = Refresh_token;} Public String Getopenid () {Return Openid;} Public Void SetOpenid (String Openid) {this.openid = openid;} Public String E () {Return Scope;} Public Void Setscope (String scope) {this.scope = scope;} Public String getunionid () {Return unionid;} Public Void Setunionid (String Unionid) {this.unionid = unionid; String tostring () {Return "AccessStoken [Access_token =" + Access_token + ", Expires_in = " + Expires_in +", Refresh_token = " + Refresh_token +", Openid = " + Openid +", scope = " + scope +", unionid = " + unionid +"] "]"] "Second, after we obtained Openid, we can carry out the next unified placement of orders. The document of the single interface on WeChat is more detailed, and I will not introduce the specific parameter meaning. The most intuitive code is posted below, especially reminding that you must pay attention to the correct signature. The key used in the signature is not AppSecret but the merchant KEY you defined when you apply.
// Uniform the order wxpaysenddata data = new wxpaysenddata (); data.setAppid (wxpayconfig.appid); data.Setattach ("WeChat Pay"); Data.SetBody ("WeChat public account payment"); tmch_id (wxpayconfig. Mchid); data.setnonce_str (noncestr); data.setnotify_url (wxpayconfig.notify_url); data.setout_trade_no (tradeno); ) (Fee*100)); // Unit: Data.Settrade_type ("" Jsapi "); data.setspbill_create_ip (ip); data.setOpenid (at.getOpenid ()); String Returnxml = UnifiedRederservice.unifiedorder (data, wxpayconfigig .Key); wxpayreturndata redata = new wxpayreturndata (); xstream xs1 = new xstream ( new domdriver ()); xs1.alias ("xml", wxpayreturndata.class); redata = (wxpayreturndata) xs1.fromxml (RETURNXML);UnifiedOrderService.java
Public Class UnifiedOrderService {Private Final Static Logger = LoggerFactory.getLogger (UnifiedOrnderService.class); Public Static String FIEDORDER (WXPAYSENDATA DATA, String Key) {// Uniform order to pay String Returnxml = Null; try {// generate sidn signature sortedMap <Object, object> Parameters = New Treemap <object, object> (); Parameters.put ("appid", data.getAppid ()); h ()); Parameters.put ("Body", Data.getBody ()); Parameters.put ("mch_id", data.getmch_id ()); parameters.put ("nonce_str", data.getnonOnonce_Str ()); fy_url ", data.getNotify_url ()); Parameters.put ("OUT_TRADE_NO", Data.getout_trade_no ()); Parameters.put ("Total_fee", data.gettotal_fee eters.put ("trade_type", data.gettrade_type () );; "SPBILL_CREATE_IP", Data.getspbill_Create_ip ()); Parameters.put ("Openid", Data.getOpenid ()); Parameters.put ("Device_info", D ata.getDevice_info ()); logger.info ("Sign:"+WXSIGN.CREATESIGN (Parameters, Key)); F-8 ", New XMLFRIENDLYNAMECODER ("- _ "," _ ")); xs.alias (" xml ", wxpaysenddata.class); string xml = xs.toxml (data); logger.info (" Unified order xml is:/n " + xml) ; HttpClientUtil Util = httpclientutil.getInstance (); Returnxml = Util.dopostForsstring ("https://api.mch.qq.com/pay/unifiedRder", NU ll, xml); logger.info ("Return Result:" + Returnxml);} Catch (Exception E) {e.printstacktrace ();} Return Returnxml;}}}}}}}}}Wxsign
Public class wxsign {Private Static String CharacterErencoding = "UTF-8"; @SuppressWarnings ("Rawtypes") Public Static String (SorteDMap <obj Ect, Object> Parameters, String Key) {StringBuffer Sb = New StringBuffer (); Set ES = Parameters.entrySet (); // All parameters participating in the parameter are sorted according to account (promoter) iterator it = es.Iterator (); while (it.hasnext ()) {map.entry entry = (map.entry) it. next (); string k = (string) entry.getkey (); object v = Entry.getValue (); if (null! = v &&! "" ". &&! "Key" .equals (k)) {sb.append (k + "=" + v + "&");}} sb.append ("key =" + key); string sign = md5util.md5enCode ( sb.tstring (), charaCterenCoding) .touppercase (); Return Sign;} Public Static String GetnOstr () {Random Random = New Random (); Return ODE (String.valueof (RANDOM.NEXTINT (10000)), " UTF-8 ");} Public Static String Gettimestamp () {Return String.valueof (System.currenttTimemillis () / 1000);}}The last thing to mention is the Notify_url callback address to receive WeChat payment asynchronous notification callback address.
We have obtained the preparation of the preparation of the pre -payment transaction, so that we can perform the last step operation. Use H5 to adjust the payment API.
// H5 Turn up payment attr.addattribute ("appid", redata.getAppid ()); Attr.addattribute ("timestamp", wxsign.gettimestamp ()); Attr.addattribute ("Nonce eStr ", redata.getnonce_str ()) ; Attr.addattribute ("Package", "Prepay_id ="+Redata.GetprePrepay_id ()); Attr.addattribute ("Signtype", "MD5"); signmap = New Treemap <Object, Object> (Object> ( );; "appid", redata.getAppid ()); signmap.put ("timestamp", wxsign.gettimestamp ()); r ()); signmap.put ("PACKAGE", "Prepay_id ="+Redata.getprePrepay_id ()); SIGNMAP.Put ("Signtype", "MD5"); Logger.info ("PaySign:"+WXSIGN.CREATESIGN (SIGNMAP, SIGNMAP, SIGNMAP, SIGNMAP, SIGNMAP, Wxpayconfig.key)) ; Attr.addattribute ("PaySign", wxsign.createSign (signmap, wxpayconfig.key));After passing the required parameters to the page, use WeChat to provide a method to set up payment.
<Script> Function geturlparam (name) {// Construct a regular expression object containing target parameters VAR Reg = New Regexp ("(^| &)" + name + "= ([^&]*) (& | $) ) "); // match the target parameter var r = window.location.search.substr (1) .match (reg); // Return the parameter value if (R! = Null) Return Unescape (R [2]); null;} Function onbridgeready () {var appid = geturlparam ('appid'); VAR TIMESTAMP = geturlparam ('timeStamp'); Var NonCestr = nonCestr '); Var Package = Geturlparam (' Package '); VAR SIGNTYPE = Geturlparam ('Signtype'); VAR PAYSIGN = GeturlParam ('PaySign'); Weixinjsbridge.invoke ('GetbrandwcpayRequest', {"appid": appid, /// "WX2421B1C4370EC43B", // Public account name, introduced by merchants " TimesStamp ": Timestamp, //" 1395712654 ", // Timelia, the second number of seconds since 1970" Noncestr ": Noncestr, //" E61463F8EFA94090B1F366cccfbbb444 ", // Random string" Package " GE, // "Prepay_id = u802345jgfjsdgsdg888 "," Signtype ": Signtype, //" MD5 ", // WeChat signature method:" PaySign ": PaySign, //" 70EA570631E4bb79628fbca905343FFADD89 "" // WeChat signature}, function (res) {// Use the above method to judge the front end Back, the WeChat team solemnly reminds: Res.err_msg will return to OK after the user pays successfully, but it does not guarantee that it is absolutely reliable. Alert ("" Payment Success ");} if (res.err_msg ==" get_brand_wcpay_request: cancel ") {alert (" transaction cancellation ");} if (res.err_msg ==" get_wcpay_Request: FAIL ") lert ("payment Failure ");}});} Function callPay () {if (typeof weixinjsbridge ==" underfined ") {if (document.addeventristener) {Document.adDeventListener ('Wei XINJSBRIDGEREADY ', onbridgeready, FALSE);} else if (document .Atachevent) {document.attachevent ('weixinjsbridgereidy', onbridgereidy); Document.attachevent ('Onweixinjsbridgeready', onbridgeready) ;}} Else {onbridgeready ();}} </script>You can customize your own return page where you return the result.
Summary: Since I also do it for the first time, writing this article is to record my work results, and friends who share with novice can have some help. Finally, I hope that there are good insights to leave a message and discuss. Study progress.
The above is all the contents of Java's development of WeChat public payment. I hope everyone can like it.