WeChat Pay in Java

There are various payment methods such as credit card payment, code scanning payment, official account payment, and APP payment on WeChat payment documents. This time, we will take the webpage payment opened in WeChat as an example, and implement it with java. Wechat in-page payment can be attributed to the official account payment.

1. Set up payment directory

Open the WeChat Merchant Platform and set the path: Merchant Platform --> Product Center --> Development Configuration, as shown in Figure 7.7. The official account payment will verify whether the request source has been configured on the merchant platform when requesting payment, so it must be ensured that the payment directory has been correctly configured, otherwise the verification will fail and the payment request will be unsuccessful.

Payment Directory Configuration

2. Set up an authorized domain name

When developing the official account payment, the user's openid must be passed in the unified order interface, and to obtain the openid, you need to set the domain name to obtain the openid on the official platform. Only the domain name that has been set is a valid domain name for obtaining the openid, otherwise will get failed.

WeChat webpage authorized domain name

After completing the above two steps, the payment port on WeChat can be called by our website.

3. Analyze the business sequence diagram

WeChat reflects its corresponding business processes with sequence diagrams in official documents.

Sequence diagram of web payment in WeChat

According to this figure, it can be seen that the process is roughly as follows: your own java background generates a payment link, the user clicks the link, a merchant order is generated in the java background, the order is sent to the WeChat payment system in the WeChat format, and the WeChat payment system generates a prepaid payment Order to the java backend, and then generate payment parameters in the java backend to return to the user, the user clicks the payment, and the legality of the payment parameters will be checked to the WeChat payment system, and the payment operation can be completed after confirmation. After the payment is completed, the merchant will be notified of the payment result asynchronously, and it will jump to the specified payment success page.

Fourth, java implementation

1. First, you need to call the WeChat payment package and add it to pom.xml.

		<dependency>
		    <groupId>com.github.wxpay</groupId>
		    <artifactId>wxpay-sdk</artifactId>
		    <version>0.0.3</version>
		</dependency>

2. On the page, the events that need to be clicked on the payment button are as follows. First, jump to your own background, return the payment parameters required for payment, and store them in the js element for use by pay2(). The value of '${redirect_uri}' is the domain name you filled in before. It's just that for the convenience of management, I wrote it into the configuration file, which can be passed into js as a value returned by the background.

function pay(){
   	 var redirect_uri = 'http://'+'${redirect_uri}'+"/xjwUtil/mobile/user/pay/";
   	 jQuery.ajax({
 		url : redirect_uri,
 		datatype : 'json',
 		type : "Post",
 		scriptCharset: 'utf-8',
 		contentType: "application/x-www-form-urlencoded; charset=utf-8",
 		success : function(data) {
 			var d = eval('('+data +')');
 			jQuery('#appId').val();
 			jQuery('#timeStamp').val(d.timeStamp);
 			jQuery('#nonceStr').val(d.nonceStr);
 			jQuery('#signType').val(d.signType);
 			jQuery('#paySign').val(d.paySign);
 			jQuery('#package').val(d.pk);
 			pay2();
 		}
 	})
}

3. The java processing Controller corresponding to the address "mobile/user/pay/" is shown in the following code, the purpose is to return the parameter values ​​required for payment. The openId parameter is stored in the session by me when the user logs in using WeChat. The focus is on WXPayExample.yy(openId) here, this class is the channel for obtaining prepayment information through openId.

Controller.java 

