Table of Contents
同时支持 H5 支付和 JSAPI 支付
注意事项
参考
总结
Home WeChat Applet Mini Program Development Sorting out the WeChat payment process from a front-end perspective

Sorting out the WeChat payment process from a front-end perspective

Dec 09, 2020 pm 05:56 PM
WeChat Pay

WeChat Mini Program Development Tutorial Sorting out the process of WeChat payment

Sorting out the WeChat payment process from a front-end perspective

##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)
Before using WeChat payment, you must open a WeChat merchant account. To use that payment method, you must open it on the merchant platform (subject to review).

The money paid will eventually go to the merchant account (usually opened by the company's finance).

During the process of developing WeChat Pay, I still encountered a lot of pitfalls, big and small. I finally finished it and organized the development process.

Reference:

    WeChat Payment-Access Guide
  • WeChat Payment-Development Document
Mini Program Payment

Development process

    The applet requests to create an order interface, and the backend places an order to obtain
  1. orderId and returns
  2. The applet obtains it through wx.login () Get
  3. code
  4. The applet uses this
  5. code and orderId to request the backend interface and obtain the data required for payment
  6. After obtaining the data required for payment, the applet calls the wx.requestPayment() interface and directly calls the payment page
  7. Logic to determine whether payment is successful
Pseudocode

async function wxPay(goodId) {
  // 1. 创建订单 获取orderId
  let orderId = await ajax("POST", "/api/OrderProgram/CreateTheOrder", {
    goodId, // 商品id
  });
  // 2. 获得 code
  let code = await wxlogin(); // 基于pr封装的wx.login()方法
  // 3. 获取支付的数据
  let payData = await ajax("POST", "/api/OrderProgram/WxXcxPay", {
    orderId,
    code,
  });
  // 4. 发起支付
  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("支付失败");
  }
}
Copy after login

Notes

    Apply for a WeChat mini program account
  1. 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
  2. WeChat Mini Program Authentication
  3. Only mini programs that have passed the certification can access WeChat Payment and bind the merchant platform
  4. Apply for a merchant platform account
  5. 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)
  6. The merchant number associated with the WeChat mini program
  7. After both WeChat and the merchant are successfully authenticated, Connect in the WeChat payment menu in the WeChat background
  8. Access to WeChat payment
  9. Connect in the WeChat payment menu in the WeChat background
H5 payment

Development Process

    The front-end requests to create an order interface, and the back-end places an order uniformly to obtain the
  1. orderId and returns
  2. The front-end requests payment with
  3. orderId Interface, get mweb_url,
  4. and then jump to
  5. mweb_url will jump to WeChat and automatically call WeChat payment
  6. After payment, return to the payment page to determine whether to pay. Successful (need to send request to backend query)
  7. 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.
Pseudocode

async function wxH5Pay(goodId) {
  // 1. 创建订单 获取orderId
  let orderId = await ajax("POST", "/api/OrderProgram/CreateTheOrder", {
    goodId, // 商品id
  });
  // 2. 获取支付跳转的URL
  let mweb_url = await ajax("POST", "/api/OrderProgram/WxH5Pay", { orderId });
  // 3. 跳转URL去微信支付
  if (mweb_url) {
    location.href = mweb_url;
  } else {
    console.log("回调地址出错");
  }
  // 4. 支付后返回支付页,判断是否支付成功
  // 4.1 刷新页面,获取最新的订单(商品)状态。
  // 4.2 设置一个"我已支付"的按钮,让用户点击之后查询状态。
}
Copy after login

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_urlurlencodeprocess
  • H5 payment cannot be made directly on WeChat customers To load it within the client, please load it in an external browser.
Reference

    WeChat payment-H5 payment-development steps
JSAPI payment (webpage payment within WeChat)

Development process

    Product page
    Create an order on the front-end product page, and obtain the
  1. orderId# after placing the unified order on the back-end ##The front end jumps to the payment page with
  2. orderId
  3. ,
Payment page
    Get
  1. code

    Enter the page for the first time, determine whether there is
      code
    1. in the path, but not
    2. code
    3. , and request data jump On the sub-authorization page, code will be returned together through the callback address. gets the
    4. code
    5. and sends it to the backend, which parses it to openid ,keep properly.
  2. Click the Confirm Payment button to trigger the
  3. wxPay()

    method

    Send
      orderId
    1. to the post terminal, obtain the data of wx.config and wx.chooseWXPay contained in
    2. wxData
    3. wxData. First call
    4. wx.config()
    5. and then call wx.chooseWXPay(). If everything is normal, the payment page will pop up.
    The payment status is queried through the backend
  4. Pseudo code

