# vk-uni-pay 统一支付组件

本组件支持 uni-app 和 uni-app x 蒸汽模式。x 需插件 ≥ 1.18.0、HBuilderX ≥ 5.33,完整接入步骤与示例。本文的选项式示例用于 uni-app,x 使用下方的组合式写法。

使用 vk-uni-pay 组件的优势

  • 1、自动请求云函数
  • 2、自动识别 H5、小程序、APP,抹平不同平台的代码差异
  • 3、H5 扫码支付自动获取二维码地址 vkPay.codeUrl,支持自动轮询获取支付状态
  • 4、可实时监听支付状态 vkPay.status 0:待支付 1:支付中 2:已支付
  • 5、支付成功的判断是直接查你数据库的订单状态是否已支付,安全可靠。

# template

# uni-app

以下使用 Vue2 的 .sync 写法。

<vk-uni-pay
  ref="vkPay"
  :query-payment-action="vkPay.queryPaymentAction"
  :status.sync="vkPay.status"
  :code-url.sync="vkPay.codeUrl"
  :page-show="vkPay.pageShow"
  :polling="vkPay.polling"
></vk-uni-pay>
1
2
3
4
5
6
7
8

# uni-app x 蒸汽模式

在 .uvue 页面的 <script setup lang="ts"> 中定义组件引用和状态,模板使用 v-model:

<template>
  <vk-uni-pay ref="payRef" v-model:status="vkPay.status" v-model:codeUrl="vkPay.codeUrl" v-model:qrcodeImage="vkPay.qrcodeImage" :page-show="vkPay.pageShow" :polling="true" />
</template>

<script setup lang="ts">
  const payRef = ref(null);
  const vkPay = reactive({ status: 0, codeUrl: '', qrcodeImage: '', pageShow: true });
  onShow(() => {
    vkPay.pageShow = true;
  });
  onHide(() => {
    vkPay.pageShow = false;
  });
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

页面就绪后通过 payRef.value.createPayment(options) 调用。以上仅展示组件绑定,包含按钮、二维码和查单的可运行示例见接入指南。默认查询接口为 vk-pay / pay/queryPayment,自定义云函数时需传 query-payment-action。

# 属性

参数 说明 类型 默认值 可选值
query-payment-action 查询支付状态的云函数配置 Object、String - -
status.sync Vue2 特有属性 支付状态 0:待支付 1:支付中 2:已支付 Number - -
code-url.sync Vue2 特有属性 PC 扫码支付专用 - 二维码 url 地址 String - -
qrcode-image.sync Vue2 特有属性 PC 扫码支付专用 - 二维码图片 base64 值 String - -
v-model:status Vue3 / uni-app x 支付状态 0:待支付 1:支付中 2:已支付 Number - -
v-model:code-url Vue3 / uni-app x 二维码内容(也支持 v-model:codeUrl) String - -
v-model:qrcode-image Vue3 / uni-app x 二维码图片(也支持 v-model:qrcodeImage) String - -
page-show 当前页面是否显示;x 中用于暂停或恢复支付结果轮询 Boolean true false
polling 自动查询二维码支付结果;x 中也用于 App 打开支付链接后的查询 Boolean false true
polling-time 轮询间隔 Number 1500 -
return-url 微信 H5 支付的网页返回地址;x App 收到 H5 链接时也可使用 String - -
await-notify 付款成功后尝试等待业务通知;业务处理结果以返回的 user_order_success 为准 Boolean false true
pay-order-info 支付成功后,是否需要返回支付订单数据 Boolean true false
debug 是否需要打印调试日志(当前仅用于 ios 内购时生效) Boolean false true
auto-get-openid 是否自动获取小程序的 openid(若传 false,则在 createPayment 时需要自己传对应的 openid) Boolean true false

# 方法

uni-app 选项式通过 this.$refs.vkPay.xxx() 调用;uni-app x 通过 payRef.value.xxx() 调用。

方法名 说明
createPayment 发起支付
queryPayment 查询支付状态;主动查询成功后,页面按需更新 status
init 初始化并触发 init 事件,组件挂载时自动执行,通常无需手动调用
getOpenid 获取小程序 OpenID,返回 Promise;auto-get-openid 为 false 时不自动获取

注意:需要在 template 内声明组件,ref 名称与调用时的组件引用对应;以下 uni-app 示例使用 vkPay。

<vk-uni-pay ref="vkPay" ...其他参数></vk-uni-pay>
1

Vue3 setup 内写法

由于 setup 内没有 this,故写法稍微变一下,代码如下:

import { ref } from 'vue';

const vkPay = ref(null); // 这里的 vkPay 变量名必须和组件写的ref的值一致

// this.$refs.vkPay.createPayment 改成 vkPay.value.createPayment
vkPay.value.createPayment({
  // 参数
});
1
2
3
4
5
6
7
8

# 事件

事件 说明
init 组件初始化完成
create 云端创建订单成功,尚未确认付款
success 支付成功
fail 创建订单或支付流程失败,可读取 msg、errMsg、failType
cancel 用户取消支付
userPaying 付款码支付中,等待用户完成付款
update:status / update:codeUrl / update:qrcodeImage 用于 v-model 同步状态和二维码

create、success、fail、cancel、userPaying 可通过组件事件监听,也可在 createPayment 参数中传同名回调。两种方式都会执行,同一业务选择一种即可。只有方法参数中的 create 回调返回 false 才会停止后续支付流程。

x 中 await createPayment() 不代表付款完成,请使用 success 或云端查单结果。发货、充值仍由云端业务回调处理。

# createPayment 加载提示

createPayment 支持通过 loading 和 title 参数控制本次支付的加载提示。两个参数均放在方法的顶层参数中,与 action、data 同级。

参数 说明 类型 默认值 可选值
loading 是否显示本次支付的加载提示 Boolean true true、false
title 自定义加载提示文字,空字符串等效于 loading: false String 各阶段原有文案,支付请求时为“请求中...” -

传入 loading: false 或 title: '' 后,组件会关闭本次支付请求、后续支付结果查询、等待异步通知及 iOS 内购处理过程中的加载提示,并跳过对应的 uni.hideLoading() 调用,便于页面自行管理加载提示。loading: false 的优先级高于自定义 title。

this.$refs.vkPay.createPayment({
  ...paymentOptions, // 原有支付参数,包含 action、data 及回调
  loading: false, // 也可以使用 title: ''
});
1
2
3
4

自定义提示文字示例:

this.$refs.vkPay.createPayment({
  ...paymentOptions,
  title: '正在创建订单...',
});
1
2
3
4

非空 title 会替换本次流程中需要显示的加载提示文字,后台静默轮询保持原有行为。省略 title 时,各阶段继续使用原有文案,如“请求中...”“请稍等...”和 iOS 内购的“支付处理中...”。Vue3 setup 内使用 vkPay.value.createPayment 时,参数写法相同。以上设置仅对本次 createPayment 调用及其后续流程生效。

# createPayment 示例

# uni-app