@RequestMapping(value = "/pay/", method = RequestMethod.POST)
@ResponseBody  
	public String pay(HttpServletRequest req, HttpServletResponse resp){
		Map<String,String> m= new HashMap<String,String>();
		try {
		req.setCharacterEncoding("utf-8");
		String openId=(String)req.getSession().getAttribute("openId");
		Map<String,String> result=WXPayExample.yy(openId);
		String nonceStr=result.get("nonce_str");
		String package1="prepay_id="+result.get("prepay_id");
		m.put("appId","************");
		m.put("package", package1);
		m.put("nonceStr", nonceStr);
		long time=System.currentTimeMillis()/1000;
		m.put("timeStamp",time+"");
	    m.put("signType", "MD5");
		m.put("paySign", WXPayUtil.generateSignature(m,"*********************", SignType.MD5));
		String reqBody =WXPayUtil.mapToXml(m);
		m.put("pk", package1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    String result1 = JSON.toJSONString(m);
        return result1; 
	}

In the WXPayExample class, the first step is to obtain the service ID APPID, merchant ID, and Key through MyConfig() configuration, and load the payment certificate. Then fill in the random code in the payment information, payment amount, payment method, payment URL, etc. Then WXPay adds its signature, WxPayUtil converts it into an xml file, sends it to the WeChat payment platform through wxpay.unifiedOrder(data), and obtains the return value. These three packages can all need to be imported

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants.SignType;
import com.github.wxpay.sdk.WXPayUtil;

WXPayExample.java 

	public static Map<String,String>  yy(String openId) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "xx");
        data.put("out_trade_no", WXPayUtil.generateNonceStr());
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "192.168.31.166");
        data.put("openid",openId);
        data.put("notify_url", "http://"+GetPeizhi.serverName+"/xjwUtil");
        data.put("trade_type", "JSAPI"); 
        try {
        	Map<String, String> data2 = wxpay.fillRequestData(data);
        	String reqBody =WXPayUtil.mapToXml(data2);
        	System.out.println(reqBody);
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println(resp);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

MyConfig.java

import com.github.wxpay.sdk.WXPayConfig;
import java.io.*;
public class MyConfig implements WXPayConfig{

    private byte[] certData;

    public MyConfig() throws Exception {
    	String certPath=this.getClass().getResource("/*****证书******").getPath();
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    public String getAppID() {
        return "***********";
    }

    public String getMchID() {
        return "***********";
        
    }

    public String getKey() {
        return "***********";
    }

    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }
}

4. At this time, you can already get the prepayment information. There is a prepayment prepay_id which is the ID of the prepayment information in the WeChat platform. Encapsulate the returned nonceStr, prepay_id as a package and other parameters as required. and add a signature. Then put the signature and all other tags into the map collection, convert it into result1 and send it to the page. Users can choose to pay.

5. The javascript paid by the user. Back in cart.jsp, after the ajax in the second step gets the return value, you can proceed to the next step. The function pay2() is the sending of the user's payment instruction. When the WeChat payment is ready, the payment is made through the onBridgeReady() method. If the payment is successful, the success method is called, and if the payment fails, the failure page is directly jumped. At this point, the whole process comes to an end.

cart.jsp

function pay2() {
		var appId = jQuery('#appId').val();
		var timeStamp = jQuery('#timeStamp').val();
		var nonceStr = jQuery('#nonceStr').val();
		var signType = jQuery('#signType').val();
		var pk = jQuery('#package').val();
		var paySign = jQuery('#paySign').val();
		if (typeof WeixinJSBridge == "undefined") {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', onBridgeReady,
						false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
				document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			}

		} else {
			onBridgeReady();
		}
		function onBridgeReady() {
			console.log(appId + "==" + timeStamp + "==" + nonceStr + "==" + pk
					+ "==" + "MD5" + "==" + paySign + "")
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				"appId" : appId, //公众号名称,由商户传入     
				"timeStamp" : timeStamp, //时间戳,自1970年以来的秒数     
				"nonceStr" : nonceStr, //随机串     
				"package" : pk,
				"signType" : "MD5", //微信签名方式:     
				"paySign" : paySign
			//微信签名 
			}, function(res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					success();
				} // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回    ok,但并不保证它绝对可靠。 
				else{
					window.location.href="${pageContext.request.contextPath}/mobile/user/payfail/"
					
				}
			});
		}
	}
  function success(){
    	 jQuery.ajax({
    	 		url : "${pageContext.request.contextPath}/mobile/user/paysuccess/",
    	 		datatype : 'json',
    	 		type : "Post",
    	 		scriptCharset: 'utf-8',
    	 		contentType: "application/x-www-form-urlencoded; charset=utf-8",
    	 		success : function(data) {
    	 			window.location.href="${pageContext.request.contextPath}/mobile/user/success2"
    	 		}
    	 	})
    }

5. Attached

The variable appId is required when using WeChat Pay. In the above, the appId is taken out through the session. The method of obtaining the appID for the first time is as follows:

Or write it in the next blog. . .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325445856&siteId=291194637