Home  >  Article  >  Web Front-end  >  How to use uniapp to implement WeChat payment function

How to use uniapp to implement WeChat payment function

PHPz
PHPzOriginal
2023-04-20 15:05:389036browse

Uniapp is a cross-platform development framework based on Vue.js, which can be used to quickly develop applications for multiple platforms such as mini programs, Apps and H5. In uniapp, we can implement online payment function by integrating WeChat payment, allowing users to purchase goods or services in the application.

This article will introduce how to use uniapp to implement WeChat payment function, including registering a WeChat payment account, configuring payment parameters, calling the payment interface and other steps.

1. Register a WeChat payment account
To use the WeChat payment function, we must first register a WeChat payment merchant account. If you already have a WeChat official account or mini program, you can directly upgrade it to a payment account. , otherwise you need to go to the WeChat Pay official website to register.

After the registration is completed, you need to submit the corresponding information for real-name authentication. After passing the authentication, you can log in to the merchant platform and complete subsequent payment-related operations.

2. Create a merchant order
After completing the registration of a WeChat merchant payment account, you need to create an order in uniapp so that users can pay online to purchase goods or services. When creating an order, you need to pay attention to the following parameters:

  1. appId: AppID assigned by the WeChat open platform;
  2. timeStamp: timestamp, from January 1, 1970 00: The number of seconds since 00:00;
  3. nonceStr: a random string, no longer than 32 characters;
  4. package: the prepay_id parameter value returned by the unified order interface, the format is as follows: prepay_id=*
  5. signType: signature algorithm, currently supports MD5;
  6. paySign: signature, usually generated by the background.

In uniapp, you can create merchant orders in the following ways:

export default {
  data() {
    return {
      appId: 'XXXXXXXXXXXXXX', // 微信开放平台分配的 AppID
      merchantId: 'XXXXXXXXXXXXX', // 微信支付分配的商户号
      amount: null, // 订单金额,单位为分 
      orderNumber: null // 自定义订单编号
    };
  },
  methods: {
    createPayOrder() {
      // 调用后台接口,获取生成商户订单参数
      let data = {
        appId: this.appId,
        merchantId: this.merchantId,
        amount: this.amount,
        orderNumber: this.orderNumber
      };

      // 发送请求,获取预支付信息
      this.$http.post('/pay/unifiedOrder', data).then(resp => {
        wx.requestPayment({
          // 获取支付信息成功后,使用官方 API 调起微信支付
          timeStamp: resp.data.timeStamp,
          nonceStr: resp.data.nonceStr,
          package: resp.data.package,
          signType: resp.data.signType,
          paySign: resp.data.paySign,
          success(res) {
            console.log('支付成功');
          },
          fail(res) {
            console.log('支付失败');
          },
          complete(res) {
            console.log('支付完成');
          }
        })
      })
    }
  }
}

3. Configure WeChat payment parameters
After creating a merchant order, you need to configure WeChat payment in uniapp Parameters, including merchant number, interface key, certificate, etc. When configuring parameters, you need to pay attention to the following points:

  1. Merchant number: the merchant number assigned by WeChat payment;
  2. Interface key: as the key for merchant signature, it needs to be saved in In the background server;
  3. Certificate path: If you need to use advanced functions such as refunds and red envelopes, you need to upload the certificate to the WeChat payment platform.

In uniapp, you can configure WeChat payment parameters in the following ways:

function getSign(params) {
  let str = '';
  for (let key in params) {
    str += key + '=' + params[key] + '&';
  }
  str += 'key=' + API_KEY;
  return md5(str).toUpperCase();
}

function createPayParams(data) {
  let params = Object.assign({}, data, {
    appid: APP_ID, // 微信开放平台分配的 AppID 
    mch_id: MERCHANT_ID, // 微信支付分配的商户号
    nonce_str: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15), // 随机字符串
    notify_url: NOTIFY_URL, // 异步通知地址,接收微信支付异步通知回调地址
    spbill_create_ip: '127.0.0.1' // 终端IP
  });

  let sign = getSign(params);

  return `
    <xml>
      <appid><![CDATA[${params.appid}]]></appid>
      <attach>支付测试</attach>
      <body>APP支付测试</body>
      <mch_id>${params.mch_id}</mch_id>
      <nonce_str>${params.nonce_str}</nonce_str>
      <notify_url>${params.notify_url}</notify_url>
      <out_trade_no>${data.orderNumber}</out_trade_no>
      <spbill_create_ip>${params.spbill_create_ip}</spbill_create_ip>
      <total_fee>${params.total_fee}</total_fee>
      <trade_type>APP</trade_type>
      <sign>${sign}</sign>
    </xml>
  `;
}

4. Call the payment interface
After configuring the WeChat payment parameters, you can use uniapp The official API provided calls the WeChat payment interface and passes in parameters to implement the online payment function. When calling the payment interface, you need to pay attention to the following points:

  1. The applet or App must have WeChat payment permissions;
  2. Need to pass in payment parameters, including merchant order number and amount , transaction type, etc.;
  3. After the payment is successful, the payment result can be determined by receiving asynchronous notifications from WeChat.

In uniapp, you can call the WeChat payment interface in the following ways:

  let params = {
    appId: APP_ID, // 微信开放平台分配的 AppID
    partnerId: MERCHANT_ID, // 微信支付分配的商户号
    prepayId: prepayId, // 预支付交易会话标识
    package: 'Sign=WXPay', // 扩展字段,暂填写固定值 Sign=WXPay
    nonceStr: nonceStr, // 随机字符串,不长于32位
    timeStamp: timeStamp.toString(), // 时间戳
    sign: getSign({ // 根据微信支付签名算法生成签名
      appId: APP_ID,
      partnerId: MERCHANT_ID,
      prepayId: prepayId,
      package: 'Sign=WXPay',
      nonceStr: nonceStr,
      timeStamp: timeStamp.toString()
    })
  };

  wx.requestPayment({
    appId: APP_ID,
    timeStamp: timeStamp.toString(),
    nonceStr: nonceStr,
    package: params.package,
    signType: 'MD5',
    paySign: params.sign,
    success(res) {
      console.log('支付成功');
    },
    fail(res) {
      console.log('支付失败');
    }
  });

The above are the specific steps for using the WeChat payment function in uniapp, including registering a WeChat payment account and creating merchant orders , configure WeChat payment parameters, call the payment interface, etc. During the application development process, perfect payment functions can greatly improve users’ experience in purchasing goods or services, and increase the conversion rate and revenue of the application or website.

The above is the detailed content of How to use uniapp to implement WeChat payment function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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