小程序云開發(fā)現(xiàn)在越來(lái)越備受開發(fā)者的喜歡,但是如何在云函數(shù)里面接入微信支付分呢兴革?這方面的文檔還比較少绎晃,今天有點(diǎn)空余時(shí)間,簡(jiǎn)單總結(jié)下我在接入微信支付分的一些經(jīng)驗(yàn)
要接入微信支付分之前杂曲,需要寫郵件給騰訊去申請(qǐng),一般要等2到3天時(shí)間回收到回復(fù)
開發(fā)之前需要仔細(xì)閱讀如下接入文檔
https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/payscore/chapter6_1.shtml
- 具體代碼如下箕昭,最麻煩的地方在驗(yàn)證簽名的地方, 官方并沒(méi)有提供nodejs相關(guān)驗(yàn)證簽名的實(shí)例代碼。
//云函數(shù)入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
const moment = require('moment')
const stringRandom = require('string-random');
const request = require('request');
const rp = require('request-promise');
const crypto = require('crypto')
const jsrsasign = require('jsrsasign')
const KEYUTIL = jsrsasign.KEYUTIL
const KJUR = jsrsasign.KJUR
const tenpay = require('tenpay');
const util = require('util');
const forge = require('node-forge');
const fs = require('fs')
const uuid = require('node-uuid');
cloud.init({
env: process.env.ID
})
const db = cloud.database()
const private_key = fs.readFileSync('apiclient_key.pem');
const mchid = "你自己的商戶號(hào)";
const serialNo = "商戶證書號(hào)";
const serviceId = "申請(qǐng)的支付分服務(wù)號(hào)"
const api3Key = "api3 key"
const apiKey = "api key"
const config = {
appid: '您的appid',
mchid: '商戶號(hào)',
partnerKey: apiKey, //就是微信支付賬戶里面設(shè)置的API密鑰
pfx: require('fs').readFileSync('apiclient_cert.p12'), //這是pfx格式的證書,支付不用證書泌霍,但是退款什么的會(huì)用到
notify_url: 'http://www.weixin.qq.com/wxpay/pay.php', //隨便寫一個(gè)货抄,云函數(shù)無(wú)法實(shí)現(xiàn)返回結(jié)果述召,但有巧妙的方法實(shí)現(xiàn)同樣功能
spbill_create_ip: '127.0.0.1' //隨便寫一個(gè),為一些POS場(chǎng)合用的
};
//云函數(shù)入口函數(shù)
exports.main = async(event, content) => {
const wxContext = cloud.getWXContext()
const openid = wxContext.OPENID
const app = new TcbRouter({
event
});
app.router('queryZFFOrder', async(ctx) => {
console.log(util.inspect(event))
event.method = "GET"
event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder?out_order_no=${event.out_order_no}&service_id=${serviceId}&appid=${config.appid}`
let auth = getAuthorization(event)
let result = await rp({
url: event.url,
method: event.method,
json: true,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
"Authorization": auth
}
})
ctx.body = result
})
app.router('completeZFFOrder', async(ctx) => {
console.log(util.inspect(event))
event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/complete`
event.method = "POST"
event.body = {
appid: config.appid,
service_id: serviceId,
post_payments: [{
name: "借閱費(fèi)用",
amount: event.amount
}],
total_amount: event.amount,
time_range: {
end_time: moment().utcOffset(8).format("YYYYMMDDHHmmss")
}
}
let authorization = getAuthorization(event)
let result = await rp({
uri: event.url,
method: "POST",
json: true,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
"Authorization": authorization
},
body: event.body
})
ctx.body = result
})
app.router("createZFFOrder", async(ctx) => {
console.log(util.inspect(event))
const configuration = await db.collection("configuration").where({
name: "deposit"
}).get()
let deposit = configuration.data[0].value
const configuration2 = await db.collection("configuration").where({
name: "ZFFCallbackURL"
}).get()
let callbackURL = configuration2.data[0].value
let out_order_no = uuid.v1().replace(new RegExp('-', "g"), "")
event.url = "https://api.mch.weixin.qq.com/v3/payscore/serviceorder"
event.method = "POST"
event.body = {
out_order_no: out_order_no,
appid: config.appid,
service_id: serviceId,
service_introduction: "借書巴巴",
location: {
start_location: event.address.slice(0, 49)
},
time_range: {
start_time: "OnAccept"
},
risk_fund: {
name: "DEPOSIT",
amount: deposit
},
post_payments: [{
name: `${event.title.slice(0, 14)}-借閱費(fèi)用`,
amount: parseInt(event.price * 100),
description: `借閱${event.days}天, 共${event.price}元`
}],
notify_url: callbackURL,
need_user_confirm: true
}
let authorization = getAuthorization(event)
let result = await rp({
uri: event.url,
method: "POST",
json: true,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
"Authorization": authorization
},
body: event.body
})
result.out_order_no = out_order_no
if (result.state == "CREATED") {
ctx.body = getExtraData(result.package, out_order_no)
} else {
ctx.body = result
}
})
app.router('changeZFFOrder', async(ctx) => {
event.method = "POST"
event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/modify`
event.body = {
appid: config.appid,
service_id: serviceId,
post_payments: event.payments,
total_amount: event.total_amount,
reason: event.reason
}
console.log(util.inspect(event))
let auth = getAuthorization(event)
let result = await rp({
url: event.url,
method: event.method,
json: true,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
"Authorization": auth
},
body: event.body
})
ctx.body = result
})
app.router('cancelZFFOrder', async(ctx) => {
console.log(util.inspect(event))
event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/cancel`
event.method = "POST"
event.body = {
appid: config.appid,
service_id: serviceId,
reason: event.reason
}
let authorization = getAuthorization(event)
let result = await rp({
uri: event.url,
method: "POST",
json: true,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
"Authorization": authorization
},
body: event.body
})
ctx.body = result
})
app.router('syncZFFOrder', async(ctx) => {
event.method = "POST"
event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/sync`
event.body = {
appid: config.appid,
service_id: serviceId,
type: event.type,
detail: {
paid_time: event.paid_time
}
}
let auth = getAuthorization(event)
let result = await rp({
url: event.url,
method: event.method,
json: true,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
"Authorization": auth
},
body: event.body
})
ctx.body = result
})
app.router('ZFFOrderPay', async(ctx) => {
event.method = "POST"
event.url = `https://api.mch.weixin.qq.com/v3/payscore/serviceorder/${event.out_order_no}/pay`
event.body = {
appid: config.appid,
service_id: serviceId
}
let auth = getAuthorization(event)
let result = await rp({
url: event.url,
method: event.method,
json: true,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36",
"Authorization": auth
},
body: event.body
})
ctx.body = result
})
return app.serve();
}
function getExtraData(package, out_order_no) {
var now = Date.now();
var timeStamp = (Math.round(now / 1000)).toString();
var nonceStr = now.toString();
var str = `mch_id=${mchid}&nonce_str=${nonceStr}&package=${package}&sign_type=HMAC-SHA256×tamp=${timeStamp}&key=${apiKey}`
var sign = crypto.createHmac("sha256", apiKey).update(str).digest("hex").toUpperCase()
return {
mchid: mchid,
package: package,
timeStamp: timeStamp,
nonceStr: nonceStr,
signType: "HMAC-SHA256",
sign: sign,
out_order_no: out_order_no
}
}
function getAuthorization(event) {
let method = event.method
let relativePath = event.url.replace("https://api.mch.weixin.qq.com", "")
let body = ""
if (event.body) {
body = JSON.stringify(event.body)
}
var now = Date.now();
var timeStamp = Math.round(now / 1000);
var nonceStr = now;
let message = `${method}\n${relativePath}\n${timeStamp}\n${nonceStr}\n${body}\n`
var privateKey = forge.pki.privateKeyFromPem(private_key);
var sha256 = forge.md.sha256.create();
sha256.update(forge.util.encodeUtf8(message));
var signature = forge.util.encode64(privateKey.sign(sha256));
console.log(`message=[${message}]`);
var auth = `WECHATPAY2-SHA256-RSA2048 mchid="${mchid}",serial_no="${serialNo}",nonce_str="${nonceStr}",timestamp="${timeStamp}",signature="${signature}"`;
return auth;
}
-
具體效果可以參考借書巴巴小程序里面蟹地,申請(qǐng)借閱借書驛站圖書
image.png