Product page
  • // 1. 创建订单 获取orderId
    let orderId = await ajax("POST", "/api/OrderProgram/CreateTheOrder", {
      goodId, // 商品id
    });
    // 2. 携带id 跳转到支付页
    this.$router.push({ name: "wx_pay_page", params: { orderId: id } });
    Copy after login
Entry file (
    main.js
  • )
    // main.js 引入 js-sdk
    import wx from "weixin-js-sdk";
    Copy after login
    Payment page HTML
  • <template>
      <p>
        <button @click="wxPay">点击支付</button>
      </p>
    </template>
    Copy after login
Payment page JS

// Vue
data(){
    return {
        orderId: this.$route.params.orderId, // 订单id
        url: '',// 获取code的url
        wxData: null,// js-sdk接口所需的数据
    }
},
mounted(){
    // 判断是否有code
    this.getCode()
}
methods: {
    getCode() {
        var code = this.getUrlPram("code");
        if (code != null) {
            this.code = code;
            // 拿到 code 发给 后端
            this.sendCode(code);
        } else {
            // 去拿code
            this.getUrl();
        }
    },
    getUrl() {
        // 请求后端拿到url所需数据,然后跳转页面在通过回调地址返回,获取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) {
        // 发送code给后端 后端解析出openid
        this.axios
            .post("/api/OrderProgram/GetOpenidAndAccessTokenFromCode", {
                code: code,
            })
            .then((res) => {
                console.log(res);
            })
            .catch((err) => {
                console.log(err);
            });
    },
    wxPay: async function() {
        // 发送orderid,获取wx.chooseWXPay和wx.config所需的参数
        this.wxData = await this.axios.post(
            "/api/OrderProgram/WxJSAPIPay",
            { orderId: this.orderId }
        );
        let wxConfigData = this.wxData.wxConfigData // 获取wx.chooseWXPay()所需数据
        let wxPayData = this.wxData.wxPayData;// 获取wx.config()所需数据
        this.$wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: wxConfigData.appId, // 必填,公众号的唯一标识
            timestamp: wxConfigData.timeStamp, // 必填,生成签名的时间戳
            nonceStr: wxConfigData.nonceStr, // 必填,生成签名的随机串
            signature: wxConfigData.paySign, // 必填,签名
            jsApiList: [
                "chooseWXPay",
            ],
        });
        // 执行支付
        this.$wx.chooseWXPay({
            timestamp: wxPayData.timeStamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
            nonceStr: wxPayData.nonceStr, // 支付签名随机串,不长于 32 位
            package: wxPayData.package, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
            signType: wxPayData.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
            paySign: wxPayData.paySign, // 支付签名
            success: (res) => {
                this.$toast("支付成功");
            },
            fail: (err) => {
                this.$toast("支付失败");
            },
        });
    },
}
Copy after login

同时支持 H5 支付和 JSAPI 支付

// 在创建订单之后,就判断环境使用哪种方法支付。
if (isWx()) {
  this.WXPay(orderId); // 带着orderId跳转到支付页逻辑
} else {
  this.H5Pay(orderId); // 执行上面H5支付中的创建订单之后的逻辑
}
// 判断是否是微信浏览器
function isWx() {
  let uAgent = navigator.userAgent.toLowerCase();
  reutrn(/micromessenger/.test(uAgent)) ? true : false;
}
Copy after login

