The author’s recent demand includes the process of wechat payment, and I have encountered many pits, so I make a record for avoiding pits in the future.

First, know yourself and know your opponent, wechat payment types

When the product says, other groups also support wechat payment, our group also support it. Wechat H5 payment is also listed on the demand list.

Be aware that the payment scenario on the demand sheet is not well thought out.

Common types of wechat payment:

  • H5 payment is mainly used for the scene of wechat payment request by mobile browser of touch screen version (note not wechat browser). Wechat Pay can be invoked from an external browser.
  • JSAPI payment, mainly in wechat to open the web page, can call wechat pay to complete the order purchase process.
  • APP payment. Open SDK is integrated in mobile APP to adjust wechat payment module to complete payment. (H5 payment can also be embedded in mobile terminals, but the experience is not as good as native payment, the official website does not recommend this practice)
  • Native payment refers to the mode in which the merchant system generates a qr code for payment according to the wechat payment agreement, and users complete the payment by “scanning” on wechat. Applicable to PC websites, physical stores, single products or orders, media advertising payment and other scenarios.
  • For payment by payment code, the user shows the bar code and QR code in wechat wallet, and the merchant can complete payment by scanning the user’s bar code.
  • Small program payment. Merchants already have small programs on wechat. When users share with friends or scan two-dimensional code to open the small program in wechat, they can call wechat Pay to complete the process of ordering and purchasing.

This time, H5 payment is listed on the author’s demand list. H5 payment is also embedded in Android client, and Apple’s native IAP payment is in IOS client.

Not considered before development

  • Wechat browser JSAPI payment (what can be done, overtime),
  • Native payment when opened on PC and desktop (toast prompts payment on mobile, not done).

Ii. Preparation before development

You can refer to the wechat payment development documentation to focus on the following.

  1. Before development, a merchant number is required, which can be registered on the wechat public platform and authenticated. We should also have a wechat public account for JSAPI payment in wechat.

  2. After passing the certification, users can apply for wechat Pay on wechat public platform.

    The company of above two steps has applied for finish commonly, look for corresponding person docking to go directly

  3. Open H5 payment permission

    Go to wechat Pay merchant platform – > Product Center – > Development configuration – >H5 payment, setting generally takes effect within 10 minutes. After the login, add the H5 payment domain name in the “Payment Configuration”. Note: The domain name must be registered through ICP, and the domain name format does not include http:// or https://.

  4. Open JSAPI payment permission

    JSAPI payment relies on wechat public number, and enterprise authentication, webpage authorization. The wechat public account should be logged in and set separately on the wechat public platform.

    Go to wechat Pay merchant platform – > Product Center – > Development configuration – >JSAPI payment, setting generally takes effect within 5 minutes.

    4.1 Setting the Payment directory

    • Merchants finally request to pull up the wechat Pay cashier page address, which we call “payment catalog”, for example: www.weixin.com/pay.php.

    • The actual payment catalog of the merchant must be consistent with that set on the wechat pay merchant platform; otherwise, an error message “the URL of the current page is not registered:” will be displayed.

    • If the payment authorization directory is set to a top-level domain name (for example, www.weixin.com/), only the top-level domain name is verified, but the suffix is not verified.

    • If the payment authorization directory is set to a multi-level directory, all matches are performed. For example, if the payment authorization directory is set to www.weixin.com/abc/123/, the value of…

    • When configuring the domain name, pay attention to the protocol header. HTTP and HTTPS are completely different. If you encounter the problem “The current page URL is not registered:” during the development process, check the authorized domain name.

    4.2 Setting a Web Page Authorized Domain Name

    If you can’t see the webpage authorization, see if the public number has opened enterprise certification. The service number must be authenticated by wechat.

    • When developing JSAPI payment, the user OpenID is required to be transmitted in the unified ordering interface. To obtain OpenID, you need to set the domain name of OpenID on the public platform. Only the domain name that has been set is a valid domain name for obtaining OpenID, otherwise, the acquisition will fail.

    • Authorized domain name setting instructions: Login wechat public platform –> public account Settings –> Function Settings

    The “download file” in the picture must be placed in the online server web root directory. Otherwise, the domain name cannot be added.

    The above basic configuration must be configured, or it is easy to have some problems. In particular, web page authorization this step, often can not see the configuration, first of all, the public to enterprise authentication can be. Then the domain name must be completely written right, it is best to look at the following, let others add, easy to write wrong pit. The number of authorized domain names is generally limited, the development process encountered the need to change the domain name, just the number reached the upper limit, can only delete the original, add a new domain name. And then all sorts of weird things happen. Please note the above.

