Directory:
Mobile brain -SpringMVc RestFul background service (I) – environment construction
Mobile brain -SpringMVc build RestFul background service (2) – configure mysql database
Mobile brain -SpringMVc RestFul background service (III) -RestFul interface writing (simulating user registration and login)
Mobile brain -SpringMVc build RestFul backend service (4) – Add Token filter
Mobile brain -SpringMVc build RestFul background service (V) – Alipay payment
Mobile Brain -SpringMVc build RestFul background service (VI) – wechat Pay (Android)
In the last blog “Mobile brain -SpringMVc build RestFul background service (V) – Alipay Payment”, alipay payment has been realized. Next, I will add wechat payment function, so that the payment function is basically complete, and UnionPay will not be considered.
Originally I wrote a “Android wechat payment climb pit” blog, which is completely from the APP end initiated payment, there is a need to see.
Here’s an example:
First began to prepare for work in WeChat development platform (https://open.weixin.qq.com/) to apply for your own application, and fill in the correct package name and signature, after the approval to apply for WeChat payment function, or get a merchant account at this time, and in the merchant background setting their 32-bit key, above all when ready, And download the required wechat development JAR package (mainly generating signature and network access tool classes, can be changed to their own tool classes according to their own situation), you can start the development of wechat.
The process of wechat payment and Alipay is actually the same: APP requests the payment interface of the server —-> the server generates the local order —-> the server constructs the data to the wechat end generates the pre-payment order —-> the server gets the pre-payment order and returns it to APP—-> the APP gets the wechat pay information and sets up the wechat pay service > wechat Pay succeeds by notifies APP OPEN > wechat asynchronous transfer The server uses the payment verification interface —-> to process the verification result and return it to wechat, completing a payment process.
Start coding:
I. Add wechat order in PaySerVice
view plain
copy
?
- else if(payWay == 2)// Wechat Pay
- {
- SortedMap<String, String> parameters = new TreeMap<String, String>();
- parameters.put(“appid”, WX_APPID);
- parameters.put(“body”, orderBean.getSubject());
- parameters.put(“mch_id”, WX_MCHID);
- parameters.put(“nonce_str”, CommonUtils.genNonceStr());
- parameters.put(“notify_url”.“http://10.50.50.205:8080/pay/verifywxpayresult.do”);
- parameters.put(“out_trade_no”, orderBean.getOrderNo());
- parameters.put(“total_fee”.“50”);
- parameters.put(“trade_type”.“APP”);
- parameters.put(“spbill_create_ip”.“196.168.1.1”);
- parameters.put(“sign”, CommonUtils.createSign(“UTF-8”, parameters, WX_KEY)); // Pass in the signed parameter values
- StringBuilder xmlBuilder = new StringBuilder();
- xmlBuilder.append(“<xml>”);
- Set es = parameters.entrySet();// All parameters are sorted by accsii (ascending order)
- Iterator it = es.iterator();
- CommonUtils.createXml(it, xmlBuilder);
- xmlBuilder.append(“</xml>”);
- System.out.println(xmlBuilder.toString());
- try {
- String url = “https://api.mch.weixin.qq.com/pay/unifiedorder”;
- byte[] buf = Util.httpPost(url, new String(xmlBuilder.toString().getBytes(“UTF-8”), “ISO8859-1”));
- String content = new String(buf);
- System.out.println(“content:” + content);
- Map<String, String> map = CommonUtils.xmlToMap(content);
- String nonceStr = CommonUtils.genNonceStr();
- String timeStamp = String.valueOf(CommonUtils.genTimeStamp());
- SortedMap<String, String> signparameters = new TreeMap<String, String>();
- signparameters.put(“appid”, map.get( “appid”));
- signparameters.put(“partnerid”, map.get( “mch_id”));
- signparameters.put(“prepayid”, map.get( “prepay_id”));
- signparameters.put(“package”. “Sign=WXPay”);
- signparameters.put(“noncestr”, nonceStr);
- signparameters.put(“timestamp”, timeStamp);
- wxPayBean = new WxPayBean();
- wxPayBean.setOrderId(order.getOrderNo());
- wxPayBean.setAppid(map.get(“appid”));
- wxPayBean.setPartnerid(map.get(“mch_id”));
- wxPayBean.setPrepayid(map.get(“prepay_id”));
- wxPayBean.setNoncestr(nonceStr);
- wxPayBean.setTimestamp(timeStamp);
- wxPayBean.setPackageValue(“Sign=WXPay”);
- wxPayBean.setSign(CommonUtils.createSign(“UTF-8”, signparameters, WX_KEY));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
Parameters = new TreeMap<String, String>(); else if(payWay == 2)// parameters.put("appid", WX_APPID); parameters.put("body", orderBean.getSubject()); parameters.put("mch_id", WX_MCHID); parameters.put("nonce_str", CommonUtils.genNonceStr()); The parameters. The put (" notify_url ", "http://10.50.50.205:8080/pay/verifywxpayresult.do"); parameters.put("out_trade_no", orderBean.getOrderNo()); parameters.put("total_fee", "50"); parameters.put("trade_type", "APP"); Parameters. The put (" spbill_create_ip 196.168.1.1 ", ""); parameters.put("sign", CommonUtils.createSign("UTF-8", parameters, WX_KEY)); StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append("<xml>"); Set es = parameters.entrySet(); Iterator it = es.iterator(); Iterator = es.iterator(); CommonUtils.createXml(it, xmlBuilder); xmlBuilder.append("</xml>"); System.out.println(xmlBuilder.toString()); try { String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; byte[] buf = Util.httpPost(url, new String(xmlBuilder.toString().getBytes("UTF-8"), "ISO8859-1")); String content = new String(buf); System.out.println("content:" + content); Map<String, String> map = CommonUtils.xmlToMap(content); String nonceStr = CommonUtils.genNonceStr(); String timeStamp = String.valueOf(CommonUtils.genTimeStamp()); SortedMap<String, String> signparameters = new TreeMap<String, String>(); signparameters.put("appid", map.get("appid")); signparameters.put("partnerid", map.get("mch_id")); signparameters.put("prepayid", map.get("prepay_id")); signparameters.put("package", "Sign=WXPay"); signparameters.put("noncestr", nonceStr); signparameters.put("timestamp", timeStamp); wxPayBean = new WxPayBean(); wxPayBean.setOrderId(order.getOrderNo()); wxPayBean.setAppid(map.get("appid")); wxPayBean.setPartnerid(map.get("mch_id")); wxPayBean.setPrepayid(map.get("prepay_id")); wxPayBean.setNoncestr(nonceStr); wxPayBean.setTimestamp(timeStamp); wxPayBean.setPackageValue("Sign=WXPay"); wxPayBean.setSign(CommonUtils.createSign("UTF-8", signparameters, WX_KEY)); } catch (Exception e) { e.printStackTrace(); }}Copy the code
2. Add wechat Pay callback interface in PayAction
view plain
copy
?
- / * *
- * wechat callback interface
- * @param request
- * @param resp
- * @return
- * /
- @ResponseBody
- @RequestMapping(value=“/verifywxpayresult.do”, method=RequestMethod.POST)
- public String verifyWxPayRight(HttpServletRequest request, HttpServletResponse resp)
- {
- System.out.println(“———————————–come here wxpay——————————–“);
- synchronized (wxlock) {
- System.out.println(“———————————–come here wxpay 2——————————–“);
- BufferedReader reader = null ;
- try {
- reader = request.getReader() ;
- String line = “” ;
- String xmlString = null ;
- StringBuffer inputString = new StringBuffer() ;
- while( (line = reader.readLine()) ! =null) {
- inputString.append(line) ;
- }
- xmlString = inputString.toString() ;
- request.getReader().close();
- System.out.println(“xmlString:” + xmlString);
- Map<String, String> map = CommonUtils.xmlToMap(xmlString);
- System.out.println(“result sign:” + map.get(“sign”));
- SortedMap<String, String> parameters = new TreeMap<String, String>();
- parameters.put(“appid”, map.get(“appid”));
- parameters.put(“bank_type”, map.get(“bank_type”));
- parameters.put(“cash_fee”, map.get(“cash_fee”));
- parameters.put(“fee_type”, map.get(“fee_type”));
- parameters.put(“is_subscribe”, map.get(“is_subscribe”));
- parameters.put(“mch_id”, map.get(“mch_id”));
- parameters.put(“nonce_str”, map.get(“nonce_str”));
- parameters.put(“openid”, map.get(“openid”));
- parameters.put(“out_trade_no”, map.get(“out_trade_no”));
- parameters.put(“result_code”, map.get(“result_code”));
- parameters.put(“return_code”, map.get(“return_code”));
- parameters.put(“time_end”, map.get(“time_end”));
- parameters.put(“total_fee”, map.get(“total_fee”));
- parameters.put(“trade_type”, map.get(“trade_type”));
- parameters.put(“transaction_id”, map.get(“transaction_id”));
- String resultSign = CommonUtils.createSign(“UTF-8”, parameters, PayService.WX_KEY);
- System.out.println(“create sign:” + resultSign);
- if(map.get(“sign”).equals(resultSign))
- {
- if(payService.verifyWxPay(map).equals(“success”))
- {
- SortedMap<String, String> result = new TreeMap<String, String>();
- result.put(“return_code”. “SUCCESS”);
- return mapToXml(result);
- }
- SortedMap<String, String> result = new TreeMap<String, String>();
- result.put(“return_code”.“FAIL”);
- return mapToXml(result);
- }
- else
- {
- SortedMap<String, String> result = new TreeMap<String, String>();
- result.put(“return_code”.“FAIL”);
- return mapToXml(result);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- SortedMap<String, String> result = new TreeMap<String, String>();
- result.put(“return_code”.“FAIL”);
- return mapToXml(result);
- }
/** * @responseBody @requestMapping (value="/verifywxpayresult.do", method=RequestMethod.POST) public String verifyWxPayRight(HttpServletRequest request, HttpServletResponse resp) { System.out.println("-----------------------------------come here wxpay--------------------------------"); synchronized (wxlock) { System.out.println("-----------------------------------come here wxpay 2 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "); BufferedReader reader = null ; try { reader = request.getReader() ; String line = "" ; String xmlString = null ; StringBuffer inputString = new StringBuffer() ; while( (line = reader.readLine()) ! = null ){ inputString.append(line) ; } xmlString = inputString.toString() ; request.getReader().close(); System.out.println("xmlString:" + xmlString); Map<String, String> map = CommonUtils.xmlToMap(xmlString); System.out.println("result sign:" + map.get("sign")); SortedMap<String, String> parameters = new TreeMap<String, String>(); parameters.put("appid", map.get("appid")); parameters.put("bank_type", map.get("bank_type")); parameters.put("cash_fee", map.get("cash_fee")); parameters.put("fee_type", map.get("fee_type")); parameters.put("is_subscribe", map.get("is_subscribe")); parameters.put("mch_id", map.get("mch_id")); parameters.put("nonce_str", map.get("nonce_str")); parameters.put("openid", map.get("openid")); parameters.put("out_trade_no", map.get("out_trade_no")); parameters.put("result_code", map.get("result_code")); parameters.put("return_code", map.get("return_code")); parameters.put("time_end", map.get("time_end")); parameters.put("total_fee", map.get("total_fee")); parameters.put("trade_type", map.get("trade_type")); parameters.put("transaction_id", map.get("transaction_id")); String resultSign = CommonUtils.createSign("UTF-8", parameters, PayService.WX_KEY); System.out.println("create sign:" + resultSign); if(map.get("sign").equals(resultSign)) { if(payService.verifyWxPay(map).equals("success")) { SortedMap<String, String> result = new TreeMap<String, String>(); result.put("return_code", "SUCCESS"); return mapToXml(result); } SortedMap<String, String> result = new TreeMap<String, String>(); result.put("return_code", "FAIL"); return mapToXml(result); } else { SortedMap<String, String> result = new TreeMap<String, String>(); result.put("return_code", "FAIL"); return mapToXml(result); } } catch (IOException e) { e.printStackTrace(); } } SortedMap<String, String> result = new TreeMap<String, String>(); result.put("return_code", "FAIL"); return mapToXml(result); }Copy the code
Add payment whitelist to filter
view plain
copy
?
- else if(uri.endsWith(“pay/verifyalipayresult.do”))// Alipay callback interface
- {
- return true;
- }
- else if(uri.endsWith(“pay/verifywxpayresult.do”)) // Wechat callback interface
- {
- return true;
- }
Else if (uri endsWith (" pay/verifyalipayresult. Do ")) / / alipay callback interface {return true; } else if(uri.endswith ("pay/verifywxpayresult.do"))// }Copy the code
These are the main codes, which can generate wechat pre-payment orders on the server side. For the detailed codes, please refer to the source code at the end of the article. The example of pre-payment orders is shown in the figure:
Server information:
Client information:
After the client gets the pre-payment order, it can adjust wechat Payment:
Adjust the wechat payment code:
view plain
copy
?
- PayApi.getInstance().createOrder(MyApplication.getInstance().getUserBean().getId(), MyApplication.getInstance().getPhone(), “Wechat Pay Test”. “1”.2.“APP wechat SDK Payment”.new HttpSubscriber<AliWxPayBean>( new SubscriberOnListener<AliWxPayBean>() {
- @Override
- public void onSucceed( final AliWxPayBean data) {
- hideLoadDialog();
- System.out.println(Wechat pre-payment order Information: + data.getPrepayid());
- System.out.println(“sign:” + data.getSign());
- PayReq request = new PayReq();
- request.appId = data.getAppid();
- request.partnerId = data.getPartnerid();
- request.prepayId = data.getPrepayid();
- request.packageValue = data.getPackageValue();
- request.nonceStr = data.getNoncestr();
- request.timeStamp = data.getTimestamp();
- request.sign = data.getSign();
- WxFactory.getInstance().getWxApi(MainActivity.this).sendReq(request);
- }
- @Override
- public void onError( int code, String msg) {
- hideLoadDialog();
- Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
- }
- }, MainActivity.this));
PayApi.getInstance().createOrder(MyApplication.getInstance().getUserBean().getId(), MyApplication. GetInstance (). GetPhone (), "WeChat pay test", "1", 2, "APP WeChat SDK to pay", new HttpSubscriber<AliWxPayBean>(new SubscriberOnListener<AliWxPayBean>() { @Override public void onSucceed(final AliWxPayBean data) { hideLoadDialog(); System.out.println(" + data.getPrepayid() "); System.out.println("sign: "+ data.getSign()); PayReq request = new PayReq(); request.appId = data.getAppid(); request.partnerId = data.getPartnerid(); request.prepayId = data.getPrepayid(); request.packageValue = data.getPackageValue(); request.nonceStr = data.getNoncestr(); request.timeStamp = data.getTimestamp(); request.sign = data.getSign(); WxFactory.getInstance().getWxApi(MainActivity.this).sendReq(request); } @Override public void onError(int code, String msg) { hideLoadDialog(); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show(); } }, MainActivity.this));Copy the code
Processing wechat payment results:
view plain
copy
?
- package com.ywl5320.rxjavaretrofit.wxapi;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.widget.Toast;
- import com.tencent.mm.opensdk.constants.ConstantsAPI;
- import com.tencent.mm.opensdk.modelbase.BaseReq;
- import com.tencent.mm.opensdk.modelbase.BaseResp;
- import com.tencent.mm.opensdk.openapi.IWXAPI;
- import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
- public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
- private IWXAPI api;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // api = WXAPIFactory.createWXAPI(this, “”, true);
- // api.registerApp(“”);
- api = WxFactory.getInstance().getWxApi(this);
- api.handleIntent(getIntent(), this);
- }
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- setIntent(intent);
- api.handleIntent(intent, this);
- }
- @Override
- public void onReq(BaseReq req) {
- }
- @Override
- public void onResp(BaseResp resp) {
- if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
- if(resp.errCode == 0)
- {
- Toast.makeText(this.“Payment successful”, Toast.LENGTH_LONG).show();
- }
- else if(resp.errCode == –1)
- {
- Toast.makeText(this.“Payment error:” + resp.errStr, Toast.LENGTH_LONG).show();
- }
- else if(resp.errCode == –2)
- {
- Toast.makeText(this.“Cancel payment”, Toast.LENGTH_LONG).show();
- }
- }
- finish();
- }
- }
package com.ywl5320.rxjavaretrofit.wxapi; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import com.tencent.mm.opensdk.constants.ConstantsAPI; import com.tencent.mm.opensdk.modelbase.BaseReq; import com.tencent.mm.opensdk.modelbase.BaseResp; import com.tencent.mm.opensdk.openapi.IWXAPI; import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler; public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler { private IWXAPI api; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // api = WXAPIFactory.createWXAPI(this, "", true); // api.registerApp(""); api = WxFactory.getInstance().getWxApi(this); api.handleIntent(getIntent(), this); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); api.handleIntent(intent, this); } @Override public void onReq(BaseReq req) { } @Override public void onResp(BaseResp resp) { if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {if(resp.errCode == 0) {toast.maketext (this, "paid successfully ", toast.length_long).show(); } else if(resp.errcode == -1) {toast.maketext (this, "pay error:" + resp.errstr, toast.length_long).show(); } else if(resp.errCode == -2) {toast.maketext (this, "cancel the payment ", toast.length_long).show(); } } finish(); }}Copy the code
Server and client core code is all of the above, please refer to the source code for specific examples:
Download the source from GitHub AppServiceRestFul
Incremental updates will be added in the next article.