WechatPayment.vue 5.3 KB

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