3. Prepare basic tools

  • Record the ppID of the public number (starting with WX), JSAPI payment to obtain the code used; And app_secret, which is usually just thrown to the back end.
  • The public number of web developer tools, must add the developer’s micro signal, so as to facilitate debugging.
  • Wechat developer tools many pits, development of all kinds of problems, or to use the test machine (real machine) debugging.

Problems encountered during development and debugging

Note: wechat update to 7.0 after the capture of the public account will have a certificate problem, capture small program directly can not open you don’t need to look around, also don’t doubt life, you have no problem, win10 also have no problem, fiddler and Charles also have no problem, because wechat update, no longer from the mobile phone local access to the certificate. Android 7.0 or later, wechat 7.0 or later, will trust the certificate provided by the system. Android 7.0 or later, wechat 7.0 or later, WeChat only trust the certificate list its own configuration The above rule is to copy someone else’s, but it does so, close test do I suspect that life, mostly raised well in Windows 7, the day before the second day in a win10 system, just WeChat automatically update again, suddenly can’t catch, all suspicion win10 (this dude innocent), All kinds of doubt life can not find the reason, ask you afraid, ask you pit pit… If you want to catch the package debugging, at this stage, either android 7 below the phone, or wechat 7.0 below the version…

Under the development environment, the website link cannot be opened in wechat of Android phone (the test sister said that her test machine can, but mine can’t anyway). The wechat developer tool can be opened, but the link cannot be jumped. According to the above tutorial, wechat will be downgraded to version 7.0 or below, the test is invalid; I didn’t try android versions below 7.0.

In the development environment, the website link could not be opened in wechat, so JSAPI payment would not be debuggable. I asked the backend boss, who did not know, and said only online environment debugging (the leader expressed great concern about online debugging). How to do? How to do? Sad I lost a lot of hair. Android test machine can not link, subconsciously thought IOS is not.

To solve

An unexpected attempt to open on ios showed that links could be opened in a test environment. But it comes with the condition that the phone can only connect to DNS, not proxies (which can be used to capture packets).

So development and debugging, can only borrow IOS test machine.

Iv. H5 Payment

The official website reminds H5 payment is not recommended to be used in the APP end, but this demand, android APP end is used, development encountered many pits, experience is also greatly discounted.

demand

This time, click the purchase button of paid goods, jump to the payment order page, and initiate wechat payment on the payment order page. If successful, it will return to the payment order page and toast indicates successful purchase. After 1s, it will jump to the product details page and change the page style. If it fails, it will return to the payment order page and toast will indicate that the payment failed. If the payment is cancelled, it will return to the payment order page and Toast will prompt you to cancel the payment. JSAPI payment is the same, but the demand sheet is not written. This purchase also includes the purchase of points, which will be a little too much to consider, as well as the in-account payment that is not available this time.

Key points of development document

Refer to the development documentation and highlight the following:

Let’s take a look at the callback page for H5 payments. Normal process After the payment is complete, the user is returned to the page that initiates the payment. If the user needs to return to the specified page, add the redirect_URL parameter after MWEB_URL to specify the callback page.

Note:

  • Redirect_url requires urlencode processing
  • Since redirect_URL is set, jumping back to the specified page may occur when:
    1. More than 5 seconds after the wechat cashier is set up on the middle page of wechat Pay (automatic return);
    2. Users click “cancel payment” or click the “Finish” button after the payment is completed.

    Therefore, there is no guarantee that when the page jumps back, the payment process has finished, so the redirect_URL address set by the merchant cannot automatically perform the order lookup operation, and users should click the button to trigger the order lookup operation. Refer to the following figure for the display effect of the jump back page.

The above jump back operation distinguishes the operation within 5s and after 5S, and the performance effect is completely different. If there is no prompt box indicating whether the payment is successful, it is difficult to perform the check operation stably.

Demand PK (a bitter tears)

