进行微信支付,在小程序端我们主要做三件事:
注:服务端调用统一下单API、签名算法不再本次分享讨论范围内,请期待毛毛的下次分享。
使用** wx.login **获取临时登录凭证code,发送到后端获取openId
wx.login({
success (res) {
if (res.code) {
// 发起请求,换取openId
wx.request({
url: ‘’,
data: {
code: res.code
}
})
}
}
})
2.将** openId **以及相应需要的商品信息发送到后端,换取服务端进行的签名等信息
wx.request({
url: ‘’,
data: {
openId: ‘’,
num: 1,
id: ‘111’
}
})
3.接收返回的信息(必须要包含发起微信支付** wx.requestPayment的参数 **),发起微信支付
wx.requestPayment({
// 时间戳
timeStamp: ‘’,
// 随机字符串
nonceStr: ‘’,
// 统一下单接口返回的 prepay_id 参数值
package: ‘’,
// 签名类型
signType: ‘’,
// 签名
paySign: ‘’,
// 调用成功回调
success () {},
// 失败回调
fail () {},
// 接口调用结束回调
complete () {}
})
以上信息中 timeStamp 、 nonceStr 、 prepay_id 、 signType 、 paySign 各参数均建议必须都由服务端返回(这样会尽最大可能性保证签名数据一致性),小程序端不做任何处理。
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import './index.scss'
export default class Index extends Component {
config = {
navigationBarTitleText: '首页'
}
componentWillMount () { }
async componentDidMount () {
}
componentWillUnmount () { }
componentDidShow () { }
componentDidHide () { }
/**
* sendOrderInfo()
* @description 提交订单信息,获取支付凭证,唤起支付
*/
async sendOrderInfo () {
// 获取临时登录凭证code
let codeData = await Taro.login()
// 换取openId
let openId = ''
if (codeData.code) {
let res = await Taro.request({
// 定义的后端换取openId的接口
url: 'https://www.justbecoder.com/getLogin',
data: {
code: codeData.code
}
})
if (res && res.code === 0) {
openId = res.openId
}
}
// 发送openId以及对应的商品信息
let data = await Taro.requrest({
url: 'https://www.justbecoder.com/createdOrder',
data: {
openId,
// 实际情况的商品数量
num: 1,
// 实际情况的商品Id
id: 111,
}
})
// code === 0 表示提交订单成功,返回需要的签名信息等
if (data && data.code === 0) {
let {
timeStamp,
nonceStr,
prepay_id,
signType,
paySign
} = data.payInfo
// 唤起支付,按小程序要求格式发送参数
let payData = await Taro.requestPayment({
timeStamp,
nonceStr,
package: 'prepay_id=' + prepay_id,
signType,
paySign
})
if (payData && payData.errMsg === 'requestPayment:ok') {
Taro.showModal({
title: '操作提示',
content: '支付成功',
showCancel: false,
confirmText: '确定'
})
} else {
Taro.showModal({
title: '操作提示',
content: '支付失败,请重新尝试',
showCancel: false,
confirmText: '确定'
})
}
}
}
render () {
return (
<View className='index'>
<Button onClick={this.sendOrderInfo}>立即下单</Button>
</View>
)
}
}