WechatPayment.vue 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <template>
  2. <!-- 支付加载提示 -->
  3. <view v-if="showPayLoading" class="pay-loading-mask">
  4. <view class="pay-loading-box">
  5. <view class="loading-spinner"></view>
  6. <text class="loading-text">处理支付中...</text>
  7. </view>
  8. </view>
  9. </template>
  10. <script setup>
  11. import { ref, getCurrentInstance } from "vue";
  12. import { createPaymentOrder, queryPaymentStatus } from "@/api/payment";
  13. import { generateCustomId } from "@/utils/util.js";
  14. // 组件实例
  15. const instance = getCurrentInstance();
  16. // 状态管理
  17. const orderNo = ref("");
  18. const orderId = ref("");
  19. const showPayLoading = ref(false);
  20. const paymentInProgress = ref(false);
  21. // 回调函数存储
  22. const callbacks = ref({
  23. onUniPayCreate: null,
  24. onUniPaySuccess: null,
  25. onUniPayCancel: null,
  26. onUniPayFail: null,
  27. });
  28. /**
  29. * 发起微信支付
  30. * @param {Object} options - 支付参数
  31. * @param {number} options.amount - 支付金额(分)
  32. * @param {string} options.description - 商品描述
  33. * @param {string} options.openId - 用户openId
  34. * @param {string} options.orderPrefix - 订单号前缀
  35. * @param {string} options.orderNo - 订单号
  36. * @param {Function} options.onUniPayCreate - 订单创建成功回调
  37. * @param {Function} options.onUniPaySuccess - 支付成功回调
  38. * @param {Function} options.onUniPayCancel - 取消支付回调
  39. * @param {Function} options.onUniPayFail - 支付失败回调
  40. */
  41. const createUniPay = async (options) => {
  42. // 防止重复发起支付
  43. if (paymentInProgress.value) return;
  44. try {
  45. paymentInProgress.value = true;
  46. showPayLoading.value = true;
  47. // 保存回调函数
  48. Object.keys(callbacks.value).forEach((key) => {
  49. callbacks.value[key] =
  50. options[key] && typeof options[key] === "function"
  51. ? options[key]
  52. : () => {};
  53. });
  54. if (options.orderNo) {
  55. // 若传入订单号则使用传入的订单号
  56. orderNo.value = options.orderNo;
  57. } else {
  58. // 生成订单号(使用公共组件)
  59. orderNo.value = generateCustomId(options.orderPrefix || "WX_");
  60. }
  61. // 调用后端创建支付订单
  62. const { data: payRes } = await createPaymentOrder({
  63. amount: options.amount,
  64. description: options.description,
  65. openId: options.openId,
  66. orderNo: options.orderNo,
  67. });
  68. // return console.log("payRes", payRes);
  69. // 订单创建成功,触发回调
  70. callbacks.value.onUniPayCreate({
  71. out_trade_no: options.orderNo,
  72. ...payRes,
  73. });
  74. // 调起微信支付
  75. await uni.requestPayment({
  76. provider: "wxpay",
  77. timeStamp: payRes.timeStamp.toString(),
  78. nonceStr: payRes.nonceStr,
  79. package: payRes.package,
  80. signType: payRes.signType,
  81. paySign: payRes.paySign,
  82. success: () => {
  83. confirmPaymentStatus();
  84. },
  85. fail: (err) => {
  86. showPayLoading.value = false;
  87. paymentInProgress.value = false;
  88. if (err.errMsg && err.errMsg.includes("cancel")) {
  89. callbacks.value.onUniPayCancel(err);
  90. } else {
  91. callbacks.value.onUniPayFail(err);
  92. }
  93. },
  94. });
  95. } catch (err) {
  96. showPayLoading.value = false;
  97. paymentInProgress.value = false;
  98. console.error("支付流程异常:", err);
  99. callbacks.value.onUniPayFail(err);
  100. }
  101. };
  102. /**
  103. * 确认支付状态(轮询查询)
  104. */
  105. const confirmPaymentStatus = async () => {
  106. try {
  107. let checkCount = 0;
  108. const maxCheckCount = 10; // 最多查询10次
  109. const checkInterval = 1000; // 每次查询间隔1秒
  110. const checkStatus = async () => {
  111. // 超过最大查询次数,视为超时
  112. if (checkCount >= maxCheckCount) {
  113. showPayLoading.value = false;
  114. paymentInProgress.value = false;
  115. callbacks.value.onUniPayFail(
  116. new Error("支付结果查询超时,请稍后查看订单状态")
  117. );
  118. return;
  119. }
  120. checkCount++;
  121. try {
  122. // 查询支付状态
  123. const res = await queryPaymentStatus(orderNo.value);
  124. // 根据后端返回的支付状态进行处理
  125. if (res.code === 200) {
  126. showPayLoading.value = false;
  127. paymentInProgress.value = false;
  128. callbacks.value.onUniPaySuccess({
  129. ...res.data,
  130. out_trade_no: orderNo.value,
  131. });
  132. }
  133. } catch (err) {
  134. // 查询接口出错,重试
  135. console.error(`第${checkCount}次查询支付状态失败:`, err);
  136. setTimeout(checkStatus, checkInterval);
  137. }
  138. };
  139. // 开始第一次查询
  140. checkStatus();
  141. } catch (err) {
  142. showPayLoading.value = false;
  143. paymentInProgress.value = false;
  144. console.error("确认支付状态异常:", err);
  145. callbacks.value.onUniPayFail(err);
  146. }
  147. };
  148. // 对外暴露方法
  149. defineExpose({
  150. createUniPay,
  151. });
  152. </script>
  153. <style scoped>
  154. /* 支付加载提示样式 */
  155. .pay-loading-mask {
  156. position: fixed;
  157. top: 0;
  158. left: 0;
  159. right: 0;
  160. bottom: 0;
  161. background-color: rgba(0, 0, 0, 0.5);
  162. display: flex;
  163. justify-content: center;
  164. align-items: center;
  165. z-index: 9999;
  166. }
  167. .pay-loading-box {
  168. background-color: white;
  169. padding: 30rpx 40rpx;
  170. border-radius: 16rpx;
  171. display: flex;
  172. flex-direction: column;
  173. align-items: center;
  174. }
  175. .loading-spinner {
  176. width: 50rpx;
  177. height: 50rpx;
  178. border: 4rpx solid #eee;
  179. border-top-color: #07c160;
  180. border-radius: 50%;
  181. animation: spin 1s linear infinite;
  182. margin-bottom: 20rpx;
  183. }
  184. .loading-text {
  185. color: #333;
  186. font-size: 28rpx;
  187. }
  188. /* 旋转动画 */
  189. @keyframes spin {
  190. to {
  191. transform: rotate(360deg);
  192. }
  193. }
  194. </style>