前提:
1.你的小程序不是个人小程序
2.有微信商户号和商户密钥
小程序端 购买按钮方法
buyBtnAction:function(){
wx.cloud.callFunction({
name:'xiadanpay',
data:'',
success:function(e){
//云函数返回的需要的支付参数
wx.requestPayment({
timeStamp: e.result.timeStamp,
nonceStr: e.result.nonceStr,
package: e.result.package,
signType: e.result.signType,
paySign: e.result.paySigns,
success:function(res){
console.log('支付成功!!!!!!')
},
fail:function(e){
console.log('支付失败')
}
})
},
fail:function(err){
console.log(err)
}
})
},
云函数端
const cloud = require('wx-server-sdk')
const ip = require('ip')
// 初始化 cloud
cloud.init()
const appId = 'xxxxx' // 小程序appid
const mchId = 'xxxxxx' //商户id
const key = 'xxxxxxx'//商户密匙
const timeout = 10000 // 毫秒
const {
WXPay,
WXPayConstants,
WXPayUtil
} = require('wx-js-utils');
let wxpay = new WXPay({
appId,
mchId,
key,
timeout,
signType: WXPayConstants.SIGN_TYPE_MD5,
useSandbox: false
});
exports.main = async (event, context) => {
const wxcontext = cloud.getWXContext();
var time_stamp_jj = '' + Math.ceil(Date.now() / 1000)
// 统一下单
var reqObj = {
body: '商城-商品1',
out_trade_no: '1478582754971', //订单号每次支付不能重复,(这里写死仅做测试)
total_fee: 1, //支付费用 (单位是分不是元)
spbill_create_ip: ip.address() || '127.0.0.1',
notify_url: 'http://www.qq.com',
trade_type: 'JSAPI',
time_stamp: time_stamp_jj,
openid: wxcontext.OPENID
};
var resobj = await wxpay.unifiedOrder(reqObj)
var preid = 'prepay_id=' + resobj.prepay_id
const paySign = await WXPayUtil.generateSignature({
appId: resobj.appid,
nonceStr: resobj.nonce_str,
package: preid,
signType: 'MD5',
timeStamp: time_stamp_jj
}, key);
//返回给小程序端调起支付的支付参数
return{
timeStamp:time_stamp_jj,
nonceStr: resobj.nonce_str,
package:preid,
signType:'MD5',
paySigns:paySign
}
}
网友评论