


Sorting out the WeChat payment process from a front-end perspective
Dec 09, 2020 pm 05:56 PMWeChat Mini Program Development Tutorial Sorting out the process of WeChat payment
##Recommended: WeChat Mini Program Program Development Tutorial
Due to business needs, the WeChat payment function is developed, involving three payment methods:- JSAPI payment: WeChat webpage payment requires WeChat activation Service number
- Mini program payment: To pay in the mini program, you need to open the mini program
- H5 payment: Pay on the web page in the mobile browser (exit WeChat intranet)
- WeChat Payment-Access Guide
- WeChat Payment-Development Document
- The applet requests to create an order interface, and the backend places an order to obtain
- orderId
and returns
The applet obtains it through wx.login () Get - code
- code
and
orderIdto request the backend interface and obtain the data required for payment
After obtaining the data required for payment, the applet calls the wx.requestPayment() interface and directly calls the payment page - Logic to determine whether payment is successful
async?function?wxPay(goodId)?{
??//?1.?創(chuàng)建訂單?獲取orderId
??let?orderId?=?await?ajax("POST",?"/api/OrderProgram/CreateTheOrder",?{
????goodId,?//?商品id
??});
??//?2.?獲得?code
??let?code?=?await?wxlogin();?//?基于pr封裝的wx.login()方法
??//?3.?獲取支付的數(shù)據(jù)
??let?payData?=?await?ajax("POST",?"/api/OrderProgram/WxXcxPay",?{
????orderId,
????code,
??});
??//?4.?發(fā)起支付
??let?res?=?await?payment(payData);?//?基于pr封裝的wx.requestPayment()方法
??//?5.?判斷是否支付成功
??let?payResult?=?res.errMsg;
??if?(payResult?==?"requestPayment:ok")?{
????console.log("支付成功");
??}?else?if?(payResult?==?"requestPayment:fail?cancel")?{
????console.log("用戶取消支付");
??}?else?{
????console.log("支付失敗");
??}
}
Notes
- Apply for a WeChat mini program account
- If you apply successfully, you can get the AppID (mini program id) and AppSecret (mini program key)
The application type is Enterprise nature, otherwise you cannot access WeChat Payment
WeChat Mini Program Authentication - Only mini programs that have passed the certification can access WeChat Payment and bind the merchant platform
Apply for a merchant platform account - The AppID that needs to be applied for in the first step
If the application is successful, you can get MchID (merchant id) and MchKey (merchant key)
The merchant number associated with the WeChat mini program - After both WeChat and the merchant are successfully authenticated, Connect in the WeChat payment menu in the WeChat background
Access to WeChat payment - Connect in the WeChat payment menu in the WeChat background
- The front-end requests to create an order interface, and the back-end places an order uniformly to obtain the
- orderId
and returns
The front-end requests payment with - orderId
Interface, get
mweb_url,
and then jump to - mweb_url
will jump to WeChat and automatically call WeChat payment
After payment, return to the payment page to determine whether to pay. Successful (need to send request to backend query) - 4.1 Refresh the page to obtain the latest payment (order) status.
4.2 Set a button "I have paid" to allow users to click to automatically check the status.
async?function?wxH5Pay(goodId)?{
??//?1.?創(chuàng)建訂單?獲取orderId
??let?orderId?=?await?ajax("POST",?"/api/OrderProgram/CreateTheOrder",?{
????goodId,?//?商品id
??});
??//?2.?獲取支付跳轉(zhuǎn)的URL
??let?mweb_url?=?await?ajax("POST",?"/api/OrderProgram/WxH5Pay",?{?orderId?});
??//?3.?跳轉(zhuǎn)URL去微信支付
??if?(mweb_url)?{
????location.href?=?mweb_url;
??}?else?{
????console.log("回調(diào)地址出錯(cuò)");
??}
??//?4.?支付后返回支付頁,判斷是否支付成功
??//?4.1?刷新頁面,獲取最新的訂單(商品)狀態(tài)。
??//?4.2?設(shè)置一個(gè)"我已支付"的按鈕,讓用戶點(diǎn)擊之后查詢狀態(tài)。
}
Notes
- Set the correct payment domain name on the merchant platform
- Debugging needs to be online. If you are in trouble, you can use intranet penetration (Ngrok or peanut shell)
- Need to
- redirect_url
urlencode
process
H5 payment cannot be made directly on WeChat customers To load it within the client, please load it in an external browser.
- WeChat payment-H5 payment-development steps
- Product page
- Create an order on the front-end product page, and obtain the
- orderId
# after placing the unified order on the back-end ##The front end jumps to the payment page with
orderId - ,
- Get
- code
Enter the page for the first time, determine whether there is- code
-
in the path, but not
code - , and request data jump On the sub-authorization page,
code
will be returned together through the callback address.gets the
code - and sends it to the backend, which parses it to
openid
,keep properly.
Click the Confirm Payment button to trigger the -
- wxPay()
method
Send- orderId
- to the post terminal, obtain the data of
wx.config
andwx.chooseWXPay
contained in wxData -
wxData
.First call
wx.config() - and then call
wx.chooseWXPay()
. If everything is normal, the payment page will pop up.
- to the post terminal, obtain the data of
- Pseudo code
//?1.?創(chuàng)建訂單?獲取orderId let?orderId?=?await?ajax("POST",?"/api/OrderProgram/CreateTheOrder",?{ ??goodId,?//?商品id }); //?2.?攜帶id?跳轉(zhuǎn)到支付頁 this.$router.push({?name:?"wx_pay_page",?params:?{?orderId:?id?}?});
- main.js
- )
//?main.js?引入?js-sdk import?wx?from?"weixin-js-sdk";
- Payment page HTML
-
<template> ??<p> ????<button @click="wxPay">點(diǎn)擊支付</button> ??</p> </template>
獲取 code 請(qǐng)求這個(gè)地址之后, 前端引入 js-skd 整個(gè)流程走下來,給我的體驗(yàn)是:小程序支付最方面(因?yàn)榕渲蒙伲?,其次?H5,JSAPI 支付最麻煩(文章一多半都在寫它) 在微信支付功能開發(fā)過程中,其實(shí)最麻煩的不是開發(fā)流程,而是他的各種配置和授權(quán)流程,為了拿到所需的參數(shù)而來回折騰。 開發(fā)過程中的一些參數(shù)是經(jīng)常用到的,如 appid、openid、orderId 支付流程大徑相同,先獲取到用戶的 openid,知道你是誰,然后統(tǒng)一下單拿到 orderId 再去處理不同平臺(tái)的支付方式 開發(fā)時(shí)候用到的相關(guān)文檔,一定要仔細(xì)閱讀二遍以上為止?。?/p>
遇到問題不要死剛,多百度多 Google,說不準(zhǔn)你遇到的問題已經(jīng)有無數(shù)的人遇到過并且已經(jīng)有成熟的解決方案了。 前端和后端要多溝通,有什么問題(難點(diǎn))隨時(shí)反饋,需要什么參數(shù)好好說,遇到觀點(diǎn)不一致的時(shí)候千萬要注意控制住情緒,切莫撕逼(.——.)。 因?yàn)楸救怂接邢?,?duì)后端流程懂得不多,只能以前端的角度來梳理整個(gè)支付流程。 以上,希望對(duì)你有所幫助。//?Vue
data(){
????return?{
????????orderId:?this.$route.params.orderId,?//?訂單id
????????url:?'',//?獲取code的url
????????wxData:?null,//?js-sdk接口所需的數(shù)據(jù)
????}
},
mounted(){
????//?判斷是否有code
????this.getCode()
}
methods:?{
????getCode()?{
????????var?code?=?this.getUrlPram("code");
????????if?(code?!=?null)?{
????????????this.code?=?code;
????????????//?拿到?code?發(fā)給?后端
????????????this.sendCode(code);
????????}?else?{
????????????//?去拿code
????????????this.getUrl();
????????}
????},
????getUrl()?{
????????//?請(qǐng)求后端拿到url所需數(shù)據(jù),然后跳轉(zhuǎn)頁面在通過回調(diào)地址返回,獲取code.
????????this.axios
????????????.post("/api/OrderProgram/GetOpenidAndAccessToken",?{
????????????????orderId:?this.orderId,
????????????})
????????????.then((data)?=>?{
????????????????this.url?=?`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${data.appId}&redirect_uri=${data.redirect_uri}&response_type=${data.response_type}&scope=${data.scope}&state=${data.state}`;
????????????????window.location.href?=?this.url;
????????????})
????????????.catch((err)?=>?{
????????????????console.log(err);
????????????});
????},
????sendCode(code)?{
????????//?發(fā)送code給后端?后端解析出openid
????????this.axios
????????????.post("/api/OrderProgram/GetOpenidAndAccessTokenFromCode",?{
????????????????code:?code,
????????????})
????????????.then((res)?=>?{
????????????????console.log(res);
????????????})
????????????.catch((err)?=>?{
????????????????console.log(err);
????????????});
????},
????wxPay:?async?function()?{
????????//?發(fā)送orderid,獲取wx.chooseWXPay和wx.config所需的參數(shù)
????????this.wxData?=?await?this.axios.post(
????????????"/api/OrderProgram/WxJSAPIPay",
????????????{?orderId:?this.orderId?}
????????);
????????let?wxConfigData?=?this.wxData.wxConfigData?//?獲取wx.chooseWXPay()所需數(shù)據(jù)
????????let?wxPayData?=?this.wxData.wxPayData;//?獲取wx.config()所需數(shù)據(jù)
????????this.$wx.config({
????????????debug:?false,?//?開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過log打出,僅在pc端時(shí)才會(huì)打印。
????????????appId:?wxConfigData.appId,?//?必填,公眾號(hào)的唯一標(biāo)識(shí)
????????????timestamp:?wxConfigData.timeStamp,?//?必填,生成簽名的時(shí)間戳
????????????nonceStr:?wxConfigData.nonceStr,?//?必填,生成簽名的隨機(jī)串
????????????signature:?wxConfigData.paySign,?//?必填,簽名
????????????jsApiList:?[
????????????????"chooseWXPay",
????????????],
????????});
????????//?執(zhí)行支付
????????this.$wx.chooseWXPay({
????????????timestamp:?wxPayData.timeStamp,?//?支付簽名時(shí)間戳,注意微信jssdk中的所有使用timestamp字段均為小寫。但最新版的支付后臺(tái)生成簽名使用的timeStamp字段名需大寫其中的S字符
????????????nonceStr:?wxPayData.nonceStr,?//?支付簽名隨機(jī)串,不長于?32?位
????????????package:?wxPayData.package,?//?統(tǒng)一支付接口返回的prepay_id參數(shù)值,提交格式如:prepay_id=\*\*\*)
????????????signType:?wxPayData.signType,?//?簽名方式,默認(rèn)為'SHA1',使用新版支付需傳入'MD5'
????????????paySign:?wxPayData.paySign,?//?支付簽名
????????????success:?(res)?=>?{
????????????????this.$toast("支付成功");
????????????},
????????????fail:?(err)?=>?{
????????????????this.$toast("支付失敗");
????????????},
????????});
????},
}
同時(shí)支持 H5 支付和 JSAPI 支付
//?在創(chuàng)建訂單之后,就判斷環(huán)境使用哪種方法支付。
if?(isWx())?{
??this.WXPay(orderId);?//?帶著orderId跳轉(zhuǎn)到支付頁邏輯
}?else?{
??this.H5Pay(orderId);?//?執(zhí)行上面H5支付中的創(chuàng)建訂單之后的邏輯
}
//?判斷是否是微信瀏覽器
function?isWx()?{
??let?uAgent?=?navigator.userAgent.toLowerCase();
??reutrn(/micromessenger/.test(uAgent))???true?:?false;
}
注意事項(xiàng)
[圖片上傳失敗...(image-b07878-1605777597831)]www.xx.com/pay
,最后獲取的 code 會(huì)拼在此回調(diào)地址后返回,返回后如www.xx.com/pay?code=xxxx
code
:https://open.weixin.qq.com/connect/oauth2/authorize
?appid=你的appid
&redirect_uri=你的回調(diào)地址(拿到code后返回)
&response_type=code(返回類型,默認(rèn)code)
&scope=snsapi_base(授權(quán)范圍,靜默授權(quán)拿到openid)
&state=STATE(自定義狀態(tài),非必填)
#wechat_redirect(重定向使用必須攜帶)
redirect_uri
參數(shù)要和你在微信公眾號(hào)里設(shè)置的回調(diào)域名一致(例如:www.xx.com/pay
),需要注意的是這 url 需要urlEncode
。code
會(huì)以你設(shè)置的redirect_uri
地址里的參數(shù)帶回來,拿到之后傳給后端就行了。
script
引入js-sdknpm
包weixin-js-sdkwx.config
的參數(shù)
wx.chooseWXPay
所需的參數(shù)
參考
總結(jié)
The above is the detailed content of Sorting out the WeChat payment process from a front-end perspective. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

