预备工作
连接电源
打开你的电脑
打开你的vscode
获取appid
npm install weixin-js-sdk
开撸
在你的支付按钮上添加一个事件、代码为:
var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=输入你的appid&redirect_uri=http://tdjl.kurongdashi.com?pay='+msg+'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
location.href = url;
1.1 url这串链接是微信给你提供的,里面的具体参数看下图,就不再详解了,我这么菜都能看懂的,你也行,这部分最主要的是为了获取code然后再获取openid。
1.2 在redirect_uri=这里填写你们的域名,前提是在微信白名单中内设置了,这部分一般都不归我们管,然后?后面我自己添加了一个金额参数,用于提交所充值的金额,因为这部分页面只是做一个跳转,所以要保存金额,当然也可以用vuex来处理金额部分,我就懒得用了。
2. 在跳转链接后,没出任何问题,会重定向到你redirect_uri中设置的地方,这时,url栏里有了一些非常重要的参数,首先就是code,然后则是自己设置的金额参数,把它们拆接下来继续下一步操作,代码为:
let str = location.href,
num = str.indexOf("?");
str = str.substr(num + 1);
let arr = str.split("&");
var code = arr[1].split('=')[1]
var moneys = arr[0].split('=')[1]
this.axios.defaults.headers.common["X-Api-Token"] =localStorage.access_token;
this.axios.get('/pay/openid', {
params: {
'code': code //这部分做过小程序的人就会很熟悉
}
}).then((response)=>{
var openid = response.data.data.openid
this.axios.post('/user/recharge', {
'price': moneys,
'pay_type': 1,
'openid': openid
}).then((response)=>{
//关键代码,里面所填写的资料都是后台给你的,所以粘贴复制就行了
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": response.data.data.appId, //公众号名称,由商户传入
"timeStamp":response.data.data.timeStamp, //时间戳,自1970年以来的秒数
"nonceStr":response.data.data.nonceStr, //随机串
"package": response.data.data.package,
"signType": response.data.data.signType, //微信签名方式
"paySign": response.data.data.paySign //微信签名
},
function(res){
//我这里无论成功与否,都会跳转到我设置的页面中,且带了一个参数,用于跳转到原来的页面时给用户提示充值是否成功
if(res.err_msg == "get_brand_wcpay_request:ok" ) {
console.log('支付成功')
window.location.href="http://tdjl.kurongdashi.com/#/paycenter?cg=cg";
}else if(res.err_msg == 'get_brand_wcpay_request:cancel'){
window.location.href="http://tdjl.kurongdashi.com/#/paycenter?qx=qx";
}else{
window.location.href="http://tdjl.kurongdashi.com/#/paycenter?sb=sb";
}
}
);
}).catch((response)=>{
console.log(response)
})
}).catch((response)=>{
console.log(response);
})
结尾补充
当时弄这个东西弄了一个通宵,第一次做,没头绪加上开发公众号测试代码真的好坑,每次都是线下代码修改完毕得上传到线上打开微信开发者工具测试反复如此,好蛋疼,还有一种就是直接在线上开发,保存即可看,不知道还有没有其他方式。
这是属于微信内H5支付,想开发微信外调起微信支付的,在公众号中设置一下权限整体流程也差不多,代码写的比较low,能实现功能不出BUG一分钱一分货是我的座右铭,大神勿喷。
结语:本人目前所会的都来自Dell老师的一门实战课程,https://coding.imooc.com/class/203.html 感谢Dell老师的专业与付出的汗水,学完该课程差不多也会了微信小程序开发,反正我是这样的,嘿嘿。