WeChatPay

Business requirements:

At present, there are many projects related to wechat, mainly involving the functions of [wechat custom sharing, wechat payment, etc.]. When developing the H5 page of wechat official account, we need to use wechat Pay for financial payment. When wechat Payment is completed ** [payment successfully click “Finish”], the corresponding business logic needs to be started; For example: jump to the order page when the payment is successful; Jump to place order page when payment fails; The current order page remains unchanged when payment is cancelled. In the early stage of the development of wechat H5 page, most of the consideration is how to deal with [successful payment], because it is just to contact wechat payment, most of the payment status is updated by refreshing the page to obtain new data. This approach can solve the problem at that time, but from the perspective of business logic, it is not very reasonable. Pay scene is more and more, the WeChat pay process have further understanding and the understanding, now looking back on the past project using * * WeChat pay 】 【 business scenarios of carding and perfect, further optimize the payment process, as well as the different states of the payment after the corresponding processing and optimization, and connecting with the actual situation to do the corresponding business logic analysis.

Payment method:

  • A:Wechat Pay 【 wechat official account 】
    • This payment method requires the introduction of JS file in the HTML page, namely [jweixin-1.6.0.js];
    • This JS file link supports HTTP and HTTPS. When referencing, it must match the request-response protocol (HTTP and HTTPS) of the current project.
    • The JS file can be loaded using the AMD/CMD standard module loading mode.
let WeChatPay = function() {
	// 2. Obtain the verification information of public number after importing JS
	let timestamp = ' ',
		nonceStr = ' ',
		signature = ' ';
	let v = {
		// The parameter used to exchange wechat verification information: must not contain the "#" sign
		url: location.split(The '#') [0]};// 3. Verify the configuration through the config interface injection permission (synchronization is required, and the config can be injected only after the verification information is obtained, otherwise the verification fails!)
	wx.config({
		debug: true.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log.
		appId: ' '.// Mandatory, the unique identifier of the public account
		timestamp:,// Mandatory to generate the timestamp of the signature
		nonceStr: ' '.// Mandatory to generate a random string of signatures
		signature: ' '.// Mandatory, signature
		jsApiList: ["checkJsApi"."chooseWXPay"."updateAppMessageShareData"."updateTimelineShareData"] // Mandatory, a list of JS interfaces to be used
	});

	axios.post('/wx/pay/orderPay_XXXX', data).then(res= > {
		// Successful payment status
		if (res.code == 200) {
			// Get the required parameters for payment
			let {
				nonceStr,
				package,
				signType,
				paySign
			} = res.data;
			// 4. Verify that the processing is successful through the ready interface
			wx.ready(function() {
				/* wechat Pay */
				wx.chooseWXPay({
					timestamp: 0.// Payment signature timestamp, note that all use timestamp fields in wechat JSSDK are lowercase. But the latest version of the payment background generated signature timeStamp field name needs to capitalize the S character
					nonceStr: nonceStr, // The payment signature is a random string, no longer than 32 bits
					package: package, // The prepay_id parameter returned by the unified payment interface is submitted in the format prepay_id=\*\* *)
					signType: signType, // Signature mode, default is 'SHA1', use the new version of payment to pass 'MD5'
					paySign: paySign, // Pay the signature
					success: function(res) {
						// Front-end judgment return method, wechat team solemnly remind: not guaranteed absolute reliability, remember!
						if (res.errMsg == 'chooseWXPay:ok') {
							// 【 Payment successfully 】
						} else if (res.errMsg == 'chooseWXPay:cancel') {
							// [Cancel payment] : The user cancels payment without entering this judgment, but instead enters the complate and cancel functions
						} else{}},complete: function(res) {
						// The callback function that is executed when the interface call completes, regardless of success or failure
						if (res.errMsg == 'chooseWXPay:ok') {
							// [Payment successfully] : The payment is successful prompt page, after clicking the "Finish" button
							wx.closeWindow(); /* Close the wechat window, which needs to be checked in config */
						} else if (res.errMsg == 'chooseWXPay:cancel') {
							// [Payment cancellation]
						} else{}/** * Both iOS and Android pay will enter the success and complete functions after clicking "finish", both will return 'chooseWXPay: OK '* * The reason is that iOS and Android return different data. Android returns {"errMsg":"getBrandWCPayRequest: OK "}, iOS returns {"err_Info":"success","errMsg":"chooseWXPay: OK "}, * */
					},
					fail: function(err) {
						// Failed to call the interface
					},
					cancel: function(err) {
						// The callback function when the user clicks cancel: the user cancels the payment and actually enters the cancel and complate functions}}); }); } }).catch(err= > {
		console.log('Payment failure:', err);
	});
}
Copy the code
  • Interface Description:Do not attempt to use Ajax in trigger to asynchronously request changes to the content of the share, because the client share operation is a synchronous operation and the Ajax-using packet will not return.
  1. Success: Callback function executed when the interface invocation succeeds.
  2. Fail: Callback function executed when an interface call fails.
  3. Complete: The callback function executed when the interface call completes, whether it succeeds or fails.
  4. Cancel: Callback function when the user clicks cancel. This function is used only by some apis that have user cancellations.
  5. Trigger: the method that is triggered when the button in Menu is clicked. This method only supports the relevant interface in Menu.
  • Method 2: wechat Payment [JSAPI Payment] (commonly used payment method)
function onBridgeReady() {
	WeixinJSBridge.invoke(
		'getBrandWCPayRequest', {
			"appId": "wx2421b1c4370ec43b".// The public id is passed in by the merchant
			"timeStamp": "1395712654".// Timestamp, the number of seconds since 1970
			"nonceStr": "e61463f8efa94090b1f366cccfbbb444"./ / random string
			"package": "prepay_id=u802345jgfjsdfgsdg888"."signType": "MD5".// wechat signature:
			"paySign": "70EA570631E4BB79628FBCA90534C63FF7FADD89" // Wechat signature
		},
		function(res) {
			// The payment was successful
			if (res.err_msg == "get_brand_wcpay_request:ok") {
				// Use the above methods to judge the front-end return, wechat team solemnly remind:
				//res.err_msg will return OK after the user has paid successfully, but it is not guaranteed to be absolutely reliable.
			}
			// The user cancels during payment
			if (res.err_msg == "get_brand_wcpay_request:cancel") {}// Payment failed
			if (res.err_msg == "get_brand_wcpay_request:fail") {}/** * other * 1, please check whether prepay_id is invalid * 2, the requested appID is the same as the ordering interface appID ** /
			if (res.err_msg == "Missing argument to call payment JSAPI: total_fee") {}}); }// Check WeixinJSBridge in the payment environment
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();
}
Copy the code

JSAPI calls up payment notes:

  • Open H5 web page in wechat browser to perform JS call up payment;
  • WeixinJSBridge is a built-in object in wechat browser, which is invalid in other browsers.
  • The arguments passed by the call payment are case sensitive.