In WeChat, users can enter their payment password to make purchases, but how do they retrieve their payment password if they forget it? Users need to go to My-Services-Wallet-Payment Settings-to recover their payment password if they forget it. This introduction to how to retrieve your payment password if you forget it will tell you the specific operation method. The following is a detailed introduction, so take a look! WeChat usage tutorial. How to find the WeChat payment password if you forget it? Answer: My-Service-Wallet-Payment Settings-Forgot payment password. Specific method: 1. First, click My. 2. Click on the service inside. 3. Click on the wallet inside. 4. Find the payment settings. 5. Click Forgot payment password. 6. Enter your own information for verification. 7. Then enter the new payment password to change it.

Solution for forgetting WeChat payment password: 1. Open WeChat APP, click "I" in the lower right corner to enter the personal center page; 2. In the personal center page, click "Pay" to enter the payment page; 3. On the payment page , click "..." in the upper right corner to enter the payment management page; 4. In the payment management page, find and click "Forgot payment password"; 5. Follow the page prompts and enter personal information for identity verification. After successful verification, you can Choose the method of "retrieve by swiping your face" or "retrieve by verifying bank card information" to retrieve your password, etc.

Steps to set the order of deductions for WeChat payment: 1. Open the WeChat APP, click on the "Me" interface, click on "Services", and then click on "Collect and Payment"; 2. Click on "Prioritize Use This Payment Method" under the payment code on the collection and payment interface; 3. Select the preferred payment method you need.

