preface

WeChat applet is a small program of electricity business, which provides a very perfect, excellent and safe payment function. In the small program can call WeChat API to complete the payment function, convenient and fast. Small program developers in the development of small programs, payment process is inevitable to contact, today Hu Ge on the whole process of small program payment for everyone one by one, so that small partners can quickly master the ability to pay small programs, to avoid pit!

If you know yourself and know your enemy, you can win a hundred battles

For example, 🌰 :

A user Xiaoming in an e-commerce small program to buy a piece of soap, from browsing, order to pay what kind of process?

  1. Open the small program of e-commerce, search and browse to a carved soap, click to view the details, found that the size, smooth degree is very appropriate, click to place an order directly
  2. Wx. login gets the user’s temporary login certificate code and sends it to the backend server for OpenID
  3. When placing an order, the applet needs to send the ID of the goods purchased by Xiao Ming, the quantity of the goods, and the OpenID of the user Xiao Ming to the server
  4. After receiving the commodity ID, commodity quantity and openID, the server generates the order data of the service period. At the same time, through a certain signature algorithm, it sends a request to the WeChat payment to obtain the prepayment information (prepay_id). At the same time, it will sign the acquired data again with the corresponding rules. Responds to the applet side with the necessary information (required field information is described in more detail below)
  5. After obtaining the corresponding parameters, the applet side calls wx.requestPayment() to initiate WeChat payment, and wakes up the payment workbench to make payment

summary

To make WeChat payments, we mainly do three things on the applet side:

Note: The server calls the unified ordering API and the signature algorithm are not within the scope of this sharing discussion. Please look forward to another sharing from Brother Hu.

  1. Use wx.login to get the temporary login credential code and send it to the back end to get the openID

    Wx.login ({success (res) {if (res.code) {// make a request to OpenID wx.request({url: ", data: {code: res.code}})}})
  2. The OpenID and the corresponding required commodity information is sent to the back end in exchange for the signature and other information carried out by the server

    wx.request({
      url: '',
      data: {
        openId: '',
        num: 1,
        id: '111'
      }
    })
  3. Receive the returned message (must include the parameter to initiate the WeChat payment wx.requestPayment) and initiate the WeChat payment

    Wx. requestPayment({// timeStamp: '', // random string nonceStr: '', // Prepay_id returned by Uniform Order ', / / signature type signType: "', / / signature paySign:" ', / / call the success callback success () {}, / / failure callback fail () {}, end / / interface to invoke the callback complete () {}})

    Note: in the above information
    timeStamp,
    nonceStr ,
    prepay_id,
    signType,
    paySignAll parameters are suggested to be returned by the server (this will ensure the maximum possible consistency of the signature data), and the applet side does not do any processing

WeChat payment instance based on Taro

import Taro, { Component } from '@tarojs/taro' import { View, Text, Button } from '@tarojs/components' import './index.scss' export default class Index extends Component { config = { navigationBarTitleText: } componentWillUnmount () {} componentWillUnMount () {} componentDidShow () {} ComponentDidHide () {} /** * sendorderInfo () * @Description to submit order information, get payment proof, */ async sendorderInfo () {code let codeData = await taro.login () // return openID let openID = "if" (codeData. Code) {let res = await Taro. The request ({/ / backend for openId interfaces defined url: 'https://www.justbecoder.com/getLogin' data: { code: Codedata. code}}) if (res && res.code === = 0) {openID = res. openID}}} let data = await Taro. Requrest ({url: 'https://www.justbecoder.com/createdOrder' data: {openId, / / the actual situation of goods quantity num: 1, / / the actual situation of commodity Id Id: // code === 0 indicates that the order was submitted successfully, If (data&&data. code === 0) {let {timeStamp, nonceStr, prepay_id, signType, PaySign} = data.payInfo // Send the parameters in the format required by the small program let PayData = await Taro. RequestPayment ({timeStamp, nonceStr, package: 'prepay_id=' + prepay_id, signType, PaySign}) if (PayData && PayData. errMsg === 'RequestPayment: OK ') {Taro. ShowModal ({title:' Action prompt ', content: 'Pay successfully ', showCancel: false, confirmText:' confirm '})} else {Taro. ShowModal ({title: 'action prompt ', content: 'Failed to pay, please try again ', showCancel: false, confirmText: }}} render () {return (<View className='index' <Button onClick={this.sendorderInfo}}> </Button> </View>) {return (<View className='index' <Button onClick={this. }}

rendering

conclusion

In the real project operation, you can change the interface to your own available interface.

Afterword.

The above is the content that Hu Ge shared with you today, like small friends remember to collect, forward, click the button in the lower right corner to see, recommend to more small friends Yo, welcome to leave a message to communicate…

Hu elder brother has words, a technology, have feelings of Hu elder brother! Jingdong open platform chief front-end siege lion. Talk with you about the big front end, share the front end system architecture, framework implementation principle, the latest and most efficient technical practice!

Long press sweep code attention, more handsome more beautiful yo! Pay attention to the words of elder brother Hu public number, can continue to in-depth exchanges with elder brother Hu yo!