Redirect back, display the redirect page and let the user click the button to trigger the lookup.

The author’s demand list is to directly toast the result after the return. In this case, it is impossible to accurately know the results of the payment process when the page bounces back.

During development, I was tortured by the different performance in 5s and after 5S. After a long period of development, the desired results are still not achieved, resulting in various problems in the development process.

I worked two days overtime on New Year’s Day. To move, reason to persuade the product, pay back must be added to the payment confirmation prompt page, otherwise it is unable to do payment. The product finally changed this requirement because OF my continuous overtime work. Therefore, I finally completed the development of the payment process on the last day of working overtime on New Year’s Day (more than 10 PM).

Thanks again for the product sister.

The development of

The difficulty of this demand is how to monitor wechat successful payment or cancel payment and return to the payment order page, so as to make some prompt effects.

(1) Visibilitychange

The first thing that comes to mind is the visibilityChange native event, referred to as MDN, which triggers the VisiBilityChange event on the document when the contents of its tabs become visible or hidden. There is a library called vue-visition-change that can be used.

But it has some problems:

  1. visibilitychangeNative events aren’t very compatible and Safari won’t be able to use them, even if they arevue-visibility-changeThe results were not much better. And on the Android client, end wechat operation within 5s,visibilitychangeThe trigger effect can be seen, but not after 5s. We need to use JsBridge to let the Android client tell the Web page to appear. Even with the assistance of JsBridge, the first time you enter the payment order page, you can see the toast that JsBridge triggers popping up. It mainly depends on the loading status of the Web page in the WebView page. If the loading is slow, the toast will not be seen (the toast has ended before loading). If the loading is fast, the toast prompt that you do not want to see will be displayed.
  2. In addition to returning from the wechat payment page can be monitored, the page can still be monitored when switching back from the background, so this consideration is relatively more.
  3. Because there is no payment confirmation popup, the performance of successful payment within 5s and after 5S is different from that of return after cancelling payment. Considering the environment of Android and IOS, and the compatible performance of multiple different browsers, all kinds of weird phenomena are numerous.

The plan was finally abandoned.

B. History. Length

The payment code is aggregated in the payment order page, which is a separate page. Enter the wechat page, and then return to the payment page, the history will continue to accumulate. Therefore, history.length (hLlength) can be used as an example.

From commodity to payment order page, hLlength is 1 because the payment order page is a new page. When entering wechat page, hLlength will be increased by 1 and finally return to the order page.

Therefore, as long as hLlength is determined to be 2, the confirmation of payment popup can pop up in theory.

Ideal is full, reality is very skinny. Strange things happen. Here’s how mobile browsers performed.

  • When entering a new page, Safari has an hLlength of 2, while Chrome and the Chrome kernel normally have an hLlength of 1.

  • If you skip to wechat Pay, the Llength of Safari and Chromeh increases by 1, but the hLlength of OPPO’s built-in browser does not.

  • The hLlength of webView in Android client is normal.

Because the hLlength performance of different browsers is different, it is impossible to predict the performance of untested browsers, so this scheme is also passed.

(3) Redirect parameter markers

H5 payment callback page. Normal process After the payment is complete, the user is returned to the page that initiates the payment. If the user needs to return to the specified page, add the redirect_URL parameter after MWEB_URL to specify the callback page.

If there is no payment confirmation box, the page performance is different from the payment back, so it is necessary to have a payment confirmation box to send a check operation, so as to judge whether the payment is completed. If you do not specify redirect_URL, you will go back to the original payment to page. Since this is an old page, you cannot continue to trigger the Created hook. Redirect_url and is_redirect=1 can trigger the created hook by specifying redirect_URL and adding is_redirect=1 to the new page.