There are many food and snack shops provided in the Meituan takeout app, and all mobile phone users log in through their accounts. Add your personal delivery address and contact number to enjoy the most convenient takeout service. Open the homepage of the software, enter product keywords, and search online to find the corresponding product results. Just swipe up or down to purchase and place an order. The platform will also recommend dozens of nearby restaurants with high reviews based on the delivery address provided by the user. The store can also set up different payment methods. You can place an order with one click to complete the order. The rider can arrange the delivery immediately and the delivery speed is very fast. There are also takeout red envelopes of different amounts for use. Now the editor is online in detail for Meituan takeout users. We show you how to set up WeChat payment. 1. After selecting the product, submit the order and click Now

When everyone has nothing to do, they will choose to browse the Xianyu platform. Everyone can find that there are a large number of products on this platform, which can allow everyone to see various second-hand products. Although these products are second-hand products, there is absolutely no problem with the quality of these products, so everyone can buy them with confidence. The prices are very affordable, and they still allow everyone to face-to-face with these products. It is entirely possible for sellers to communicate and conduct some price bargaining operations. As long as everyone negotiates properly, then you can choose to conduct transactions, and when everyone pays here, they want to make WeChat payment, but it seems that the platform It's not allowed. Please follow the editor to find out what the specific situation is. Xianyu