注意事项

  • 开通微信商户号 - 设置支付目录(如果是 Vue 这类 SPA 页面,到根目录即可,也就是#号之前的地址)
  • 开通微信公众号(服务号) - 设置安全域名、设置授权域名
  • 收集参数:appId 和 AppSecret
  • 添加 Web 开发工具开发者(需要开发者同时开发者关注开发的微信公众号和微信公众账号安全助手)参考文档
    [图片上传失败...(image-b07878-1605777597831)]
  • 设置回调域名(例如:www.xx.com/pay,最后获取的 code 会拼在此回调地址后返回,返回后如www.xx.com/pay?code=xxxx
  • 获取 code

    • 参考获取 code 文档
    • 在微信客户端网页打开授权地址,跳转之后,在返回的回调地址之后拿到 code
https://open.weixin.qq.com/connect/oauth2/authorize
?appid=你的appid
&redirect_uri=你的回调地址(拿到code后返回)
&response_type=code(返回类型,默认code)
&scope=snsapi_base(授权范围,静默授权拿到openid)
&state=STATE(自定义状态,非必填)
#wechat_redirect(重定向使用必须携带)
Copy after login

redirect_uri参数要和你在微信公众号里设置的回调域名一致(例如:www.xx.com/pay),需要注意的是这 url 需要urlEncode

请求这个地址之后,code 会以你设置的redirect_uri地址里的参数带回来,拿到之后传给后端就行了。

  • 前端引入 js-skd

    • 使用script引入js-sdk
    • 下载使用 npm 包weixin-js-sdk
  • 获取 wx.config 的参数
  • 获取 wx.chooseWXPay 所需的参数

参考

  • 微信支付-JSAPI
  • 微信公众号-网页授权
  • JS-SDK 开发文档

总结

整个流程走下来,给我的体验是:小程序支付最方面(因为配置少),其次是 H5,JSAPI 支付最麻烦(文章一多半都在写它)

在微信支付功能开发过程中,其实最麻烦的不是开发流程,而是他的各种配置和授权流程,为了拿到所需的参数而来回折腾。

开发过程中的一些参数是经常用到的,如 appid、openid、orderId

支付流程大径相同,先获取到用户的 openid,知道你是谁,然后统一下单拿到 orderId 再去处理不同平台的支付方式

开发时候用到的相关文档,一定要仔细阅读二遍以上为止!!

遇到问题不要死刚,多百度多 Google,说不准你遇到的问题已经有无数的人遇到过并且已经有成熟的解决方案了。

前端和后端要多沟通,有什么问题(难点)随时反馈,需要什么参数好好说,遇到观点不一致的时候千万要注意控制住情绪,切莫撕逼(.——.)。

因为本人水平有限,对后端流程懂得不多,只能以前端的角度来梳理整个支付流程。

以上,希望对你有所帮助。

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

If you forget your WeChat payment password, how to retrieve it? If you forget your WeChat payment password, how to retrieve it? Feb 23, 2024 pm 09:40 PM

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.

What should I do if I forget my WeChat payment password? What should I do if I forget my WeChat payment password? Jan 08, 2024 pm 05:02 PM

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.

How to set up WeChat payment for Meituan Takeout How to set up WeChat payment How to set up WeChat payment for Meituan Takeout How to set up WeChat payment Mar 12, 2024 pm 10:34 PM

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

How to set the order of deduction for WeChat payment How to set the order of deduction for WeChat payment Sep 06, 2023 am 11:11 AM

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.

Can WeChat payment be canceled immediately after successful payment? Can WeChat payment be canceled immediately after successful payment? Nov 29, 2023 pm 02:19 PM

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.

Can Xianyu pay with WeChat? How to change to WeChat payment method? Can Xianyu pay with WeChat? How to change to WeChat payment method? Mar 12, 2024 pm 12:19 PM

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

Does WeChat Pay need to bind a bank card? Does WeChat Pay need to bind a bank card? Nov 17, 2022 am 11:57 AM

WeChat Pay does not need to be bound to a bank card. WeChat payment can be used without binding a bank card, provided that real-name authentication is carried out. As long as the real-name authentication is passed, you can use WeChat change to send red envelopes, transfer, collect money, WeChat payment and other operations. It should be noted that WeChat cannot withdraw cash if it is not bound to a bank card, and there are limits on receipts, payments, transfers, etc., with a maximum of 200 yuan for a single transaction and daily, and a maximum of 500 yuan per month.

How to pay with WeChat on Alibaba_How to pay with WeChat on Alibaba 1688 How to pay with WeChat on Alibaba_How to pay with WeChat on Alibaba 1688 Mar 20, 2024 pm 05:51 PM

Alibaba 1688 is a purchasing and wholesale website, and the items there are much cheaper than Taobao. So how does Alibaba use WeChat payment? The editor has compiled some relevant content to share with you. Friends in need can come and take a look. How does Alibaba use WeChat payment? Answer: WeChat payment cannot be used for the time being; 1. On the page where we purchase goods, we click [Change payment method] 2. Then in the pop-up page, we can only go to [Alipay, staged payment] , cashier] can be selected;

See all articles