1.登录到微信支付(https://pay.weixin.qq.com/),提交各种企业资料开通微信支付功能
2.获取商户号和API密钥(初次设置需要先设置操作密码)
小程序端:
testWxCloudPay: function () {
wx.cloud.callFunction({
name: 'getPay',
// data: {body:"body",attach:"attach",total_fee:1}, // 可传入相关参数。
success: res => {
console.log(res.result)
if (!res.result.appId) return
wx.requestPayment({
...res.result,
success: res => {
console.log(res)
}
})
}
})
},
云函数getPay:
const key = "ABC...XYZ" //换成你的商户key,32位
const mch_id = "1413092000" //换成你的商户号
//以下全部照抄即可
const cloud = require('wx-server-sdk')
const rp = require('request-promise')
const crypto = require('crypto')
cloud.init()
function getSign(args) {
let sa = []
for (let k in args) sa.push(k + '=' + args[k])
sa.push('key=' + key)
return crypto.createHash('md5').update(sa.join('&'), 'utf8').digest('hex').toUpperCase()
}
function getXml(args) {
let sa = []
for (let k in args) sa.push('<' + k + '>' + args[k] + '</' + k + '>')
sa.push('<sign>' + getSign(args) + '</sign>')
return '<xml>' + sa.join('') + '</xml>'
}
exports.main = async(event, context) => {
const wxContext = cloud.getWXContext()
const appId = appid = wxContext.APPID
const openid = wxContext.OPENID
const attach = 'attach'
const body = 'body'
const total_fee = 1
const notify_url = "https://mysite.com/notify"
const spbill_create_ip = "118.89.40.200"
const nonceStr = nonce_str = Math.random().toString(36).substr(2, 15)
const timeStamp = parseInt(Date.now() / 1000) + ''
const out_trade_no = "otn" + nonce_str + timeStamp
const trade_type = "JSAPI"
const xmlArgs = {
appid,
attach,
body,
mch_id,
nonce_str,
notify_url,
openid,
out_trade_no,
spbill_create_ip,
total_fee,
trade_type
}
let xml = (await rp({
url: "https://api.mch.weixin.qq.com/pay/unifiedorder",
method: 'POST',
body: getXml(xmlArgs)
})).toString("utf-8")
if (xml.indexOf('prepay_id') < 0) return xml
let prepay_id = xml.split("<prepay_id><![CDATA[")[1].split("]]>")[0]
let payArgs = {
appId,
nonceStr,
package: ('prepay_id=' + prepay_id),
signType: 'MD5',
timeStamp
}
return {
...payArgs,
paySign: getSign(payArgs)
}
}
packge.json:
{
"name": "getPay",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "zfe",
"license": "ISC",
"dependencies": {
"wx-server-sdk": "latest",
"crypto": "^1.0.1",
"request-promise": "^4.2.2"
}
}
相关文档:
Cloud.getWXContext()返回结果详情
参考链接:https://developers.weixin.qq.com/community/develop/article/doc/0004c4a50a03107eaa79f03cc56c13
更新:
云开发后期支持了云开发的支付接口,因此使用如下更简单的方式
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/open/pay/CloudPay.unifiedOrder.html
参考文档:
小程序云开发:现已原生支持微信支付