WeChat payment cannot be canceled immediately after successful payment. Refunds usually need to meet the following conditions: 1. The merchant's refund policy. The merchant will formulate its own refund policy, including the refund time window, refund amount and refund method; 2. Payment time, refunds usually require Apply within a certain time frame, and refunds may not be possible beyond this time frame; 3. Goods or service status. If the user has received the goods or enjoyed the service, the merchant may require the user to return the goods or provide corresponding proof; 4. Refund process, etc.

The Didi Chuxing app provides more convenience for everyone's daily travel. You can go wherever you want, and all Didi vehicles are on call. You no longer need to wait anxiously. Dozens of taxi red envelopes are available for free. Travel faster. Open the homepage of the software, enter the starting point and destination according to your personal itinerary, and freely choose from vehicles of different prices below. Place an order with one click and publish the itinerary. Didi drivers will receive the order in seconds and arrive at the designated location as quickly as possible. For the location, just check your mobile phone number before getting on the bus. Of course, there are many ways to pay for the fare, including WeChat and Alipay, but everyone usually uses WeChat. It is easy to set up payment with one click. Now the editor is online carefully paying for Didi one by one. Travel users bring how to set up WeChat payment. 1. We are on the mobile phone

1. First, we need to open the WeChat APP on the mobile phone, and then click to log in to the WeChat account, so that we enter the WeChat homepage. 2. Click the [Me] button in the lower right corner of the WeChat homepage, then select the [Payment] option. We click to enter the payment page. 3. After entering the [Payment] page, click the [Wallet] option to enter, and click [Bill] in the upper right corner of the [Wallet] page.
