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