uniapp微信公众号h5需要实现支付功能,将实现流程记录一下,便于后面复用。
<template>
<view class="buy">
</view>
</template>
<script>
import {
paypayOrder,
getticket
} from '@/config/api.js'
import configs from '@/config/config.js'
import wx from 'weixin-js-sdk';
export default {
components: {},
data() {
return {
data: {
appId: "",
nonceStr: "",
package: "",
paySign: "",
signType: "",
timeStamp: "",
}
}
},
props: {
orderno: {
type: String,
default () {
return '';
}
}
},
mounted() {
var url = window.location.href;
this.getWxconfig(url)
},
methods: {
getPay() {
var that = this;
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady(), false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady());
document.attachEvent('onWeixinJSBridgeReady', that.onBridgeReady());
}
} else {
that.onBridgeReady();
}
},
onBridgeReady() {
var that = this;
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": that.data.appId, //公众号ID,由商户传入
"timeStamp": that.data.timeStamp, //时间戳,自1970年以来的秒数
"nonceStr": that.data.nonceStr, //随机串
"package": that.data.package,
"signType": that.data.signType, //微信签名方式:
"paySign": that.data.paySign //微信签名
},
function(res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
uni.redirectTo({
url: '/pages/order/order'
})
}
});
},
getWxconfig(url) {
getticket({}, {
params: {},
custom: {
auth: true
}
}).then(function(res) {
if (res.code == 1) {
var jsapi_ticket = res.data.ticket;
var timestamp = Date.parse(new Date()) / 1000
let sha1 = require('js-sha1');
var str2 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + configs.appid + "×tamp=" +
timestamp + "&url=" + url;
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: configs.appid, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: configs.appid, // 必填,生成签名的随机串
signature: sha1(str2.toString()), // 必填,签名
jsApiList: ['chooseImage', 'uploadImage', 'previewImage',
'onMenuShareTimeline', 'onMenuShareAppMessage',
'updateAppMessageShareData', 'updateTimelineShareData',
'onMenuShareTimeline', 'chooseWXPay', 'getLocation'
], // 必填,需要使用的JS接口列表
});
wx.error(function(res) {
// location.reload();
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});
}
})
},
paypayOrder(orderno, total) {
var that = this;
var openid = uni.getStorageSync('openid')
paypayOrder({}, {
params: {
orderno: orderno,
amount: total,
openid: openid
},
custom: {
auth: true
}
}).then(res => {
if (res.code == 1) {
that.data = res.data
that.getPay()
}
}).catch(err => {
})
},
}
}
</script>