Computed :{// Pay successfully from wechat, cancel return isRedirectFromWechat() {const is_redirect= location.search. Match (/is_redirect=(\d+)/); return !! (is_redirect && is_redirect[1] === "1"); }}, // return from wechat pay page, because it is returned by redirect_URL, so it will be a new page, Can trigger created hook created () {if (this. IsRedirectFromWechat) {this. $modal. The show (); // TOOD } }Copy the code

This scheme can stably open the payment confirmation box.

But there are some side effects:

  • The URL that comes back with the payment will be broughtis_redirect=1If you refresh the page, the confirmation box will continue to trigger.
  • The stack of History is the payment order page — the middle page of wechat — the payment order page. If you cancel the pop-up box and do not do any processing, click the back button, it will return to the wechat Payment page, and return to the Payment order page on android client, with a close button on the upper right corner (inconsistent with the initial page).

So you can do some articles in the payment confirmation box.

  1. Click “unpaid” to cancel the confirmation box and remain on the order payment page. The directhistory.go(-2);, perfect return to the original payment order page, no side effects.
  2. Click “Paid” and send a check request. If it is successful, toast will prompt “successful payment” and return to the product details page 1s later. If it fails, Toast will prompt “failed payment” and remain on the payment order page. The “payment failed” operation is the same as step 1. If it succeeds, it will delay for a certain amount of time (give toast time) and then close the current page.
Async delayToPage(options) {await sleep(TIMEOUT_DELAY); closeCurrentPage(options); }Copy the code

The code that closes the current page can be wrapped together.

Const closeWindow = () => {if (window.close) {window.close(); return; } window.opener = null; const t = window.open('', '_self', ''); t.close(); } // close the current page const closeCurrentPage = ({isSuccess} = {}) => {// if (isPlatform()) { If (isSuccess) {window.location.href = 'schema://close_webview'; ** * Android pay order page is a WebView, the bottom is the order page, the middle is the wechat pay page, 'window.location.href = mweb_URL; 'history + 1; * Jump to wechat page and add 1 to history; * Cancel wechat pay, redirect to payment page, add 1 to history, then the total is 3; * Use history.go(-2) to jump to the original payment page. */ else { history.go(-2); } return; If (isSuccess) {closeWindow(); return; } // For other browsers, go back two steps to history.go(-2); };Copy the code

At this point, wechat H5 payment key code has been completed.

(4) localStorage

In the case of CodereView, some colleagues recommended that state changes can also be recorded through localStorage. If you haven’t tested it, you can try again.

5. JSAPI Payment

JSAPI payment in wechat, relying on wechat public account, configuration refer to the second part.

The development steps are as follows:

  1. Enter the authorization page to approve authorization and obtain the code

    In the Created hook function, trigger getCode.

    Const getCode = (url) = > {/ / access code const redirect_uri url = | | window. The location. The href; let state = parseInt(Math.random() * 1000); // APP_ID const path = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${encodeURIComponent(redirect_uri)}&re sponse_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`; window.location.replace(path); };Copy the code
  2. Exchange web page authorization access_token with code

    Pass the code value obtained in the previous step (in the URL parameter) to the back end for processing, and the front end will have cross-domain.

    Request access code, the following links for access_token: api.weixin.qq.com/sns/oauth2/…

  3. After a series of processing, the backend obtains the parameters of participating signature as appId, timeStamp, nonceStr, Package, signType and paySign.

    Then the front end invokes the following method to evoke payment in wechat browser.

    Function onBridgeReady(){// WeixinJSBridge is a built-in object in wechat, Invoke ('getBrandWCPayRequest', {"appId":" wx2421B1C4370EC43b ", // Public id name, "TimeStamp ":"1395712654", Since 1970, the number of seconds "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", / / a random string of "package" : "prepay_id = u802345jgfjsdfgsdg888", "SignType ":"MD5", // "PaySign" : "70 ea570631e4bb79628fbca90534c63ff7fadd89" / / WeChat signature}, Function (res){// get_brand_wcpay_request:cancel The payment process. // get_brand_wcpay_request:fail The payment fails. If (res.err_msg == "Get_brand_wcpay_request: OK"){// Use the above method to judge the front end return, wechat team seriously warning: //res.err_msg will return OK after the user paid successfully, but does not guarantee that it is absolutely reliable. }}); } 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 payment has a callback function, so the effect of the payment is very controllable. Go (-1) directly after successful payment by wechat; , you can return directly to the product details page. Cancel or fail to stay on the current page.

6. Problems encountered during development

Redirect_url: redirect_URL: redirect_URL: redirect_URL: redirect_URL: redirect_URL: redirect_URL: redirect_URL For other problems, go directly to your backend developer.

Once the second step is configured, development is smooth. Otherwise, most of them are configured incorrectly.