在讲支付过程之前,我们先来搞懂微信支付流程是什么样的
下面是一个微信支付流程图:
10.支付 - 图1
总结一下:

  • 客户端发起支付之前,先创建订单,然后通过订单id获取订单信息,包含一个订单no
  • 通过订单no去获取支付需要的签名参数
  • 调用微信支付支付api(requestPayment),支付完成以后去查询后端订单更新状态
  • 支付结束

定义支付接口

首先要定义好支付需要的接口,这里一共涉及四个接口,具体api参照订单接口

  1. /**
  2. * @description: 创建订单
  3. * @param {*} options
  4. * @return {*}
  5. */
  6. addOrder(options) {
  7. options.url = `/api/order/auth/save/${options.courseId}`;
  8. return this.post(options);
  9. }
  10. /**
  11. * @description: 获取订单详细信息
  12. * @param {*} options
  13. * @return {*}
  14. */
  15. getOrderInfo(options) {
  16. options.url = `/api/order/auth/get/${options.orderId}`;
  17. return this.get(options);
  18. }
  19. /**
  20. * @description: 支付订单
  21. * @param {*} options
  22. * @return {*}
  23. */
  24. orderPay(options) {
  25. options.url = `/api/order/webChat/createJsapi/${options.orderNo}`;
  26. return this.get(options);
  27. }
  28. /**
  29. * @description: 查询订单支付状态
  30. * @param {*} options
  31. * @return {*}
  32. */
  33. payStatus(options) {
  34. options.url = `/api/order/webChat/queryPayStatus/${options.orderNo}`;
  35. return this.get(options);
  36. }

发起支付

创建订单

  1. async addOrder() {
  2. try {
  3. const res = await orderService.addOrder({
  4. courseId: this.options.courseId,
  5. });
  6. console.log("res", res);
  7. this.orderId = res.data.orderId;
  8. this.getOrderInfo();
  9. } catch (e) {
  10. console.log("e", e);
  11. }
  12. },

返回orderId

获取订单信息

  1. async getOrderInfo() {
  2. try {
  3. const res = await orderService.getOrderInfo({
  4. orderId: this.orderId,
  5. });
  6. this.orderDetail = res.data.item;
  7. console.log("res", res);
  8. } catch (e) {
  9. console.log("e", e);
  10. }
  11. },

返回orderNo

发起支付

  1. async handleOrderPay() {
  2. const _this = this;
  3. if (!this.isChecked) {
  4. uni.showToast({
  5. title: "请同意谷粒微课购买协议",
  6. icon: "none",
  7. });
  8. return;
  9. }
  10. try {
  11. const res = await orderService.orderPay({
  12. orderNo: this.orderDetail.orderNo,
  13. });
  14. console.log("order", res);
  15. if (res.code === 200) {
  16. const data = res.data;
  17. uni.requestPayment({
  18. timeStamp: data.timeStamp,
  19. nonceStr: data.nonceStr,
  20. package: data.package,
  21. signType: data.signType,
  22. paySign: data.paySign,
  23. success(data) {
  24. console.log("pay-success", data);
  25. _this.getPayStatus();
  26. },
  27. fail(e) {
  28. console.log("pay-fail", e.errMsg);
  29. },
  30. });
  31. }
  32. } catch (e) {
  33. console.log(e);
  34. }
  35. },

根据orderNo换取支付参数,然后使用uni.requestPayment()发起微信支付,支付成功以后,还需要查询服务端订单更新状态

获取支付状态

  1. async getPayStatus() {
  2. const res = await orderService.payStatus({
  3. orderNo: this.orderDetail.orderNo,
  4. });
  5. console.log("status-res", res);
  6. if (res.code == 200) {
  7. uni.showToast({
  8. title: "支付成功",
  9. });
  10. uni.navigateBack();
  11. }
  12. },

最后,如果支付成功,返回课程详情页面,然后更新状态,用户可以点击去学习按钮,观看视频