在讲支付过程之前,我们先来搞懂微信支付流程是什么样的
下面是一个微信支付流程图:
总结一下:
- 客户端发起支付之前,先创建订单,然后通过订单id获取订单信息,包含一个订单no
- 通过订单no去获取支付需要的签名参数
- 调用微信支付支付api(requestPayment),支付完成以后去查询后端订单更新状态
- 支付结束
定义支付接口
首先要定义好支付需要的接口,这里一共涉及四个接口,具体api参照订单接口:
/*** @description: 创建订单* @param {*} options* @return {*}*/addOrder(options) {options.url = `/api/order/auth/save/${options.courseId}`;return this.post(options);}/*** @description: 获取订单详细信息* @param {*} options* @return {*}*/getOrderInfo(options) {options.url = `/api/order/auth/get/${options.orderId}`;return this.get(options);}/*** @description: 支付订单* @param {*} options* @return {*}*/orderPay(options) {options.url = `/api/order/webChat/createJsapi/${options.orderNo}`;return this.get(options);}/*** @description: 查询订单支付状态* @param {*} options* @return {*}*/payStatus(options) {options.url = `/api/order/webChat/queryPayStatus/${options.orderNo}`;return this.get(options);}
发起支付
创建订单
async addOrder() {try {const res = await orderService.addOrder({courseId: this.options.courseId,});console.log("res", res);this.orderId = res.data.orderId;this.getOrderInfo();} catch (e) {console.log("e", e);}},
获取订单信息
async getOrderInfo() {try {const res = await orderService.getOrderInfo({orderId: this.orderId,});this.orderDetail = res.data.item;console.log("res", res);} catch (e) {console.log("e", e);}},
发起支付
async handleOrderPay() {const _this = this;if (!this.isChecked) {uni.showToast({title: "请同意谷粒微课购买协议",icon: "none",});return;}try {const res = await orderService.orderPay({orderNo: this.orderDetail.orderNo,});console.log("order", res);if (res.code === 200) {const data = res.data;uni.requestPayment({timeStamp: data.timeStamp,nonceStr: data.nonceStr,package: data.package,signType: data.signType,paySign: data.paySign,success(data) {console.log("pay-success", data);_this.getPayStatus();},fail(e) {console.log("pay-fail", e.errMsg);},});}} catch (e) {console.log(e);}},
根据orderNo换取支付参数,然后使用uni.requestPayment()发起微信支付,支付成功以后,还需要查询服务端订单更新状态
获取支付状态
async getPayStatus() {const res = await orderService.payStatus({orderNo: this.orderDetail.orderNo,});console.log("status-res", res);if (res.code == 200) {uni.showToast({title: "支付成功",});uni.navigateBack();}},
最后,如果支付成功,返回课程详情页面,然后更新状态,用户可以点击去学习按钮,观看视频