this.$refs.vkPay.createPayment({
  loading: true, // 默认true,设为false可关闭本次支付的加载提示
  // 如果是非路由框架,则action为字符串,值为云函数名称
  // 如果是路由框架,则按下方配置填写
  action: {
    name: 'vk-pay', // 云函数名称
    action: 'pay/createPayment', // 路由模式下云函数地址
    actionKey: 'action', // 路由模式下云函数地址的识别key(注意VK路由框架下,此值为$url)
    dataKey: 'data', // 路由模式下云函数请求参数的识别key
  },
  // 请求数据
  data: {
    provider: form1.provider,
    total_fee: form1.total_fee,
    out_trade_no: form1.out_trade_no,
    subject: form1.subject,
    body: form1.body,
    type: form1.type,
  },
  // 支付订单创建成功回调
  create: (res) => {
    console.log('pay-create', res);
    this.form1.out_trade_no = res.out_trade_no; // 如果订单号是云端生成的,这里可以拿到订单号,此处如果return false; 则不再执行后续逻辑
  },
  // 支付成功回调
  success: (res) => {
    this.toast('支付成功', 'success');
    console.log('pay-success', res);
  },
  // 支付失败回调
  fail: (res) => {
    if (res.failType === 'create') {
      // 创建支付失败时提示
      this.alert(res.msg);
    } else if (res.failType === 'request') {
      // 请求支付失败时提示
      this.toast('请求支付失败');
    } else if (res.failType === 'result') {
      // 支付结果失败时提示
      this.toast('支付失败');
    }
  },
  // 取消回调
  cancel: (res) => {
    this.toast('用户取消支付');
  },
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

# uni-app x 蒸汽模式

// .uvue 的 <script setup lang="ts">,模板对应 ref="payRef"
const payRef = ref(null);
function createPayment() {
  payRef.value?.createPayment({
    action: { name: 'vk-pay', action: 'pay/createPayment', actionKey: 'action', dataKey: 'data' },
    data: { provider: 'wxpay', total_fee: 1, out_trade_no: 'test_' + Date.now(), subject: '测试订单', type: 'recharge' },
    create: (res) => {
      console.log('订单已创建', res.out_trade_no);
    },
    success: () => {
      uni.showToast({ title: '支付成功' });
    },
    fail: (res) => {
      uni.showToast({ title: res.msg || res.errMsg || '支付失败', icon: 'none' });
    },
    cancel: () => {
      uni.showToast({ title: '用户取消支付', icon: 'none' });
    },
  });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

以上为调用片段,包含状态和二维码绑定的页面见下方完整示例。

# queryPayment 示例

# uni-app

this.$refs.vkPay.queryPayment({
  title: '查询中...',
  data: {
    out_trade_no: this.form1.out_trade_no,
  },
  success: (data) => {
    this.vkPay.status = 2; // 标记为已支付
    this.toast(data.msg);
  },
});
1
2
3
4
5
6
7
8
9
10

toast 和 alert 简易封装

toast(title, icon = "none", mask = false) {
  uni.showToast({
    title,
    icon,
    mask,
    duration: 1500
  });
},
alert(content, title = "提示") {
  uni.showModal({
    title,
    content,
    showCancel: false
  });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# uni-app x 蒸汽模式

// 接在下方完整页面的 script setup 中,使用其中的 payRef、form1、vkPay
function queryPayment() {
  if (!payRef.value || !form1.out_trade_no) return;
  payRef.value
    .queryPayment({
      title: '查询中...',
      data: { out_trade_no: form1.out_trade_no },
      success: (res) => {
        vkPay.status = 2;
        uni.showToast({ title: res.msg || '支付成功', icon: 'none' });
      },
    })
    .catch((error) => {
      console.log('查询未成功', error);
    });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 示例代码

# uni-app

<template>
  <view class="app">
    <!-- 页面示例开始 -->
    <view class="page-content">
      <!-- #ifdef H5 || APP-PLUS -->
      <view>请选择支付方式(H5和APP可以选择)</view>
      <view style="font-size: 24rpx;">H5端会智能识别微信公众号、手机外部浏览器,PC网站扫码支付</view>
      <radio-group @change="radioChange" style="display: flex;margin: 10rpx 0;">
        <label style="flex: 1;">
          <radio value="wxpay" :checked="form1.provider == 'wxpay'" />
          <text>微信</text>
        </label>
        <label style="flex: 1;">
          <radio value="alipay" :checked="form1.provider == 'alipay'" />
          <text>支付宝</text>
        </label>
      </radio-group>
      <!-- #endif -->
      <view style="margin-bottom: 16rpx;">支付金额:(单位分 100 = 1元)</view>
      <input class="input" type="text" v-model="form1.total_fee" placeholder="支付金额" />
      <view style="margin-bottom: 16rpx;">订单号</view>
      <input class="input" type="text" v-model="form1.out_trade_no" placeholder="订单号" />

      <!-- #ifdef H5 -->
      <button class="button" v-if="h5Env === 'h5-weixin'" type="primary" @click="getWeiXinJsCode('snsapi_base')">公众号获取openid示例</button>
      <button class="button" v-if="vkPay.status == 0" type="primary" @click="createPayment">发起支付</button>
      <button class="button" v-else-if="vkPay.status == 2" type="primary" @click="createPayment">再次发起支付</button>
      <!-- #endif -->

      <!-- #ifndef H5 -->
      <button class="button" @click="createPayment">支付</button>
      <!-- #endif -->

      <button class="button" @click="queryPayment">支付结果查询</button>
      <button class="button" @click="refund">申请退款</button>
      <button class="button" @click="queryRefund">退款结果查询</button>

      <button class="button" @click="transferAlipay">转账到支付宝</button>
      <button class="button" @click="transferWxpay2">转账到微信零钱v2</button>
      <button class="button" @click="transferWxpay3">转账到微信零钱v3</button>
      <button class="button" @click="getWxpayPublicCert">获取微信支付v3平台证书</button>
    </view>

    <!-- 页面示例结束s -->

    <!-- vue2版本的支付组件开始 -->
    <!-- #ifndef VUE3 -->
    <vk-uni-pay
      ref="vkPay"
      :status.sync="vkPay.status"
      :code-url.sync="vkPay.codeUrl"
      :qrcode-image.sync="vkPay.qrcodeImage"
      :query-payment-action="vkPay.queryPaymentAction"
      :page-show="vkPay.pageShow"
      :auto-get-openid="vkPay.autoGetOpenid"
      :polling="vkPay.polling"
      :return-url="vkPay.returnUrl"
      :await-notify="vkPay.awaitNotify"
      :pay-order-info="vkPay.payOrderInfo"
    ></vk-uni-pay>
    <!-- #endif -->
    <!-- vue2版本的支付组件结束 -->

    <!-- vue3版本的支付组件开始 -->
    <!-- #ifdef VUE3 -->
    <vk-uni-pay
      ref="vkPay"
      v-model:status="vkPay.status"
      v-model:codeUrl="vkPay.codeUrl"
      v-model:qrcodeImage="vkPay.qrcodeImage"
      :query-payment-action="vkPay.queryPaymentAction"
      :page-show="vkPay.pageShow"
      :auto-get-openid="vkPay.autoGetOpenid"
      :polling="vkPay.polling"
      :return-url="vkPay.returnUrl"
      :await-notify="vkPay.awaitNotify"
      :pay-order-info="vkPay.payOrderInfo"
    ></vk-uni-pay>
    <!-- #endif -->
    <!-- vue3版本的支付组件结束 -->

    <!-- 弹窗开始 -->

    <!-- 二维码支付弹窗开始 -->
    <view class="pay-qrcode-popup" v-if="vkPay.status < 2 && vkPay.codeUrl">
      <view class="pay-qrcode-popup-mask" @click="cancelPay"></view>
      <view class="pay-qrcode-popup-content">
        <image v-if="vkPay.qrcodeImage" :src="vkPay.qrcodeImage" class="pay-qrcode-popup-image"></image>
        <vk-uni-qrcode v-else :text="vkPay.codeUrl" :size="450"></vk-uni-qrcode>
        <view class="pay-qrcode-popup-info">
          <view>
            <text class="pay-qrcode-popup-info-fee">{{ (form1.total_fee / 100).toFixed(2) }}</text>
            <text>元</text>
          </view>
          <view v-if="form1.provider == 'wxpay'">请用微信扫码支付</view>
          <view v-else-if="form1.provider == 'alipay'">请用支付宝扫码支付</view>
        </view>
        <button v-if="vkPay.status == 1" type="primary" @click="queryPayment">我已完成支付</button>
      </view>
    </view>
    <!-- 二维码支付弹窗结束 -->

    <!-- 外部浏览器H5支付弹窗确认开始 -->
    <view class="pay-confirm-popup" v-if="vkPay.confirmShow">
      <view class="pay-confirm-popup-content">
        <view class="pay-confirm-popup-title">请确认支付是否已完成</view>
        <view><button type="primary" @click="queryPayment">已完成支付</button></view>
        <view class="pay-confirm-popup-refresh"><button type="default" @click="afreshPayment">支付遇到问题,重新支付</button></view>
        <view class="pay-confirm-popup-cancel" @click="vkPay.confirmShow = false">暂不支付</view>
      </view>
    </view>
    <!-- 外部浏览器H5支付弹窗确认结束 -->

    <!-- 弹窗结束 -->
  </view>
</template>

<script>
  export default {
    data() {
      // 页面数据变量
      return {
        vkPay: {
          /**
           * 查询支付状态的云函数配置
           * 如果是非路由框架,则action为字符串,值为云函数名称
           * 如果是路由框架,则按下方配置填写
           * 注意:queryPaymentAction内参数用默认即可,无需更改。(除非你已经知道参数的意义)
           */
          queryPaymentAction: {
            name: 'vk-pay', // 云函数名称
            action: 'pay/queryPayment', // 路由模式下云函数地址
            actionKey: 'action', // 路由模式下云函数地址的识别key
            dataKey: 'data', // 路由模式下云函数请求参数的识别key
          },
          // PC支付的付款二维码地址,渲染二维码需要自己写,可以参考示例中的二维码组件 vk-uni-qrcode
          codeUrl: '',
          qrcodeImage: '',
          // 当前支付状态 0:等待发起支付 1:支付中 2:已支付(注意:跟数据库的status无关)
          status: 0,
          // 当前页面是否显示
          pageShow: true,
          // 启用轮询检测订单支付状态(仅h5支付有效)
          polling: true,
          // 仅微信手机外部浏览器H5支付时有效,必须是http或https开头的绝对路径,且在微信H5支付配置的域名白名单中。你还需要将此H5域名加入uniCloud白名单
          // 如果此值为空,则默认返回当前页面,返回的页面url参数会带上confirmShow=true&out_trade_no=实际订单号
          returnUrl: '',
          // 确认已支付的弹窗开关(微信手机外部浏览器H5支付时有效)
          confirmShow: false,
          // 付款成功后尝试等待业务通知;业务处理结果以返回的 user_order_success 为准(当awaitNotify和payOrderInfo均为false时,支付成功的响应速度最快)
          awaitNotify: true,
          // 支付成功后,是否需要返回支付订单数据(当awaitNotify和payOrderInfo均为false时,支付成功的响应速度最快)
          payOrderInfo: false,
          // 是否自动获取小程序的openid(若传false,则在createPayment时需要自己传对应的openid,一般服务商模式下需要传false)
          autoGetOpenid: true,
        },
        // 表单请求数据
        form1: {
          provider: 'wxpay',
          total_fee: 1,
          out_trade_no: '',
          subject: '测试订单标题',
          body: '测试订单详情',
          type: 'recharge',
          openid: '',
        },
      };
    },
    // 监听 - 页面每次【加载时】执行(如:前进)
    onLoad(options = {}) {
      // 此处是因为微信H5外部浏览器支付后微信会重新打开指定页面,我们需要做一个弹窗让用户自己点下是否支付成功,同时云函数会去请求微信服务器检查是否真的付款成功。
      this.vkPay.confirmShow = options.confirmShow || false;
      if (options.out_trade_no) this.form1.out_trade_no = options.out_trade_no;
      if (options.code && options.state) {
        // 获取微信公众号的openid
        setTimeout(() => {
          this.getOpenid({
            code: options.code,
          });
        }, 300);
      }
    },
    // 监听 - 页面每次【显示时】执行(如:前进和返回) (页面每次出现在屏幕上都触发,包括从下级页面点返回露出当前页面)
    onShow() {
      this.vkPay.pageShow = true;
    },
    // 监听 - 页面每次【隐藏时】执行(如:返回)
    onHide() {
      this.vkPay.pageShow = false;
    },
    // 函数
    methods: {
      // 发起支付
      createPayment(obj = {}) {
        let { form1 } = this;
        // 这里的订单号\金额等数据应该是从数据库里获取的,这里为演示需要,故直接本地生成.
        form1.out_trade_no = obj.out_trade_no || 'test_' + Date.now();
        // #ifdef MP-WEIXIN
        form1.provider = 'wxpay';
        // #endif
        // #ifdef MP-ALIPAY
        form1.provider = 'alipay';
        // #endif
        this.$refs.vkPay.createPayment({
          loading: true, // 默认true,设为false可关闭本次支付的加载提示
          // 如果是非路由框架,则外层action不再是json,而为字符串,值为云函数名称,如 action: "你的云函数名称"
          // 如果是路由框架,则按下方配置填写
          // 如果云函数name为 vk-pay,则无需改动 action
          action: {
            name: 'vk-pay', // 云函数名称
            action: 'pay/createPayment', // 路由模式下云函数地址
            actionKey: 'action', // 路由模式下云函数地址的识别key(注意VK路由框架下,此值为$url)
            dataKey: 'data', // 路由模式下云函数请求参数的识别key
          },
          // 请求数据(data内的参数会传给云函数,云函数中通过 data.xxx 的方式获取)
          data: {
            provider: form1.provider,
            total_fee: form1.total_fee,
            out_trade_no: form1.out_trade_no,
            subject: form1.subject,
            body: form1.body,
            type: form1.type,
            openid: form1.openid, // 如果是微信公众号支付,则openid不能为空
          },
          // 支付订单创建成功回调
          create: (res) => {
            console.log('pay-create', res);
            this.form1.out_trade_no = res.out_trade_no; // 如果订单号是云端生成的,这里可以拿到订单号,此处如果return false; 则不再执行后续逻辑
          },
          // 支付成功回调
          success: (res) => {
            // 此处一般是写支付成功的提示或跳转到支付成功的页面。
            uni.showToast({ title: '支付成功', icon: 'success', mask: true });
            console.log('pay-success', res);
          },
          // 失败回调
          fail: (res) => {
            console.error('pay-fail', res);
            if (res.failType === 'create') {
              // 创建支付失败时提示
              uni.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
              });
            } else if (res.failType === 'request') {
              // 请求支付失败时提示
              uni.showToast({ title: '请求支付失败', icon: 'none', mask: true });
            } else if (res.failType === 'result') {
              // 支付结果失败时提示
              uni.showToast({ title: '支付失败', icon: 'none', mask: true });
            }
          },
          // 取消回调
          cancel: (res) => {
            uni.showToast({ title: '用户取消支付', icon: 'none', mask: true });
          },
        });
      },
      // 重新支付
      afreshPayment() {
        this.createPayment({
          out_trade_no: this.form1.out_trade_no,
        });
      },
      // 支付状态查询
      queryPayment() {
        // 支付状态查询你可以直接查你的订单表,看订单是否已支付(因为最终判定用户是否支付成功应该以你的订单表为准)
        // 如果vkPay.queryPayment接口返回支付成功,但你的订单表查询到未支付,代表你的异步回调函数写的有问题。
        this.$refs.vkPay.queryPayment({
          title: '查询中...',
          data: {
            out_trade_no: this.form1.out_trade_no,
          },
          needAlert: true,
          success: (data) => {
            this.vkPay.status = 2; // 标记为已支付
            this.vkPay.confirmShow = false; // 关闭确认弹窗(微信H5支付有弹窗确认)
            uni.showToast({ title: data.msg, icon: 'none', mask: true });
          },
          fail: (res = {}) => {
            if (res.msg === '订单已退款') {
              this.vkPay.confirmShow = false; // 关闭确认弹窗(微信H5支付有弹窗确认)
            }
          },
        });
      },
      // 退款,此为演示,实际业务开发不应该写在前端,而是写在云函数中。
      refund() {
        this.callFunction({
          title: '退款中...',
          name: 'vk-pay',
          data: {
            action: 'pay/refund',
            data: {
              out_trade_no: this.form1.out_trade_no,
              //refund_fee: 1, // 退款金额,100=1元(单位分)不填则全额退款
            },
          },
          success: (data) => {
            uni.showToast({ title: data.msg, icon: 'none', mask: true });
          },
        });
      },
      // 退款查询
      queryRefund() {
        this.callFunction({
          title: '查询中...',
          name: 'vk-pay',
          data: {
            action: 'pay/queryRefund',
            data: {
              out_trade_no: this.form1.out_trade_no,
            },
          },
          success: (data) => {
            uni.showModal({
              title: '提示',
              content: data.msg,
              showCancel: false,
            });
          },
        });
      },
      // 转账到支付宝,此为演示,实际业务开发不应该写在前端,而是写在云函数中。
      transferAlipay() {
        this.callFunction({
          title: '请求中...',
          name: 'vk-pay',
          data: {
            action: 'pay/transfer',
            data: {
              real_name: '真实姓名',
              account: '对方支付宝账号',
              pay_type: 'alipay',
            },
          },
          success: (data) => {
            uni.showModal({
              title: '提示',
              content: data.msg,
              showCancel: false,
            });
          },
        });
      },
      // 转账到微信零钱 v2版本,此为演示,实际业务开发不应该写在前端,而是写在云函数中。
      transferWxpay2() {
        this.callFunction({
          title: '请求中...',
          name: 'vk-pay',
          data: {
            action: 'pay/transfer',
            data: {
              real_name: '真实姓名',
              openid: 'oaQxQ5SYLXdTeGMeuBYjUqaguDBY',
              pay_type: 'wxpay',
              platform: 'mp-weixin',
            },
          },
          success: (data) => {
            uni.showModal({
              title: '提示',
              content: data.msg,
              showCancel: false,
            });
          },
        });
      },
      // 转账到微信零钱 v3版本,此为演示,实际业务开发不应该写在前端,而是写在云函数中。
      transferWxpay3() {
        this.callFunction({
          title: '请求中...',
          name: 'vk-pay',
          data: {
            action: 'pay/wxpayTransfer3',
            data: {},
          },
          success: (data) => {
            uni.showModal({
              title: '提示',
              content: data.msg,
              showCancel: false,
            });
          },
        });
      },
      // 获取微信支付v3版本的微信平台证书
      getWxpayPublicCert() {
        this.callFunction({
          title: '请求中...',
          name: 'vk-pay',
          data: {
            action: 'pay/getWxpayPublicCert',
            data: {},
          },
          success: (data) => {
            uni.showModal({
              title: '提示',
              content: '请按F12 看浏览器控制台的输出内容',
              showCancel: false,
            });
            let wxpayPublicCertSn = data.wxpayPublicCertSn;
            let wxpayPublicCertContent = data.wxpayPublicCertContent;
            console.log('wxpayPublicCertSn: ', wxpayPublicCertSn);
            console.log(`wxpayPublicCertContent: 请将它压缩成一行(复制下面的证书,用""引号框住证书内容,按一下回车,自动把换行转为\\n`);
            console.log(wxpayPublicCertContent);
          },
        });
      },
      // 取消支付
      cancelPay() {
        this.vkPay.status = 0;
        this.vkPay.codeUrl = '';
      },
      // 云函数调用简易封装,你也可以用你原本框架的云函数请求封装方法来调用云函数。
      callFunction(obj = {}) {
        let { needAlert = true } = obj;
        if (obj.title) uni.showLoading({ title: obj.title, mask: true });
        uniCloud.callFunction({
          ...obj,
          success: (result = {}) => {
            if (obj.title) uni.hideLoading();
            let res = result.result;
            if (res.code === 0) {
              if (typeof obj.success == 'function') obj.success(res);
            } else {
              if (needAlert && res.msg)
                uni.showModal({
                  title: '提示',
                  content: res.msg,
                  showCancel: false,
                });
              if (typeof obj.fail == 'function') obj.fail(res);
            }
          },
          fail: (res = {}) => {
            if (obj.title) uni.hideLoading();
            if (needAlert && res.msg)
              uni.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
              });
            if (typeof obj.fail == 'function') obj.fail(res);
          },
        });
      },
      // 选择支付方式
      radioChange(e) {
        this.form1.provider = e.detail.value;
      },
      // 获取公众号code
      getWeiXinJsCode(scope = 'snsapi_base') {
        let appid = 'wx2ebf03d174875bed'; // 填写公众号的appid
        let redirect_uri = window.location.href.split('?')[0];
        let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`;
        window.location.href = url;
      },
      // 获取公众号openid
      getOpenid(data) {
        let { code } = data;
        this.callFunction({
          title: '请求中...',
          name: 'vk-pay',
          data: {
            action: 'pay/code2SessionWeixinH5',
            data,
          },
          success: (res) => {
            if (res.openid) {
              this.form1.openid = res.openid;
              uni.showToast({
                title: '已获取到openid,可以开始支付',
                icon: 'none',
                mask: true,
              });
            }
          },
        });
      },
    },
    // 计算属性
    computed: {
      // h5运行环境
      h5Env() {
        // #ifdef H5
        let ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger' && ua.match(/miniprogram/i) == 'miniprogram') {
          // 微信小程序
          return 'mp-weixin';
        }
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
          // 微信公众号
          return 'h5-weixin';
        }
        if (ua.match(/alipay/i) == 'alipay' && ua.match(/miniprogram/i) == 'miniprogram') {
          // 支付宝小程序
          return 'mp-alipay';
        }
        if (ua.match(/alipay/i) == 'alipay') {
          // 支付宝内
          return 'h5-alipay';
        }
        // 外部 H5
        return 'h5';
        // #endif
      },
    },
  };
</script>
<style lang="scss" scoped>
  /* 示例页面样式开始 */
  .page-content {
    padding: 15px;
    max-width: 800px;
    margin: 0 auto;
    .input {
      width: 100%;
      height: 46px;
      border: solid 1px #dddddd;
      border-radius: 5px;
      margin-bottom: 15px;
      padding: 0px 15px;
      box-sizing: border-box;
    }
    .button {
      margin-bottom: 15px;
    }
  }
  /* 示例页面样式结束 */

  /* 外部浏览器H5支付弹窗确认开始 */
  .pay-confirm-popup {
    position: fixed;
    z-index: 2;
    width: 100vw;
    top: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    .pay-confirm-popup-content {
      width: 550rpx;
      margin: 50% auto 0 auto;
      background-color: #ffffff;
      border-radius: 10rpx;
      padding: 40rpx;
      .pay-confirm-popup-title {
        text-align: center;
        padding: 20rpx 0;
        margin-bottom: 30rpx;
      }
      .pay-confirm-popup-refresh {
        margin-top: 20rpx;
      }
      .pay-confirm-popup-cancel {
        margin-top: 20rpx;
        text-align: center;
      }
    }
  }
  /* 外部浏览器H5支付弹窗确认结束 */

  /* 二维码支付弹窗开始 */
  .pay-qrcode-popup {
    position: fixed;
    z-index: 9999;
    width: 100vw;
    top: 0;
    bottom: 0;
    top: 0;
    right: 0;
    .pay-qrcode-popup-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: rgba(0, 0, 0, 0.6);
    }
    .pay-qrcode-popup-content {
      position: relative;
      width: 500rpx;
      margin: 40% auto 0 auto;
      background-color: #ffffff;
      border-radius: 10rpx;
      padding: 40rpx;
      box-sizing: content-box;
      text-align: center;
      .pay-qrcode-popup-info {
        text-align: center;
        padding: 20rpx;
        .pay-qrcode-popup-info-fee {
          color: red;
          font-size: 60rpx;
          font-weight: bold;
        }
      }
      .pay-qrcode-popup-image {
        width: 450rpx;
        height: 450rpx;
      }
    }
  }
  /* 二维码支付弹窗结束 */
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605

# uni-app x 蒸汽模式

代码来自 pages-x/index/index.uvue,已内嵌页面样式。复制为同路径的 .uvue 页面并注册;页面中的付款码、转账入口需同时导入对应示例页面。公众号支付请替换 weixinAppId。

<template>
  <view class="demo-page">
    <scroll-view class="demo-scroll" direction="vertical">
      <view class="demo-content">
        <text class="demo-heading">官方渠道支付</text>
        <text class="demo-subtitle">微信 / 支付宝 · 金额单位为分,100 分 = 1 元</text>
        <view class="demo-card">
          <text class="demo-title">发起支付</text>
          <text class="demo-status">{{ statusText }}</text>
          <!-- #ifdef WEB || APP -->
          <radio-group class="demo-radio-group" @change="radioChange">
            <label class="demo-radio-label">
              <radio value="wxpay" :checked="form1.provider === 'wxpay'" />
              <text class="demo-radio-text">微信</text>
            </label>
            <label class="demo-radio-label">
              <radio value="alipay" :checked="form1.provider === 'alipay'" />
              <text class="demo-radio-text">支付宝</text>
            </label>
          </radio-group>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <text class="demo-tips">当前使用微信小程序支付</text>
          <!-- #endif -->
          <!-- #ifdef MP-ALIPAY -->
          <text class="demo-tips">当前使用支付宝小程序支付</text>
          <!-- #endif -->
          <text class="demo-label">支付金额(分)</text>
          <input class="demo-input" type="number" v-model="form1.total_fee" placeholder="支付金额" />
          <text class="demo-label">订单号</text>
          <input class="demo-input" v-model="form1.out_trade_no" placeholder="发起支付时自动生成" />
          <text class="demo-tips">示例本地生成订单号,创建成功后以云端返回的订单号为准。</text>
          <!-- #ifdef WEB -->
          <button v-if="h5Env === 'h5-weixin'" class="demo-button demo-light" @click="getWeiXinJsCode()">公众号获取 OpenID 示例</button>
          <text v-if="form1.openid" class="demo-tips">OpenID:{{ form1.openid }}</text>
          <!-- #endif -->
          <button class="demo-button demo-green" @click="createPayment()">
            {{ vkPay.status === 2 ? '再次发起支付' : '发起支付' }}
          </button>
          <button class="demo-button demo-light" @click="queryPayment">支付结果查询</button>
        </view>
        <view class="demo-card">
          <text class="demo-title">退款</text>
          <text class="demo-tips">对上方订单操作,默认全额退款。</text>
          <button class="demo-button demo-warn" @click="refund">申请退款</button>
          <button class="demo-button demo-light" @click="queryRefund">退款结果查询</button>
        </view>
        <view class="demo-card">
          <text class="demo-title">更多示例</text>
          <button class="demo-button demo-light" @click="codepay">扫用户付款码支付</button>
          <button class="demo-button demo-light" @click="transfer">转账示例</button>
          <button class="demo-button demo-light" @click="getWxpayPublicCert">获取微信支付 v3 平台证书</button>
        </view>
        <view v-if="resultText" class="demo-card">
          <text class="demo-title">最近一次返回</text>
          <text class="demo-result" :selectable="true">{{ resultText }}</text>
        </view>
      </view>
    </scroll-view>
    <vk-uni-pay
      ref="payRef"
      v-model:status="vkPay.status"
      v-model:codeUrl="vkPay.codeUrl"
      v-model:qrcodeImage="vkPay.qrcodeImage"
      :query-payment-action="vkPay.queryPaymentAction"
      :page-show="vkPay.pageShow"
      :polling="vkPay.polling"
      :return-url="vkPay.returnUrl"
      :auto-get-openid="vkPay.autoGetOpenid"
      :await-notify="vkPay.awaitNotify"
      :pay-order-info="vkPay.payOrderInfo"
    />
    <!-- Web 沿用原页面的扫码展示,不额外将二维码当作跳转链接。 -->
    <!-- #ifdef WEB -->
    <view v-if="vkPay.status < 2 && (vkPay.codeUrl || vkPay.qrcodeImage)" class="demo-popup">
      <view class="demo-popup-mask" @click="cancelPay"></view>
      <view class="demo-popup-content">
        <image v-if="vkPay.qrcodeImage" :src="vkPay.qrcodeImage" class="demo-qrcode" />
        <vk-uni-qrcode v-else :text="vkPay.codeUrl" :size="225" unit="px" :padding="10" />
        <text class="demo-fee">{{ (Number(form1.total_fee) / 100).toFixed(2) }} 元</text>
        <text class="demo-tips">请使用{{ form1.provider === 'wxpay' ? '微信' : '支付宝' }}扫码支付</text>
        <button class="demo-button demo-green" @click="queryPayment">我已完成支付</button>
      </view>
    </view>
    <!-- #endif -->
    <!-- App 跳转支付宝前显示;Web 保留 H5 返回后的确认入口。 -->
    <!-- #ifdef WEB || APP -->
    <view v-if="vkPay.confirmShow && !vkPay.codeUrl && !vkPay.qrcodeImage" class="demo-popup">
      <view class="demo-popup-mask" @click="cancelPay"></view>
      <view class="demo-popup-content">
        <text class="demo-title">请确认支付是否已完成</text>
        <button class="demo-button demo-green" @click="queryPayment">我已支付</button>
        <button class="demo-button demo-light" @click="afreshPayment">重新支付</button>
      </view>
    </view>
    <!-- #endif -->
    <!-- #ifndef WEB -->
    <vk-uni-pay-qrcode-popup
      :status="vkPay.status"
      :code-url="vkPay.codeUrl"
      :qrcode-image="vkPay.qrcodeImage"
      :out-trade-no="form1.out_trade_no"
      :total-fee="form1.total_fee"
      :provider="form1.provider"
      @close="cancelPay"
      @query="queryPayment"
      @afresh="afreshPayment"
    />
    <!-- #endif -->
  </view>
</template>

<script setup lang="ts">
  // 页面数据变量
  // ref 定义的变量在脚本中通过 .value 读写;reactive 定义的对象直接读写属性。
  // 支付组件实例。模板中的 ref="payRef" 与这里对应,通过 payRef.value 调用组件方法。
  const payRef = ref(null);

  // 是否正在创建支付,避免重复点击支付按钮。
  const creating = ref(false);

  // 是否正在查询、退款或调用其他云端接口。
  const requesting = ref(false);

  // 页面底部展示的接口返回结果,仅用于示例调试。
  const resultText = ref('');

  // 支付组件配置。查询接口使用默认路由即可。
  const vkPay = reactive({
    queryPaymentAction: {
      name: 'vk-pay', // 云函数名称
      action: 'pay/queryPayment', // 云函数中的查询接口
      actionKey: 'action', // 云函数接口地址的识别 key
      dataKey: 'data', // 云函数请求参数的识别 key
    },
    codeUrl: '', // 二维码内容
    qrcodeImage: '', // 云端直接返回的二维码图片
    status: 0, // 0:等待支付;1:支付中;2:已支付(与数据库订单状态不同)
    pageShow: true, // 当前页面是否显示,用于暂停或恢复查询
    polling: true, // 二维码支付时自动查询支付结果
    returnUrl: '', // 微信 H5 支付返回地址,留空时返回当前页
    confirmShow: false, // App 跳转支付宝前、Web H5 返回后的确认弹窗
    awaitNotify: true, // 等待云端业务异步通知执行完成后,再通知前端支付成功
    payOrderInfo: false, // 支付成功后是否返回订单详情
    autoGetOpenid: true, // 自动获取小程序 OpenID
  });

  // 表单请求数据。金额单位为分,100 分 = 1 元。
  const form1 = reactive({
    provider: 'wxpay', // wxpay:微信支付;alipay:支付宝支付
    total_fee: 1, // 支付金额(分)
    out_trade_no: '', // 商户订单号
    subject: '测试订单标题', // 订单标题
    body: '测试订单详情', // 订单详情
    type: 'recharge', // 支付成功后执行的云端业务回调类型
    openid: '', // 公众号支付需要的用户 OpenID
  });

  // 微信公众号 AppID,沿用原示例;实际使用时替换为自己的公众号 AppID。
  const weixinAppId = 'wx2ebf03d174875bed';

  // 暂存页面参数,在组件就绪后处理公众号授权和 H5 返回。
  let loadOptions = {};

  // 页面离开后忽略尚未完成的异步回调。
  let alive = true;

  // 页面生命周期
  // 监听:页面加载时读取参数。
  onLoad((options = {}) => {
    loadOptions = { ...options };
    // OAuth/H5 支付参数可能在 hash 路由外,不能只读取 onLoad 的路由参数。
    // #ifdef WEB
    const url = new URL(window.location.href);
    const hashQuery = new URLSearchParams(url.hash.includes('?') ? url.hash.slice(url.hash.indexOf('?') + 1) : '');
    for (const key of ['confirmShow', 'out_trade_no', 'code', 'state', 'return']) {
      if (loadOptions[key] === undefined) {
        loadOptions[key] = url.searchParams.get(key) || hashQuery.get(key) || '';
      }
    }
    // #endif
    vkPay.confirmShow = loadOptions.confirmShow === true || ['true', '1'].includes(String(loadOptions.confirmShow));
    if (loadOptions.out_trade_no) {
      form1.out_trade_no = loadOptions.out_trade_no;
    }
    // #ifdef MP-WEIXIN
    form1.provider = 'wxpay';
    // #endif
    // #ifdef MP-ALIPAY
    form1.provider = 'alipay';
    // #endif
  });

  // 监听:页面就绪后,支付组件的 ref 才能使用。
  onReady(async () => {
    // #ifdef WEB
    if (loadOptions.code && loadOptions.state) {
      await getOpenid({ code: loadOptions.code });
    }
    if (alive && String(loadOptions.return) === '1' && loadOptions.out_trade_no) {
      await queryPayment();
    }
    // #endif
  });

  // 监听:页面显示时恢复支付结果查询。
  onShow(() => {
    vkPay.pageShow = true;
  });

  // 监听:页面隐藏时暂停支付结果查询。
  onHide(() => {
    vkPay.pageShow = false;
  });

  // 监听:页面离开后,不再显示旧请求的提示。
  onUnload(() => {
    alive = false;
    vkPay.pageShow = false;
  });

  // 页面方法
  // 发起支付:先准备订单参数,再调用支付组件。
  async function createPayment(options = {}) {
    // “支付中”仍可再次发起;创建、查单等请求尚未结束时,继续拦截重复操作。
    if (!alive || !payRef.value || creating.value || requesting.value) {
      return;
    }
    if (!Number.isInteger(Number(form1.total_fee)) || Number(form1.total_fee) <= 0) {
      showError({ msg: '支付金额须为大于 0 的整数,单位分' });
      return;
    }
    // #ifdef WEB
    if (h5Env.value === 'h5-weixin' && /webdebugger/i.test(navigator.userAgent)) {
      showError({ msg: '微信公众号支付请用真机测试,且必须是线上域名' });
      return;
    }
    // #endif
    // #ifdef MP-WEIXIN
    form1.provider = 'wxpay';
    // #endif
    // #ifdef MP-ALIPAY
    form1.provider = 'alipay';
    // #endif
    // 示例为了方便在本地生成订单号;实际业务通常由云端创建订单。
    form1.out_trade_no = options.out_trade_no || 'test_' + Date.now();
    vkPay.codeUrl = '';
    vkPay.qrcodeImage = '';
    vkPay.confirmShow = false;
    creating.value = true;
    try {
      await payRef.value.createPayment({
        // 如果使用默认 vk-pay 云函数,下面的 action 配置无需修改。
        action: {
          name: 'vk-pay', // 云函数名称
          action: 'pay/createPayment', // 云函数中的创建支付接口
          actionKey: 'action', // 接口地址的识别 key
          dataKey: 'data', // 请求参数的识别 key
        },
        // 请求参数会原样传给云函数,请按业务需求填写。
        data: {
          provider: form1.provider,
          total_fee: Number(form1.total_fee), // 支付金额,单位分
          out_trade_no: form1.out_trade_no,
          subject: form1.subject,
          body: form1.body,
          type: form1.type,
          openid: form1.openid,
        },
        // 支付订单创建成功:以云端返回的订单号为准。
        create: (res) => {
          if (!alive) {
            return;
          }
          form1.out_trade_no = res.out_trade_no || form1.out_trade_no;
          // 云端 alipayAppPayToH5Pay 生效后返回 alipay_h5,组件接下来会跳转支付宝。
          // 先显示确认弹窗,用户返回后可查单或继续使用当前订单重新支付。
          // #ifdef APP
          vkPay.confirmShow = res.pay_type === 'alipay_h5' && !res.needQRcode;
          // #endif
          record(res);
        },
        // 支付成功:可在这里提示用户或跳转到业务页面。
        success: (res) => {
          if (!alive) {
            return;
          }
          vkPay.confirmShow = false;
          record(res);
          uni.showToast({
            title: '支付成功',
            icon: 'success',
          });
        },
        // 支付失败:展示失败原因,方便排查。
        fail: (res) => {
          if (!alive) {
            return;
          }
          vkPay.confirmShow = false;
          record(res);
          showError(res);
        },
        // 用户取消支付。
        cancel: (res) => {
          if (!alive) {
            return;
          }
          vkPay.confirmShow = false;
          record(res);
          uni.showToast({
            title: '用户取消支付',
            icon: 'none',
          });
        },
      });
    } catch (error) {
      if (alive) {
        vkPay.confirmShow = false;
      }
      showError(error);
    } finally {
      creating.value = false;
    }
  }

  // 重新支付:继续使用当前订单号,不另外生成订单。
  async function afreshPayment() {
    if (!alive || !payRef.value || creating.value || requesting.value || !hasOrder()) {
      return;
    }
    vkPay.status = 0;
    // 等待组件收到状态重置,结束上次轮询,再请求当前订单的支付参数。
    await nextTick();
    return createPayment({ out_trade_no: form1.out_trade_no });
  }

  // 查询支付状态。实际业务应以云端订单和异步通知为准。
  async function queryPayment() {
    if (!alive || !payRef.value || creating.value || requesting.value || !hasOrder()) {
      return;
    }
    const outTradeNo = form1.out_trade_no;
    const isCurrentOrder = () => alive && form1.out_trade_no === outTradeNo;
    requesting.value = true;
    try {
      await payRef.value.queryPayment({
        title: '查询中...',
        data: {
          out_trade_no: outTradeNo,
        },
        needAlert: false,
        success: (res) => {
          if (!isCurrentOrder()) {
            return;
          }
          vkPay.status = 2;
          vkPay.confirmShow = false;
          record(res);
          uni.showToast({
            title: res.msg || '支付成功',
            icon: 'none',
          });
        },
        fail: (res) => {
          if (!isCurrentOrder()) {
            return;
          }
          if (res.msg === '订单已退款') {
            vkPay.confirmShow = false;
          }
          record(res);
        },
      });
    } catch (error) {
      if (isCurrentOrder()) {
        showError(error);
      }
    } finally {
      requesting.value = false;
    }
  }

  // 申请退款。此为演示,实际业务应由云端校验退款权限和金额。
  function refund() {
    if (!hasOrder()) {
      return;
    }
    return callFunction({
      title: '退款中...',
      name: 'vk-pay', // 云函数名称
      data: {
        action: 'pay/refund', // 云函数中的接口地址
        data: {
          out_trade_no: form1.out_trade_no,
        }, // 接口需要的请求参数
      },
      // 请求成功后,展示结果或执行下一步操作
      success: (res) => {
        uni.showToast({
          title: res.msg || '退款申请已提交',
          icon: 'none',
        });
      },
    });
  }

  // 查询当前订单的退款结果。
  function queryRefund() {
    if (!hasOrder()) {
      return;
    }
    return callFunction({
      title: '查询中...',
      name: 'vk-pay', // 云函数名称
      data: {
        action: 'pay/queryRefund', // 云函数中的接口地址
        data: {
          out_trade_no: form1.out_trade_no,
        }, // 接口需要的请求参数
      },
      // 请求成功后,展示结果或执行下一步操作
      success: (res) => {
        uni.showToast({
          title: res.msg || JSON.stringify(res),
          icon: 'none',
          duration: 3000,
        });
      },
    });
  }

  // 获取微信支付 v3 平台证书。
  function getWxpayPublicCert() {
    return callFunction({
      title: '请求中...',
      name: 'vk-pay', // 云函数名称
      data: {
        action: 'pay/getWxpayPublicCert', // 云函数中的接口地址
        data: {}, // 接口需要的请求参数
      },
      // 请求成功后,展示结果或执行下一步操作
      success: (res) => {
        console.log('wxpayPublicCertSn:', res.wxpayPublicKeyId || res.wxpayPublicCertSn);
        console.log('wxpayPublicCertContent:', res.wxpayPublicKeyContent || res.wxpayPublicCertContent);
        uni.showToast({
          title: '证书已显示在页面返回结果中',
          icon: 'none',
        });
      },
    });
  }

  // 关闭支付弹窗并重置页面状态,订单号保留,仍可查询原订单。
  function cancelPay() {
    vkPay.status = 0;
    vkPay.confirmShow = false;
    vkPay.codeUrl = '';
    vkPay.qrcodeImage = '';
  }

  // 选择微信或支付宝支付。
  function radioChange(event) {
    form1.provider = event.detail.value;
  }

  // #ifdef WEB
  // 获取公众号授权 code,回调地址保留当前页面的路由参数。
  function getWeiXinJsCode(scope = 'snsapi_base') {
    const redirect = new URL(window.location.href);
    for (const key of ['code', 'state']) {
      redirect.searchParams.delete(key);
    }
    if (redirect.hash.includes('?')) {
      const [route, query] = redirect.hash.split('?');
      const params = new URLSearchParams(query);
      params.delete('code');
      params.delete('state');
      redirect.hash = route + (params.toString() ? '?' + params.toString() : '');
    }
    window.location.href =
      'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
      weixinAppId +
      '&redirect_uri=' +
      encodeURIComponent(redirect.toString()) +
      '&response_type=code&scope=' +
      scope +
      '&state=STATE#wechat_redirect';
  }
  // #endif

  // #ifdef WEB
  // 根据公众号授权返回的 code 获取 OpenID。
  function getOpenid(data) {
    return callFunction({
      title: '请求中...',
      name: 'vk-pay',
      data: {
        action: 'pay/code2SessionWeixinH5',
        data: {
          code: data.code,
        },
      },
      success: (res) => {
        if (res.openid) {
          form1.openid = res.openid;
          uni.showToast({
            title: '已获取 OpenID,可以开始支付',
            icon: 'none',
          });
        }
      },
    });
  }
  // #endif

  // 跳转到付款码支付示例。
  function codepay() {
    uni.navigateTo({ url: '/pages-x/index/codepay' });
  }

  // 跳转到转账示例。
  function transfer() {
    uni.navigateTo({ url: '/pages-x/index/transfer' });
  }

  // 显示接口或支付组件返回的错误信息。
  function showError(error = {}) {
    if (alive) {
      uni.showToast({
        title: error.msg || error.errMsg || error.message || '请求失败,请重试',
        icon: 'none',
        duration: 3000,
      });
    }
  }

  // 把最近一次返回显示在页面中,方便对照接口结果。
  function record(result) {
    if (alive) {
      resultText.value = JSON.stringify(result, null, 2);
    }
  }

  // 查询和退款之前,检查是否已输入或创建订单号。
  function hasOrder() {
    if (String(form1.out_trade_no).trim()) {
      return true;
    }
    showError({ msg: '请先输入或创建订单号' });
    return false;
  }

  // 云函数调用简易封装,也可以替换为你自己项目中的请求方法。
  // 调用时把 name、data、success、fail 写在一起,便于看清每个接口的参数和回调。
  async function callFunction(obj = {}) {
    // 同一时间只执行一个云端请求,页面离开后不再更新页面。
    if (creating.value || requesting.value || !alive) {
      return null;
    }
    requesting.value = true;
    if (obj.title) {
      uni.showLoading({
        title: obj.title,
        mask: true,
      });
    }
    try {
      let response;
      try {
        response = await uniCloud.callFunction({ name: obj.name, data: obj.data });
      } finally {
        // 先关闭本次请求的遮罩,再显示结果或执行后续跳转。
        if (obj.title) {
          uni.hideLoading();
        }
      }
      if (!alive) {
        return null;
      }
      let res = response.result || {};
      record(res);
      if (res.code === 0) {
        if (typeof obj.success === 'function') {
          obj.success(res);
        }
        return res;
      }
      // 云函数已执行,但业务处理失败,例如订单号不存在。
      if (obj.needAlert !== false) {
        showError(res);
      }
      if (typeof obj.fail === 'function') {
        obj.fail(res);
      }
      return null;
    } catch (res) {
      // 网络错误等情况也会到这里,允许用户稍后重试。
      if (!alive) {
        return null;
      }
      if (obj.needAlert !== false) {
        showError(res);
      }
      if (typeof obj.fail === 'function') {
        obj.fail(res);
      }
      return null;
    } finally {
      requesting.value = false;
    }
  }

  // 计算属性
  // 根据支付状态展示页面提示。
  const statusText = computed(() => {
    if (vkPay.status === 1) {
      return '支付中';
    }
    if (vkPay.status === 2) {
      return '已支付';
    }
    return '等待发起支付';
  });

  // 识别 Web 运行环境,区分微信公众号、支付宝内和外部浏览器。
  const h5Env = computed(() => {
    // #ifdef WEB
    const ua = navigator.userAgent.toLowerCase();
    if (/micromessenger/.test(ua)) {
      return /miniprogram/.test(ua) ? 'mp-weixin' : 'h5-weixin';
    }
    if (/alipay/.test(ua)) {
      return /miniprogram/.test(ua) ? 'mp-alipay' : 'h5-alipay';
    }
    return 'h5';
    // #endif
    // #ifndef WEB
    return '';
    // #endif
  });
</script>

<style scoped>
  /* 页面直接引入共用浅色样式;不依赖 App 全局样式穿透组件。 */
  .demo-page {
    flex: 1;
    height: 100%;
    background-color: #f5f7fb;
  }

  .demo-scroll {
    flex: 1;
    height: 100%;
  }

  .demo-content {
    width: 100%;
    max-width: 800px;
    align-self: center;
    padding: 16px;
    box-sizing: border-box;
  }

  .demo-heading {
    font-size: 24px;
    font-weight: bold;
    color: #172b4d;
    margin-bottom: 8px;
  }

  .demo-subtitle {
    font-size: 14px;
    line-height: 22px;
    color: #64748b;
    margin-bottom: 20px;
  }

  .demo-card {
    background-color: #ffffff;
    border-radius: 10px;
    padding: 18px;
    margin-bottom: 16px;
  }

  .demo-title {
    font-size: 17px;
    font-weight: bold;
    color: #172b4d;
    margin-bottom: 10px;
  }

  .demo-label {
    font-size: 14px;
    color: #334155;
    margin-top: 12px;
    margin-bottom: 8px;
  }

  .demo-tips {
    font-size: 13px;
    line-height: 20px;
    color: #64748b;
    margin-top: 8px;
  }

  .demo-status {
    font-size: 14px;
    color: #1677ff;
    margin-bottom: 8px;
  }

  .demo-input {
    height: 44px;
    width: 100%;
    border: 1px solid #dbe3ed;
    border-radius: 6px;
    padding: 0 12px;
    box-sizing: border-box;
    font-size: 15px;
    color: #172b4d;
    background-color: #ffffff;
  }

  .demo-radio-group {
    flex-direction: row;
    flex-wrap: wrap;
    align-items: center;
  }

  .demo-radio-label {
    flex-direction: row;
    align-items: center;
    margin-right: 20px;
    margin-bottom: 8px;
  }

  .demo-radio-text {
    font-size: 15px;
    color: #334155;
  }

  .demo-button {
    width: 100%;
    margin-top: 12px;
    padding: 12px;
    border-radius: 6px;
    border-width: 0;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    font-size: 15px;
    line-height: 22px;
    color: #ffffff;
    text-align: center;
  }

  .demo-primary {
    background-color: #1677ff;
  }

  .demo-green {
    background-color: #28a159;
  }

  .demo-warn {
    background-color: #d95454;
  }

  .demo-light {
    background-color: #edf2f8;
    color: #334155;
  }

  .demo-result {
    font-size: 13px;
    line-height: 21px;
    color: #334155;
  }

  .demo-timeline {
    margin-top: 16px;
    padding: 12px;
    border-radius: 6px;
    background-color: #f5f7fb;
  }

  .demo-timeline-item {
    font-size: 13px;
    line-height: 22px;
    color: #475569;
    margin-bottom: 6px;
  }

  .demo-popup {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 998;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .demo-popup-mask {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
  }

  .demo-popup-content {
    position: absolute;
    top: 17%;
    width: 90%;
    max-width: 300px;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 10px;
    background-color: #ffffff;
    align-items: center;
  }

  .demo-qrcode {
    width: 225px;
    height: 225px;
    background-color: #ffffff;
  }

  .demo-fee {
    color: #e34d59;
    font-size: 28px;
    font-weight: bold;
    margin-top: 12px;
  }
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841