Home WeChat Applet Mini Program Development Share the example code tutorial of the mini program payment function

Share the example code tutorial of the mini program payment function

May 26, 2017 am 09:45 AM

The payment of WeChat mini program is similar to the payment of WeChat official account. In comparison, it is simpler than the payment of official account. We only need to call WeChat’s unified ordering interface to obtain the prepay_id, and then we can call WeChat payment. .

Today we will encapsulate the payment interface of general node! ! !

First we need to know some information to call the unified ordering interface

var bookingNo = 'davdian' + this.createNonceStr() + this.createTimeStamp()
    var deferred = Q.defer()  
    var appid = config.appId  
    var nonce_str = this.createNonceStr()  
    var timeStamp = this.createTimeStamp()  
    var url = "https://api.mch.weixin.qq.com/pay/unifiedorder"  
    var formData = "<xml>"  
    formData += "<appid>" + appid + "</appid>" //appid  
    formData += "<attach>" + attach + "</attach>" //附加数据  
    formData += "<body>" + body + "</body>"  
    formData += "<mch_id>" + mch_id + "</mch_id>" //商户号  
    formData += "<nonce_str>" + nonce_str + "</nonce_str>" //随机字符串,不长于32位。  
    formData += "<notify_url>" + notify_url + "</notify_url>"  
    formData += "<openid>" + openid + "</openid>"  
    formData += "<out_trade_no>" + bookingNo + "</out_trade_no>"  
    formData += "<spbill_create_ip>61.50.221.43</spbill_create_ip>"  
    formData += "<total_fee>" + total_fee + "</total_fee>"  
    formData += "<trade_type>JSAPI</trade_type>"  
    formData += "<sign>" + this.paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, bookingNo, &#39;61.50.221.43&#39;, total_fee, &#39;JSAPI&#39;) + "</sign>"  
    formData += "</xml>"  
    var self = this
    request({  
      url: url,  
      method: &#39;POST&#39;,  
      body: formData  
    }, function(err, response, body) {  
      if (!err && response.statusCode == 200) {  
        var prepay_id = self.getXMLNodeValue(&#39;prepay_id&#39;, body.toString("utf-8")) 
        var tmp = prepay_id.split(&#39;[&#39;)  
        var tmp1 = tmp[2].split(&#39;]&#39;)  
        //签名  
        var _paySignjs = self.paysignjs(appid, nonce_str, &#39;prepay_id=&#39; + tmp1[0], &#39;MD5&#39;, timeStamp)  
        var args = {  
          appId: appid,  
          timeStamp: timeStamp,  
          nonceStr: nonce_str,  
          signType: "MD5",  
          package: tmp1[0],  
          paySign: _paySignjs  
        }
        deferred.resolve(args)  
      } else {  
        console.log(body)  
      } 
    })  
    return deferred.promise
Copy after login

This is the code of a unified ordering interface. We need appid applet public account id, mch_id merchant account id, openid small The only identifier of the program is the password for payment. The remaining parameters are the order information and price. I require enter the q module and use promise. This is due to human reasons. It depends on your needs. We need to request the api.mch.weixin.qq.com/pay/unifiedorder interfaceNote: The formdata we pass here is an xml instead of

json

Then we A signature method is required. Here we need to encapsulate two methods. One is used by the signature method to call the unified ordering interface, and the other is used to call the mini program payment

unified ordering interface sign:

var ret = {  
      appid: appid,  
      attach: attach,  
      body: body,  
      mch_id: mch_id,  
      nonce_str: nonce_str,  
      notify_url: notify_url,  
      openid: openid,  
      out_trade_no: out_trade_no,  
      spbill_create_ip: spbill_create_ip,  
      total_fee: total_fee,  
      trade_type: trade_type  
    }  
    var string = this.raw(ret)  
    string = string + &#39;&key=&#39; + key  
    var crypto = require(&#39;crypto&#39;)  
    var sign = crypto.createHash(&#39;md5&#39;).update(string, &#39;utf8&#39;).digest(&#39;hex&#39;)  
    return sign.toUpperCase() 

支付sign:
Copy after login
var ret = {  
        appId: appid,  
        nonceStr: nonceStr,  
        package: package,  
        signType: signType,  
        timeStamp: timeStamp  
    }  
    var string = this.raw(ret)  
    string = string + &#39;&key=&#39; + key  
    var sign = crypto.createHash(&#39;md5&#39;).update(string, &#39;utf8&#39;).digest(&#39;hex&#39;)  
    return sign.toUpperCase()  

注意加密的时候我们获取的是string而不是一个json,所以我们需要吧json转换成string,代码如下:
Copy after login

var keys = Object.keys(args)  
    keys = keys.sort()  
    var newArgs = {}  
    keys.forEach(function(key) {  
        newArgs[key] = args[key]  
    })  
    var string = &#39;&#39;  
    for (var k in newArgs) {  
        string += &#39;&&#39; + k + &#39;=&#39; + newArgs[k]  
    }  
    string = string.substr(1)  
    return string  

统一下单接口返回的是带有prepay_id的xml,所以我们需要一个方法进行解析,代码如下:
Copy after login
var tmp = xml.split("<" + node_name + ">")  
    var _tmp = tmp[1].split("</" + node_name + ">")  
    return _tmp[0]  

最后我们只需要把这些连接到一起就是可以获取所有微信支付所需参数,代码如下:
Copy after login
//微信小程序支付封装,暂支持md5加密,不支持sha1
/**
***create order by jianchep 2016/11/22     
 **/
var config = require('../config/weapp.js')
var Q = require("q")  
var request = require("request")  
var crypto = require('crypto')  
var ejs = require('ejs')
var fs = require('fs')  
var key = config.key
module.exports = {
  // 获取prepay_id
  getXMLNodeValue: function(node_name, xml) {  
    var tmp = xml.split("<" + node_name + ">")  
    var _tmp = tmp[1].split("")  
    return _tmp[0]  
  },
  // object-->string
  raw: function(args) {  
    var keys = Object.keys(args)  
    keys = keys.sort()  
    var newArgs = {}  
    keys.forEach(function(key) {  
        newArgs[key] = args[key]  
    })  
    var string = ''  
    for (var k in newArgs) {  
        string += '&' + k + '=' + newArgs[k]  
    }  
    string = string.substr(1)  
    return string  
  },  
    // 随机字符串产生函数  
  createNonceStr: function() {  
      return Math.random().toString(36).substr(2, 15)  
  },  
  // 时间戳产生函数  
  createTimeStamp: function() {  
      return parseInt(new Date().getTime() / 1000) + ''  
  },
  // 支付md5加密获取sign
  paysignjs: function(appid, nonceStr, package, signType, timeStamp) {  
    var ret = {  
        appId: appid,  
        nonceStr: nonceStr,  
        package: package,  
        signType: signType,  
        timeStamp: timeStamp  
    }  
    var string = this.raw(ret)  
    string = string + '&key=' + key  
    var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex')  
    return sign.toUpperCase()  
  },
  // 统一下单接口加密获取sign
  paysignjsapi: function(appid, attach, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type) {  
    var ret = {  
      appid: appid,  
      attach: attach,  
      body: body,  
      mch_id: mch_id,  
      nonce_str: nonce_str,  
      notify_url: notify_url,  
      openid: openid,  
      out_trade_no: out_trade_no,  
      spbill_create_ip: spbill_create_ip,  
      total_fee: total_fee,  
      trade_type: trade_type  
    }  
    var string = this.raw(ret)  
    string = string + '&key=' + key  
    var crypto = require('crypto')  
    var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex')  
    return sign.toUpperCase()  
  },
  // 下单接口
  order: function(attach, body, mch_id, openid, total_fee, notify_url) {
    var bookingNo = &#39;davdian&#39; + this.createNonceStr() + this.createTimeStamp()
    var deferred = Q.defer()  
    var appid = config.appId  
    var nonce_str = this.createNonceStr()  
    var timeStamp = this.createTimeStamp()  
    var url = "https://api.mch.weixin.qq.com/pay/unifiedorder"  
    var formData = "<xml>"  
    formData += "<appid>" + appid + "</appid>" //appid  
    formData += "<attach>" + attach + "</attach>" //附加数据  
    formData += "<body>" + body + "</body>"  
    formData += "<mch_id>" + mch_id + "</mch_id>" //商户号  
    formData += "<nonce_str>" + nonce_str + "</nonce_str>" //随机字符串,不长于32位。  
    formData += "<notify_url>" + notify_url + "</notify_url>"  
    formData += "<openid>" + openid + "</openid>"  
    formData += "<out_trade_no>" + bookingNo + "</out_trade_no>"  
    formData += "<spbill_create_ip>61.50.221.43</spbill_create_ip>"  
    formData += "<total_fee>" + total_fee + "</total_fee>"  
    formData += "<trade_type>JSAPI</trade_type>"  
    formData += "<sign>" + this.paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, bookingNo, &#39;61.50.221.43&#39;, total_fee, &#39;JSAPI&#39;) + "</sign>"  
    formData += "</xml>"  
    var self = this
    request({  
      url: url,  
      method: &#39;POST&#39;,  
      body: formData  
    }, function(err, response, body) {  
      if (!err && response.statusCode == 200) {  
        var prepay_id = self.getXMLNodeValue(&#39;prepay_id&#39;, body.toString("utf-8")) 
        var tmp = prepay_id.split(&#39;[&#39;)  
        var tmp1 = tmp[2].split(&#39;]&#39;)  
        //签名  
        var _paySignjs = self.paysignjs(appid, nonce_str, &#39;prepay_id=&#39; + tmp1[0], &#39;MD5&#39;, timeStamp)  
        var args = {  
          appId: appid,  
          timeStamp: timeStamp,  
          nonceStr: nonce_str,  
          signType: "MD5",  
          package: tmp1[0],  
          paySign: _paySignjs  
        }
        deferred.resolve(args)  
      } else {  
        console.log(body)  
      } 
    })  
    return deferred.promise  
  }
}

之后我们封装下单接口:
Copy after login
unifiedorder: function (req, res) {
    var body = "测试支付"  
    var openid = "openid"
    var total_fee = 1
    var notify_url = "http://localhost/notify"
    var mch_id = config.shopId
    var attach = "测试"  
    wxpay.order(attach, body, mch_id, openid, total_fee, notify_url)
      .then(function(data){  
        console.log(&#39;data--->&#39;, data, 123123)
        res.json(data)
      })  
  },
Copy after login

Then we only need to call this interface in the mini program, and we will get all the payment information, and then we can make WeChat payment.

Here are some of the pitfalls of small program payment:

1. The unified ordering interface is xml (this is not just for small programs, but also for official accounts), and the return value is also in xml format and needs to be obtained by yourself. prepay_id,

2. The signature algorithm must bring the key, and finally it must be converted to a larger number

3. The sign algorithm of WeChat payment must also bring the appid (this is unscientific, a deep pit)

4. The signature algorithm must not use json to splice key

[Related recommendations]

1.

WeChat Mini Program WeChat Payment Access Development

2.

Detailed explanation of the example of implementing floor anchor point jump in mini program development

3.

Analysis of the code for realizing the online payment function of WeChat mini program

The above is the detailed content of Share the example code tutorial of the mini program payment function. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to pay for a taxi ride on Baidu Maps. Introduction to the payment steps for a taxi ride. How to pay for a taxi ride on Baidu Maps. Introduction to the payment steps for a taxi ride. Mar 13, 2024 am 10:04 AM

Baidu Map APP has now become the preferred travel navigation software for many users, so some of the functions here are comprehensive and can be selected and operated for free to solve some of the problems that you may encounter in daily travel. You can all check some of your own travel routes and plan some of your own travel plans. After checking the corresponding routes, you can choose appropriate travel methods according to your own needs. So whether you choose some public transportation, Cycling, walking or taking a taxi can all satisfy your needs. There are corresponding navigation routes that can successfully lead you to a certain place. Then everyone will feel more convenient if they choose to take a taxi. There are many drivers They are all able to take orders online, and taxi-hailing has become super

How uniapp application implements payment and order management How uniapp application implements payment and order management Oct 19, 2023 am 10:37 AM

uniapp is a cross-platform application development framework that can develop small programs, Apps and H5 at the same time. In uniapp applications, payment and order management are very common needs. This article will introduce how to implement payment functions and order management in the uniapp application, and give specific code examples. 1. Implementing the payment function The payment function is the key to realizing online transactions, and it usually requires integrating the SDK of a third-party payment platform. The following are the specific steps to implement the payment function in uniapp: Register and obtain a third-party payment platform

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Can small programs use react? Can small programs use react? Dec 29, 2022 am 11:06 AM

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

Pay using PHP and PayPal API Pay using PHP and PayPal API Jun 19, 2023 pm 04:13 PM

With the increasing popularity of online transactions, payment methods are gradually diversifying, among which PayPal is very popular as a widely used payment method. If you want to use PayPal to process transactions on your website or application, then you can use PHP and PayPal API to complete the payment process easily. PayPalAPI is a set of programming interfaces for interacting with PayPal. Through the API, you can receive notifications from PayPal, query the latest transaction information, and initiate payments.

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: &lt;!--index.wxml--&gt;&l

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

See all articles