因 公司小程序开发中含有微信支付的需求,特在此记录一下,主要方便自己日后查询,技术萌新。
重点:发起微信支付请求需要先进行签名,计算签名值。
介绍:小程序是用原生框架开发。
步骤:
1、调用wx.login()获取wx_code(以方便后端生成openId);
2、调用后端接口,传参:订单号(订单号后面可以加一串随机数,防止微信那边返回订单号重复错误),金额,wx_code等等;
3、承接上一步,后端会返回时间戳,支付签名等参数;拿着这些回参,去调用wx.requestPayment()接口就可以啦~~
import http from '../../http/api';
payMoney:function(){
var that = this;
wx.login({
success(res){
if(res.code){
console.log("res==>",res);
that.wx_code = res.code;
that.goPay(that.wx_code);
}else{
console.log('登录失败');
}
}
});
},
goPay(wx_code){
// 调起后端支付接口,订单号后面加6位随机数,防止因后台修改价格或者其他原因导致订单号重复
http.wxPay({
data:{
out_trade_no:this.orderId + '_' + this.randomRange(6),
money:Number(this.money),
js_code:wx_code,
},
success:res =>{
if(res.code==1){
console.log("调后端支付接口",res);
let data = res.data;
wx.requestPayment
(
{
"timeStamp": data.timeStamp,//时间戳
"nonceStr": data.nonceStr,//随机字符串,长度为32个字符以下
"package": data.package,//统一下单接口返回的prepay_id参数值
"signType": "RSA",//签名算法类型,默认为MD5,支持RSA等其他加密算法
"paySign": data.paySign,//签名
"success":function(res){
console.log("调起支付成功==>",res);
},
"fail":function(res){
console.log("调起支付失败==>",res);
},
"complete":function(res){}
}
)
}
},
fail:err =>{
wx.showToast({
title: '网络异常',
duration: 2000
})
}
});
},
// 生成随机数
randomRange:function(min,max){
var returnStr = '';
var range = (max? Math.round(Math.random() * (max - min)) + min : min);
var charStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i=0;i<range;i++){
var index = Math.round(Math.random() * (charStr.length -1));
returnStr +=charStr.substring(index,index+1);
}
return returnStr
},
以下是本人刚开发时做的前端请求支付示例:
1、下载RSA.js签名插件
2、分析一下wx.requestPayment()需要的入参:timeStamp(时间戳),签名等,计算签名可参考微信文档:微信支付-开发者文档
//以下为前端发起支付,本地模拟示例:
import http from '../../http/api';
var RSA = require('../../utils/wxapp_rsa.js');
payMoney(){
let timeStamp = Math.round(Date.now()/1000);//时间戳
//去构造签名
let appid = 'wx1122233344gfgfd';
let nonceStr = 'SKFFDDDFu98u9890GDFF';
let prepay_id = 'wx321435445435dfdsfsdf';
//构造好的签名串
let paySign = `${appid}\n${timeStamp}\n${nonceStr}\nprepay_id=${prepay_id}\n`;
//私钥、商户API证书下载后,私钥applicant_key.pem的内容
let sikey = `-----------BEGIN PRIVATE KEY---- fdsffdfdgdsfFEDFDAFDFFDF43324------END
PRIVATE KEY-------`;
//加密
var sign_rsa = new RSA.RSAKey();
sign_rsa = RSA.KEYUTIL.getKey(sikey);
var hashAlg = 'sha256';
var hSig = sign_rsa.sign(paySign,hashAlg);
hSig = RSA.hex2b64(hSig);//hex 转 b64
//调起微信支付
wx.requestPayment({
"timeStamp":timeStamp,//时间戳
"nonceStr":nonceStr,//随机字符串,长度为32个字符以下
"package":preypay_id,//统一下单接口返回的prepay_id参数值
"signType":"RSA",//签名算法类型,默认为MD5,支持RSA等其他加密算法
"paySign":paySign,//签名,结合微信官方文档,详情见上文
"success":function(res){
console.log("调起微信支付成功",res);
},
"fail":function(err){
console.log("调起微信支付失败",err);
},
});
}
Tips:加密,签名等最好由后端返回,因为涉及到appId,私钥等数据。