# 微信小程序虚拟支付
vk-pay 版本要求
uni-app 需 vk-pay 版本 >= 1.12.2
uni-app x 需 vk-pay 版本 >= 1.18.0 且 HBuilderX ≥ 5.33
概述
微信规定上架短剧类目的小程序必须使用微信小程序虚拟支付,不可以使用原先的微信支付
注意
- 微信小程序虚拟支付只有特定类目的小程序才能开通
- 微信小程序虚拟支付有较高的手续费,由微信官方收取,非本插件收取(手续费多少跟使用本插件无关)
# 配置

对应支付配置的节点是 wxpay-virtual.mp-weixin
const fs = require('fs');
const path = require('path');
module.exports = {
/**
* 统一支付回调地址,格式为 "服务空间SpaceID":"URL化完整地址"
* 这里的本地开发并不是指 http://localhost:8080/ 的地址,而是另外一个服务空间的ULR化地址(如果你本地开发和线上环境共用同一个服务空间则只需要填线上环境的即可)
* 回调的云函数地址,建议填 /http/vk-pay,因为vk-pay云函数已经写好了回调处理的逻辑,否则你需要自己写全部的回调逻辑。
* 其中vk-pay是可以改名的,只需要修改 uniCloud/cloudfunctions/vk-pay/package.json 文件中的 "path": "/http/vk-pay", 把 /http/vk-pay 改成 /http/xxxx 即可(需要重新上传云函数vk-pay)。
*/
notifyUrl: {
// 本地开发环境,如果你本地开发和线上环境共用同一个服务空间则只需要填线上环境的即可
'mp-22d55e33-c2f3-22b4-55fc-7b33a6144e22': 'https://fc-mp-22d55e33-c2f3-22b4-55fc-7b33a6144e22.next.bspapp.com/http/vk-pay',
// 线上正式环境
'mp-6666d886-00b6-22b2-9156-84afeadcf669': 'https://fc-mp-6666d886-00b6-22b2-9156-84afeadcf669.next.bspapp.com/http/vk-pay',
},
// 微信虚拟支付
'wxpay-virtual': {
// 微信 - 小程序支付
'mp-weixin': {
'appId': '', // 小程序的appid
'secret': '', // secret
'mchId': '', // 商户id(在虚拟支付 - 基本配置 - 微信支付账号信息中获取)
'offerId': '', // 支付应用ID(在虚拟支付 - 基本配置 - 基础配置中获取)
'appKey': '', // 现网AppKey(正式环境,在虚拟支付 - 基本配置 - 基础配置中获取)
'sandboxAppKey': '', // 沙箱AppKey(在虚拟支付 - 基本配置 - 基础配置中获取)
'rate': 100, // 代币兑换比例,比如1元兑换100代币,那么这里就是100(需要开通虚拟支付的时候也设置成 1 人民币 = 100 代币)
'token': '', // 微信小程序通信的token,在开发 - 开发管理 - 消息推送 - Token(令牌) 通信地址填:https://url地址/vk-pay-notify/wxpay-virtual_mp-weixin
'encodingAESKey': '', // 必须43位,微信小程序消息加密密钥,在开发 - 开发管理 - 消息推送 - EncodingAESKey(消息加解密密钥)
'sandbox': false, // 是否是沙箱环境(注意:沙箱环境异步回调可能有延迟,建议直接正式环境测试)
},
},
};
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
# 示例代码
按项目类型选择对应的页面代码,云端配置和 API 共用。
# uni-app
<template>
<view class="app">
<!-- 页面示例开始 -->
<view class="page-content">
<view class="ios-tips"> 注意:苹果手机需要在微信虚拟支付 - 基本配置 - 启用苹果IAP支付后才能支付(订单实付金额需≥1元) </view>
<view class="card">
<view class="title">代币充值示例</view>
<view class="content">
<view style="margin-bottom: 8px">充值代币数量(建议设置 1 人民币 = 100 代币)</view>
<input class="input" type="text" v-model.number="form1.wxpay_virtual.buy_quantity" placeholder="支付金额" />
<view style="margin-bottom: 8px">订单号</view>
<input class="input" type="text" v-model="form1.out_trade_no" placeholder="订单号,点击支付会自动生成" />
<button class="button button-green" type="primary" @click="callPayment('short_series_coin')">发起微信虚拟支付</button>
<button class="button" type="default" @click="afreshPayment('short_series_coin')" v-if="form1.out_trade_no">原订单发起支付</button>
<button class="button" type="default" @click="queryPayment">支付结果查询</button>
<button class="button" type="default" @click="queryUserBalance">查询我的代币余额</button>
</view>
</view>
<view class="card">
<view class="title">道具直购示例</view>
<view class="content">
<view style="margin-bottom: 8px">
<view style="margin: 5px 0">道具选择</view>
<radio-group @change="productIdChange">
<label> <radio value="test001" checked="true" />道具1 </label>
<label style="margin-left: 10px"> <radio value="test002" />道具2 </label>
</radio-group>
</view>
<view style="margin-bottom: 8px">购买道具数量</view>
<input class="input" type="text" v-model.number="form1.wxpay_virtual.buy_quantity" placeholder="支付金额" />
<view style="margin-bottom: 8px">订单号</view>
<input class="input" type="text" v-model="form1.out_trade_no" placeholder="订单号,点击支付会自动生成" />
<button class="button button-green" type="primary" @click="callPayment('short_series_goods')">发起微信虚拟支付</button>
<button class="button" type="default" @click="afreshPayment('short_series_goods')" v-if="form1.out_trade_no">原订单发起支付</button>
<button class="button" type="default" @click="queryPayment">支付结果查询</button>
</view>
</view>
<view class="card">
<view class="title">退款示例</view>
<view class="content">
<view style="margin-bottom: 8px">订单号</view>
<input class="input" type="text" v-model="form1.out_trade_no" placeholder="需要退款的订单号" />
<view style="margin-bottom: 8px">退款(单位分 100 = 1元):</view>
<input class="input" type="text" v-model="form1.refund_fee" placeholder="退款金额,不填则全额退款" />
<view class="tips">注意:如果是代币充值订单,退款不会自动扣减用户的代币</view>
<button class="button" type="warn" @click="refund">申请退款</button>
<button class="button" type="default" @click="queryRefund">退款结果查询</button>
</view>
</view>
<view class="card">
<view class="title">代币相关其他接口示例</view>
<view class="content">
<view style="margin-bottom: 8px">代币数量</view>
<input class="input" type="text" v-model.number="currencyPayFormData.amount" placeholder="代币数量" />
<view style="margin-bottom: 8px">订单号</view>
<input class="input" type="text" v-model="currencyPayFormData.out_trade_no" placeholder="订单号,点击扣减代币会自动生成" />
<button class="button" type="default" @click="queryUserBalance">查询我的代币余额</button>
<button class="button" type="default" @click="currencyPay">扣减代币</button>
<button class="button" type="default" @click="cancelCurrencyPay" v-if="currencyPayFormData.out_trade_no">扣减代币回退(撤销本次扣减的代币)</button>
<view class="tips" v-if="currencyPayFormData.out_trade_no">currencyPay接口的逆操作</view>
<button class="button" type="default" @click="presentCurrency">赠送代币(增加代币)</button>
</view>
</view>
</view>
<!-- 页面示例结束 -->
<!-- vue2版本的支付组件开始 -->
<!-- #ifdef VUE2 -->
<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"
: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"
:await-notify="vkPay.awaitNotify"
:pay-order-info="vkPay.payOrderInfo"
></vk-uni-pay>
<!-- #endif -->
<!-- vue3版本的支付组件结束 -->
</view>
</template>
<script>
export default {
data() {
// 页面数据变量
return {
vkPay: {
/**
* 查询支付状态的云函数配置
* 如果是非路由框架,则action为字符串,值为云函数名称
* 如果是路由框架,则按下方配置填写
* 注意:queryPaymentAction内参数用默认即可,无需更改。(除非你已经知道参数的意义)
*/
queryPaymentAction: {
name: 'vk-pay', // 云函数名称
action: 'pay/queryPayment', // 路由模式下云函数地址
actionKey: 'action', // 路由模式下云函数地址的识别key
dataKey: 'data', // 路由模式下云函数请求参数的识别key
},
codeUrl: '', // 微信虚拟支付此参数无效
qrcodeImage: '', // 微信虚拟支付此参数无效
// 当前支付状态 0:等待发起支付 1:支付中 2:已支付(注意:跟数据库的status无关)
status: 0,
// 当前页面是否显示
pageShow: true,
// 启用轮询检测订单支付状态
polling: true,
// 支付成功后,是否需要等待异步回调全部执行完成后才通知前端(当awaitNotify和payOrderInfo均为false时,支付成功的响应速度最快)
awaitNotify: true,
// 支付成功后,是否需要返回支付订单数据(当awaitNotify和payOrderInfo均为false时,支付成功的响应速度最快)
payOrderInfo: false,
// 是否自动获取小程序的openid
autoGetOpenid: true,
},
// 表单请求数据
form1: {
provider: 'wxpay-virtual', // 支付供应商,此处固定为vkspay
out_trade_no: '', // 订单号
subject: '测试订单标题', // 订单标题
type: 'wxpay-virtual-test', // 支付回调类型,支付成功后会执行 vk-pay/pay-notify/wxpay-virtual-test 云函数(可自定义)
openid: '', // 微信小程序的用户openid
refund_fee: '', // 部分退款时传的退款金额(单位分,100=1元)
wxpay_virtual: {
mode: 'short_series_coin', // 模式 short_series_coin 代币充值 short_series_goods 道具直购
buy_quantity: 1, // 购买代币数量或道具数量
product_id: 'test001', // 道具id,在微信小程序后台 - 功能 - 虚拟支付 - 基本配置 - 道具配置 中配置道具id
goods_price: 1, // 道具价格,需要和配置的价格一致才能正常发起支付
},
},
currencyPayFormData: {
out_trade_no: '',
amount: 1,
},
// 页面参数
options: {},
};
},
// 监听 - 页面每次【加载时】执行(如:前进)
onLoad(options = {}) {
this.options = options;
},
// 监听 - 页面每次【加载完毕】执行
onReady() {},
// 监听 - 页面每次【显示时】执行(如:前进和返回) (页面每次出现在屏幕上都触发,包括从下级页面点返回露出当前页面)
onShow() {
this.vkPay.pageShow = true;
},
// 监听 - 页面每次【隐藏时】执行(如:返回)
onHide() {
this.vkPay.pageShow = false;
},
// 函数
methods: {
// 发起支付
createPayment(obj = {}) {
// #ifndef MP-WEIXIN
uni.showModal({
title: '提示',
content: '请在微信小程序中体验',
showCancel: false,
});
return;
// #endif
let that = this;
let { form1 } = that;
// 这里的订单号\金额等数据应该是从数据库里获取的,这里为演示需要,故直接本地生成.
form1.out_trade_no = obj.out_trade_no || 'test_' + Date.now();
that.$refs.vkPay.createPayment({
// 如果是非路由框架,则外层action不再是json,而为字符串,值为云函数名称,如 action: "你的云函数名称"
// 如果是路由框架,则按下方配置填写
// 如果云函数name为 vk-pay,则无需改动 action
action: {
name: 'vk-pay', // 云函数名称
action: 'pay/createPayment', // 路由模式下云函数地址
actionKey: 'action', // 路由模式下云函数地址的识别key
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,
type: form1.type,
openid: form1.openid,
wxpay_virtual: form1.wxpay_virtual, // 微信虚拟支付专属字段
},
// 支付订单创建成功回调
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: false });
console.log('pay-success', res);
},
// 失败回调
fail: (err) => {
console.error('pay-fail', err);
let errData = {
'-5': '开通签约结果未知',
'-15002': 'outTradeNo重复使用,请换新单号重试',
'-15003': '系统错误',
'-15005': '支付配置错误',
'-15006': '支付配置错误',
'-15007': 'session_key过期,用户需要重新登录',
'-15008': '二级商户进件未完成',
'-15009': '代币未发布',
'-15010': '道具productId未发布',
'-15012': '调用米大师失败导致关单,请换新单号重试',
'-15013': '道具价格错误',
'-15014': '道具/代币发布未生效,禁止下单,大概10分钟后生效',
'-15017': '此商家涉嫌违规,收款功能已被限制,暂无法支付。商家可以登录微信商户平台/微信支付商家助手小程序查看原因和解决方案',
'-15018': '代币或者道具productId审核不通过',
'-15019': '调微信报商户受限,商家可以登录微信商户平台/微信支付商家助手小程序查看原因和解决方案',
'-15020': '操作过快,请稍候再试',
'-15021': '小程序被限频交易',
};
let errMsg = errData[String(err.errCode)] || err.errMsg || err.msg || err.message;
if (errMsg === 'requestVirtualPayment:fail INVALID_PLATFORM') {
errMsg = '苹果手机不支持微信虚拟支付';
} else if (errMsg === 'requestVirtualPayment:fail no permission') {
errMsg = '微信基础库 2.19.2 开始才支付微信虚拟支付';
}
console.error(errMsg);
uni.showModal({
title: '提示',
content: errMsg,
showCancel: false,
});
},
// 取消回调
cancel: (res) => {
uni.showToast({ title: '用户取消支付', icon: 'none', mask: false });
},
});
},
// 调起支付
callPayment(mode) {
this.form1.wxpay_virtual.mode = mode;
this.createPayment();
},
// 重新支付
afreshPayment(mode) {
this.form1.wxpay_virtual.mode = mode;
this.createPayment({
out_trade_no: this.form1.out_trade_no,
});
},
// 支付状态查询
async queryPayment() {
// 支付状态查询你可以直接查你的订单表,看订单是否已支付(因为最终判定用户是否支付成功应该以你的订单表为准)
// 如果vkPay.queryPayment接口返回支付成功,但你的订单表查询到未支付,代表你的异步回调函数写的有问题。
if (!this.$refs.vkPay) {
// 尝试延迟100毫秒
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await sleep(100);
}
this.$refs.vkPay.queryPayment({
title: '查询中...',
data: {
out_trade_no: this.form1.out_trade_no,
},
needAlert: true,
success: (data) => {
this.vkPay.status = 2; // 标记为已支付
uni.showToast({ title: data.msg, icon: 'none', mask: false });
},
fail: (res = {}) => {},
});
},
// 退款,此为演示,实际业务开发不应该写在前端,而是写在云函数中。
refund() {
this.callFunction({
title: '退款中...',
name: 'vk-pay',
data: {
action: 'pay/refund',
data: {
out_trade_no: this.form1.out_trade_no,
refund_fee: this.form1.refund_fee, // 退款金额,100=1元(单位分)不填则全额退款
},
},
success: (data) => {
uni.showToast({ title: data.msg, icon: 'none', mask: false });
},
});
},
// 退款查询
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 });
},
});
},
// 取消支付
cancelPay() {
this.vkPay.status = 0;
this.vkPay.codeUrl = '';
},
// 查询用户微信虚拟支付代币余额(微信虚拟支付的代币余额是通过调用微信API查询的)
async queryUserBalance() {
// #ifndef MP-WEIXIN
uni.showModal({
title: '提示',
content: '请在微信小程序中体验',
showCancel: false,
});
return;
// #endif
let openid = await this.$refs.vkPay.getOpenid();
this.callFunction({
title: '查询中...',
name: 'vk-pay',
data: {
action: 'pay/wxpayVirtual/queryUserBalance',
data: {
openid,
},
},
success: (data) => {
let { balance, presentBalance } = data;
let content = `我的余额:${balance}`;
if (presentBalance) {
content += `(含赠送余额:${presentBalance})`;
}
uni.showModal({ title: '提示', content, showCancel: false });
},
});
},
// 扣减用户代币,扣减用户代币需要保证用户的sessionKey在有效期内(uni-pay组件会自动获取当前微信用户的sessionKey)
async currencyPay() {
// #ifndef MP-WEIXIN
uni.showModal({
title: '提示',
content: '请在微信小程序中体验',
showCancel: false,
});
return;
// #endif
let openid = await this.$refs.vkPay.getOpenid();
let out_trade_no = 'test_' + Date.now();
this.currencyPayFormData.out_trade_no = out_trade_no;
this.callFunction({
title: '请求中...',
name: 'vk-pay',
data: {
action: 'pay/wxpayVirtual/currencyPay',
data: {
openid,
out_trade_no,
amount: this.currencyPayFormData.amount,
},
},
success: (data) => {
uni.showModal({
title: '提示',
content: `成功扣减余额:${data.amount},还剩余额:${data.balance}`,
showCancel: false,
});
},
});
},
//扣减代币回退(代币支付退款)
async cancelCurrencyPay() {
// #ifndef MP-WEIXIN
uni.showModal({
title: '提示',
content: '请在微信小程序中体验',
showCancel: false,
});
return;
// #endif
let openid = await this.$refs.vkPay.getOpenid();
this.callFunction({
title: '请求中...',
name: 'vk-pay',
data: {
action: 'pay/wxpayVirtual/cancelCurrencyPay',
data: {
openid,
out_trade_no: this.currencyPayFormData.out_trade_no,
amount: this.currencyPayFormData.amount,
},
},
success: (data) => {
uni.showModal({
title: '提示',
content: `余额回退成功`,
showCancel: false,
});
},
});
},
// 赠送代币
async presentCurrency() {
// #ifndef MP-WEIXIN
uni.showModal({
title: '提示',
content: '请在微信小程序中体验',
showCancel: false,
});
return;
// #endif
let openid = await this.$refs.vkPay.getOpenid();
let out_trade_no = 'test_' + Date.now();
this.callFunction({
title: '请求中...',
name: 'vk-pay',
data: {
action: 'pay/wxpayVirtual/presentCurrency',
data: {
openid,
out_trade_no,
amount: this.currencyPayFormData.amount,
},
},
success: (data) => {
uni.showModal({
title: '提示',
content: `赠送成功,当前余额:${data.balance}`,
showCancel: false,
});
},
});
},
// 监听道具选择
productIdChange(e) {
this.form1.wxpay_virtual.product_id = e.detail.value;
if (e.detail.value === 'test002') {
this.form1.wxpay_virtual.goods_price = 2; // 道具价格
} else {
this.form1.wxpay_virtual.goods_price = 1; // 道具价格
}
},
// 云函数调用简易封装,你也可以用你原本框架的云函数请求封装方法来调用云函数。
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);
},
});
},
},
// 计算属性
computed: {},
};
</script>
<style lang="scss" scoped>
/* 示例页面样式开始 */
page,
.app {
background-color: var(--page-bg, #f8f8f8);
}
.page-content {
padding: 1px 0;
max-width: 800px;
margin: 0 auto;
font-size: 16px;
.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;
&.button-green {
background-color: #4caf50;
}
}
.ios-tips {
padding: 5px 20px;
color: red;
font-size: 14px;
font-weight: bold;
}
}
.card {
margin: 10px;
background-color: var(--card-bg, #ffffff);
border-radius: 10px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
.title {
padding: 15px;
font-weight: bold;
font-size: 17px;
border-bottom: 1px solid var(--border-color, #f0f0f0);
}
.content {
padding: 15px;
.tips {
color: #8f8f8f;
font-size: 12px;
margin-bottom: 15px;
}
}
}
/* 示例页面样式结束 */
/* 二维码支付弹窗开始 */
.pay-qrcode-popup {
position: fixed;
z-index: 2;
width: 100vw;
top: 0;
bottom: 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: 250px;
margin: 40% auto 0 auto;
background-color: var(--card-bg, #ffffff);
border-radius: 5px;
padding: 20px;
box-sizing: content-box;
text-align: center;
.pay-qrcode-popup-info {
text-align: center;
padding: 10px;
.pay-qrcode-popup-info-fee {
color: red;
font-size: 30px;
font-weight: bold;
}
}
.pay-qrcode-popup-image {
width: 225px;
height: 225px;
}
}
}
/* 二维码支付弹窗结束 */
</style>
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
# uni-app x 蒸汽模式
将下面代码保存为 .uvue 页面,并在 pages.json 注册。代码来自 pages-x/wxpay-virtual/wxpay-virtual.uvue,包含代币充值、道具直购、查询、退款及代币操作;已内嵌页面样式,可直接复制。请替换道具 ID 等业务参数,在微信小程序中运行。
<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">代币充值、道具直购与代币管理</text>
<!-- #ifndef MP-WEIXIN -->
<view class="demo-card"><text class="demo-tips">支付和代币操作请在微信小程序中体验;查询及退款可使用已有订单号。</text></view>
<!-- #endif -->
<view class="demo-card">
<text class="demo-title">代币充值</text>
<text class="demo-status">{{ statusText }}</text>
<text class="demo-tips">iOS 微信需在虚拟支付配置中启用苹果 IAP,原示例的 iOS 订单实付金额要求至少 1 元。</text>
<text class="demo-label">充值代币数量</text>
<input class="demo-input" type="number" v-model="form1.wxpay_virtual.buy_quantity" placeholder="建议设置 1 人民币 = 100 代币" />
<text class="demo-label">订单号</text>
<input class="demo-input" v-model="form1.out_trade_no" placeholder="发起支付时自动生成" />
<button class="demo-button demo-green" @click="callPayment('short_series_coin')">发起代币充值</button>
<button v-if="form1.out_trade_no" class="demo-button demo-light" @click="afreshPayment('short_series_coin')">原订单发起支付</button>
<button class="demo-button demo-light" @click="queryPayment">支付结果查询</button>
<button class="demo-button demo-light" @click="queryUserBalance">查询我的代币余额</button>
</view>
<view class="demo-card">
<text class="demo-title">道具直购</text>
<radio-group class="demo-radio-group" @change="productIdChange">
<label class="demo-radio-label">
<radio value="test001" :checked="form1.wxpay_virtual.product_id === 'test001'" />
<text class="demo-radio-text">道具 1(1 分)</text>
</label>
<label class="demo-radio-label">
<radio value="test002" :checked="form1.wxpay_virtual.product_id === 'test002'" />
<text class="demo-radio-text">道具 2(2 分)</text>
</label>
</radio-group>
<text class="demo-tips">道具 ID 和价格沿用原示例,须与微信后台配置一致。</text>
<text class="demo-label">购买道具数量</text>
<input class="demo-input" type="number" v-model="form1.wxpay_virtual.buy_quantity" placeholder="购买数量" />
<text class="demo-label">订单号</text>
<input class="demo-input" v-model="form1.out_trade_no" placeholder="发起支付时自动生成" />
<button class="demo-button demo-green" @click="callPayment('short_series_goods')">发起道具购买</button>
<button v-if="form1.out_trade_no" class="demo-button demo-light" @click="afreshPayment('short_series_goods')">原订单发起支付</button>
<button class="demo-button demo-light" @click="queryPayment">支付结果查询</button>
</view>
<view class="demo-card">
<text class="demo-title">退款</text>
<text class="demo-label">订单号</text>
<input class="demo-input" v-model="form1.out_trade_no" placeholder="需要退款的订单号" />
<text class="demo-label">退款金额(分)</text>
<input class="demo-input" type="number" v-model="form1.refund_fee" placeholder="不填则全额退款" />
<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>
<text class="demo-label">代币数量</text>
<input class="demo-input" type="number" v-model="currencyPayFormData.amount" placeholder="代币数量" />
<text class="demo-label">代币扣减订单号</text>
<input class="demo-input" v-model="currencyPayFormData.out_trade_no" placeholder="扣减时自动生成,回退时使用此单号" />
<button class="demo-button demo-light" @click="queryUserBalance">查询我的代币余额</button>
<button class="demo-button demo-primary" @click="currencyPay">扣减代币</button>
<button v-if="currencyPayFormData.out_trade_no" class="demo-button demo-light" @click="cancelCurrencyPay">扣减代币回退</button>
<button class="demo-button demo-primary" @click="presentCurrency">赠送代币</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"
:query-payment-action="vkPay.queryPaymentAction"
:page-show="vkPay.pageShow"
:polling="vkPay.polling"
:auto-get-openid="vkPay.autoGetOpenid"
:await-notify="vkPay.awaitNotify"
:pay-order-info="vkPay.payOrderInfo"
/>
</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 currencyBusy = ref(false);
// 页面底部展示的接口返回结果,仅用于示例调试。
const resultText = ref('');
// 支付组件配置。查询接口使用默认路由即可。
const vkPay = reactive({
queryPaymentAction: {
name: 'vk-pay', // 云函数名称
action: 'pay/queryPayment', // 云函数中的查询接口
actionKey: 'action', // 云函数接口地址的识别 key
dataKey: 'data', // 云函数请求参数的识别 key
},
status: 0, // 0:等待支付;1:支付中;2:已支付(与数据库订单状态不同)
pageShow: true, // 当前页面是否显示,用于暂停或恢复查询
polling: true, // 二维码支付时自动查询支付结果
awaitNotify: true, // 等待云端业务异步通知执行完成后,再通知前端支付成功
payOrderInfo: false, // 支付成功后是否返回订单详情
autoGetOpenid: true, // 自动获取小程序 OpenID
});
// 微信虚拟支付的请求数据。
const form1 = reactive({
provider: 'wxpay-virtual', // 微信小程序虚拟支付
out_trade_no: '', // 商户订单号
subject: '测试订单标题', // 订单标题
type: 'wxpay-virtual-test', // 支付成功后执行的云端业务回调类型
openid: '', // 留空时由支付组件自动获取
refund_fee: '', // 退款金额(分),留空时全额退款
wxpay_virtual: {
mode: 'short_series_coin', // short_series_coin:代币充值;short_series_goods:道具直购
buy_quantity: 1, // 购买数量
product_id: 'test001', // 道具 ID,需要与微信后台一致
goods_price: 1, // 道具单价(分)
},
});
// 代币扣减、回退和赠送使用的表单数据。
const currencyPayFormData = reactive({
out_trade_no: '', // 扣减时生成的订单号,回退时使用此单号
amount: 1, // 代币数量
});
// 页面离开后忽略尚未完成的异步回调。
let alive = true;
// 页面生命周期
// 监听:页面加载时读取参数。
onLoad((options = {}) => {
if (options.out_trade_no) {
form1.out_trade_no = options.out_trade_no;
}
});
// 监听:页面显示时恢复支付结果查询。
onShow(() => {
vkPay.pageShow = true;
});
// 监听:页面隐藏时暂停支付结果查询。
onHide(() => {
vkPay.pageShow = false;
});
// 监听:页面离开后,不再显示旧请求的提示。
onUnload(() => {
alive = false;
vkPay.pageShow = false;
});
// 页面方法
// 选择虚拟支付模式:充值代币或购买道具。
function callPayment(mode) {
if (!alive || creating.value || requesting.value || currencyBusy.value) {
return;
}
form1.wxpay_virtual.mode = mode;
return createPayment();
}
// 发起支付:先准备订单参数,再调用支付组件。
async function createPayment(options = {}) {
// “支付中”仍可再次发起;创建、查单等请求尚未结束时,继续拦截重复操作。
if (!alive || !ensureWeixin() || !payRef.value || creating.value || requesting.value || currencyBusy.value) {
return;
}
if (!Number.isInteger(Number(form1.wxpay_virtual.buy_quantity)) || Number(form1.wxpay_virtual.buy_quantity) <= 0) {
showError({ msg: '购买数量须为大于 0 的整数' });
return;
}
// 示例为了方便在本地生成订单号;实际业务通常由云端创建订单。
form1.out_trade_no = options.out_trade_no || 'test_' + Date.now();
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,
out_trade_no: form1.out_trade_no,
subject: form1.subject,
type: form1.type,
openid: form1.openid,
wxpay_virtual: {
mode: form1.wxpay_virtual.mode,
buy_quantity: Number(form1.wxpay_virtual.buy_quantity),
product_id: form1.wxpay_virtual.product_id,
goods_price: form1.wxpay_virtual.goods_price,
},
},
// 支付订单创建成功:以云端返回的订单号为准。
create: (res) => {
if (!alive) {
return;
}
form1.out_trade_no = res.out_trade_no || form1.out_trade_no;
record(res);
},
// 支付成功:可在这里提示用户或跳转到业务页面。
success: (res) => {
if (!alive) {
return;
}
record(res);
uni.showToast({
title: '支付成功',
icon: 'success',
});
},
// 支付失败:展示失败原因,方便排查。
fail: paymentFail,
// 用户取消支付。
cancel: (res) => {
if (!alive) {
return;
}
record(res);
uni.showToast({
title: '用户取消支付',
icon: 'none',
});
},
});
} catch (error) {
showError(error);
} finally {
creating.value = false;
}
}
// 重新支付:继续使用当前订单号,不另外生成订单。
function afreshPayment(mode) {
if (!alive || creating.value || requesting.value || currencyBusy.value || !hasOrder()) {
return;
}
form1.wxpay_virtual.mode = mode;
return createPayment({ out_trade_no: form1.out_trade_no });
}
// 查询支付状态。实际业务应以云端订单和异步通知为准。
async function queryPayment() {
if (!alive || !payRef.value || creating.value || requesting.value || currencyBusy.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;
record(res);
uni.showToast({
title: res.msg || '支付成功',
icon: 'none',
});
},
fail: (res) => {
if (isCurrentOrder()) {
record(res);
}
},
});
} catch (error) {
if (isCurrentOrder()) {
showError(error);
}
} finally {
requesting.value = false;
}
}
// 申请退款。此为演示,实际业务应由云端校验退款权限和金额。
function refund() {
if (currencyBusy.value || !hasOrder()) {
return;
}
let data = { out_trade_no: form1.out_trade_no };
// 留空时全额退款,填写时按指定金额退款(单位分)。
if (String(form1.refund_fee).trim()) {
let amount = Number(form1.refund_fee);
if (!Number.isInteger(amount) || amount <= 0) {
showError({ msg: '退款金额须为大于 0 的整数,单位分' });
return;
}
data.refund_fee = amount;
}
return callFunction({
title: '退款中...',
name: 'vk-pay', // 云函数名称
data: {
action: 'pay/refund', // 云函数中的接口地址
data: data, // 接口需要的请求参数
},
// 请求成功后,展示结果或执行下一步操作
success: (res) => {
uni.showToast({
title: res.msg || '退款申请已提交',
icon: 'none',
});
},
});
}
// 查询当前订单的退款结果。
function queryRefund() {
if (currencyBusy.value || !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,
});
},
});
}
// 查询当前微信用户的代币余额。
async function queryUserBalance() {
if (!alive || creating.value) {
return;
}
// 代币接口只在微信小程序使用,先检查平台,再获取用户身份。
if (!ensureWeixin()) {
return;
}
if (!payRef.value || requesting.value || currencyBusy.value) {
return;
}
// 获取 OpenID 期间也要避免重复点击。
currencyBusy.value = true;
try {
let openid = await payRef.value.getOpenid();
if (!alive) {
return;
}
if (!openid) {
showError({ msg: '未获取到当前微信用户 OpenID' });
return;
}
await callFunction({
title: '请求中...',
name: 'vk-pay', // 云函数名称
data: {
action: 'pay/wxpayVirtual/queryUserBalance', // 云函数中的接口地址
data: {
openid,
},
},
success: (res) => {
let content = '我的余额:' + res.balance;
if (res.presentBalance) {
content += '(含赠送余额:' + res.presentBalance + ')';
}
uni.showToast({
title: content,
icon: 'none',
duration: 3000,
});
},
});
} catch (res) {
showError(res);
} finally {
currencyBusy.value = false;
}
}
// 扣减用户代币。支付组件会获取当前微信用户的 OpenID。
async function currencyPay() {
if (!alive || creating.value) {
return;
}
// 代币接口只在微信小程序使用,先检查平台,再获取用户身份。
if (!ensureWeixin()) {
return;
}
if (!payRef.value || requesting.value || currencyBusy.value) {
return;
}
let amount = Number(currencyPayFormData.amount);
if (!Number.isInteger(amount) || amount <= 0) {
showError({ msg: '代币数量须为大于 0 的整数' });
return;
}
// 获取 OpenID 期间也要避免重复点击。
currencyBusy.value = true;
try {
let openid = await payRef.value.getOpenid();
if (!alive) {
return;
}
if (!openid) {
showError({ msg: '未获取到当前微信用户 OpenID' });
return;
}
// 保存这次扣减的订单号,后续回退时使用同一个单号。
let out_trade_no = 'test_' + Date.now();
currencyPayFormData.out_trade_no = out_trade_no;
await callFunction({
title: '请求中...',
name: 'vk-pay', // 云函数名称
data: {
action: 'pay/wxpayVirtual/currencyPay', // 云函数中的接口地址
data: {
openid,
out_trade_no,
amount,
},
},
success: (res) => {
uni.showToast({
title: '成功扣减余额:' + res.amount + ',还剩余额:' + res.balance,
icon: 'none',
duration: 3000,
});
},
});
} catch (res) {
showError(res);
} finally {
currencyBusy.value = false;
}
}
// 回退一次代币扣减,订单号必须使用对应扣减订单的单号。
async function cancelCurrencyPay() {
if (!alive || creating.value) {
return;
}
// 代币接口只在微信小程序使用,先检查平台,再获取用户身份。
if (!ensureWeixin()) {
return;
}
if (!payRef.value || requesting.value || currencyBusy.value) {
return;
}
let amount = Number(currencyPayFormData.amount);
if (!Number.isInteger(amount) || amount <= 0) {
showError({ msg: '代币数量须为大于 0 的整数' });
return;
}
if (!currencyPayFormData.out_trade_no.trim()) {
showError({ msg: '请先输入代币扣减订单号' });
return;
}
// 获取 OpenID 期间也要避免重复点击。
currencyBusy.value = true;
try {
let openid = await payRef.value.getOpenid();
if (!alive) {
return;
}
if (!openid) {
showError({ msg: '未获取到当前微信用户 OpenID' });
return;
}
await callFunction({
title: '请求中...',
name: 'vk-pay', // 云函数名称
data: {
action: 'pay/wxpayVirtual/cancelCurrencyPay', // 云函数中的接口地址
data: {
openid,
out_trade_no: currencyPayFormData.out_trade_no,
amount,
},
},
success: (res) => {
uni.showToast({
title: '余额回退成功',
icon: 'none',
duration: 3000,
});
},
});
} catch (res) {
showError(res);
} finally {
currencyBusy.value = false;
}
}
// 赠送代币,使用独立的新订单号。
async function presentCurrency() {
if (!alive || creating.value) {
return;
}
// 代币接口只在微信小程序使用,先检查平台,再获取用户身份。
if (!ensureWeixin()) {
return;
}
if (!payRef.value || requesting.value || currencyBusy.value) {
return;
}
let amount = Number(currencyPayFormData.amount);
if (!Number.isInteger(amount) || amount <= 0) {
showError({ msg: '代币数量须为大于 0 的整数' });
return;
}
// 获取 OpenID 期间也要避免重复点击。
currencyBusy.value = true;
try {
let openid = await payRef.value.getOpenid();
if (!alive) {
return;
}
if (!openid) {
showError({ msg: '未获取到当前微信用户 OpenID' });
return;
}
// 赠送使用新的订单号,不覆盖前一次扣减的单号。
let out_trade_no = 'test_' + Date.now();
await callFunction({
title: '请求中...',
name: 'vk-pay', // 云函数名称
data: {
action: 'pay/wxpayVirtual/presentCurrency', // 云函数中的接口地址
data: {
openid,
out_trade_no,
amount,
},
},
success: (res) => {
uni.showToast({
title: '赠送成功,当前余额:' + res.balance,
icon: 'none',
duration: 3000,
});
},
});
} catch (res) {
showError(res);
} finally {
currencyBusy.value = false;
}
}
// 切换道具时,同时更新对应的道具价格。
function productIdChange(event) {
form1.wxpay_virtual.product_id = event.detail.value;
if (event.detail.value === 'test002') {
form1.wxpay_virtual.goods_price = 2; // 道具 2 的单价,单位分
} else {
form1.wxpay_virtual.goods_price = 1; // 道具 1 的单价,单位分
}
}
// 微信虚拟支付失败时,将常见错误码转换为说明。
function paymentFail(error = {}) {
const messages = {
'-5': '开通签约结果未知',
'-15002': '订单号重复使用,请换新单号重试',
'-15003': '系统错误',
'-15005': '支付配置错误',
'-15006': '支付配置错误',
'-15007': 'session_key 过期,用户需要重新登录',
'-15008': '二级商户进件未完成',
'-15009': '代币未发布',
'-15010': '道具 productId 未发布',
'-15012': '调用米大师失败导致关单,请换新单号重试',
'-15013': '道具价格错误',
'-15014': '道具或代币发布未生效,请稍后再试',
'-15017': '商户收款功能已被限制,请检查商户平台',
'-15018': '代币或者道具审核不通过',
'-15019': '微信商户受限,请检查商户平台',
'-15020': '操作过快,请稍后再试',
'-15021': '小程序被限频交易',
};
record(error);
showError({ msg: messages[String(error.errCode)] || error.errMsg || error.msg || error.message || '支付失败' });
}
// 支付和代币操作仅支持微信小程序,其他平台先提示再返回。
function ensureWeixin() {
// #ifdef MP-WEIXIN
return true;
// #endif
// #ifndef MP-WEIXIN
showError({ msg: '请在微信小程序中体验支付和代币操作' });
return false;
// #endif
}
// 显示接口或支付组件返回的错误信息。
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 '等待发起支付';
});
</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>
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# 开通
# 配置微信小程序消息推送
微信虚拟支付的异步回调依赖微信小程序消息推送,请按下图所示配置
其中 URL(服务器地址)填:https://vk-pay的云函数URL地址/vk-pay-notify/wxpay-virtual_mp-weixin
正确示例:https://env-00jxho66o66.dev-hz.cloudbasefunction.cn/http/vk-pay/vk-pay-notify/wxpay-virtual_mp-weixin

# API
# 代币充值、道具直购
充值代币 和 道具直购 涉及到前端 API,需要搭配 vk-uni-pay 组件使用,详情见上方示例代码
# queryUserBalance(查询用户代币余额)
接口名
queryUserBalance
入参说明
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| openid | String | 是 | - | 用户的 openid |
| userIp | String | 是 | - | 用户的 ip 地址 |
返回值说明
| 参数名 | 类型 | 说明 |
|---|---|---|
| balance | Number | 代币总余额,包括有价和赠送部分 |
| presentBalance | Number | 赠送账户的代币余额 |
| sumSave | Number | 累计有价货币充值数量 |
| sumPresent | Number | 累计赠送无价货币数量 |
| sumBalance | Number | 历史总增加的代币金额 |
| sumCost | Number | 历史总消耗代币金额 |
| firstSaveFlag | Boolean | 是否满足首充活动标记。0:不满足。1:满足 |
使用示例
// 引入 vk-uni-pay 公共模块
const vkPay = require('vk-uni-pay');
exports.main = async (event, context) => {
// 获取微信虚拟支付实例
const wxpayVirtualManager = await vkPay.getWxpayVirtualManager();
// 查询代币余额
let res = await wxpayVirtualManager.queryUserBalance({
openid: '', // 用户的openid
userIp: '', // 用户的ip地址
});
console.log('res: ', res);
return res;
};
2
3
4
5
6
7
8
9
10
11
12
13
14
# currencyPay(扣减代币)
扣减代币,一般用于代币支付
接口名
currencyPay
注意
此 API 需要用到用户的 sessionKey,如果用户长时间没有活跃过小程序,则无法请求扣减代币接口,会报用户 sessionKey 不存在或已过期,请重新登录的错误
微信小程序虚拟支付退款后,如果退款的是代币充值订单,则退款成功后原本用户充值的代币不会自动扣减,需要执行此 API 才能扣减,而用户长时间没有活跃过小程序,则无法请求扣减代币接口,因此需要注意退款时间,时间相隔太长可能会导致出现无法扣减代币的尴尬情况
入参说明
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| openid | String | 是 | - | 用户的 openid |
| userIp | String | 是 | - | 用户的 ip 地址 |
| amount | Number | 是 | - | 支付的代币数量 |
| outTradeNo | String | 是 | - | 订单号 |
| deviceType | Number | 是 | - | 平台类型 1-安卓 2-苹果 |
| payitem | String | 否 | - | 物品信息。记录到账户流水中。如:[{"productid":"物品 id", "unit_price": 单价, "quantity": 数量}],注意只能是 json 字符串格式 |
| remark | String | 否 | - | 备注 |
| sessionKey | String | 否 | - | 用户的 sessionKey,不传会尝试自动获取 |
返回值说明
| 参数名 | 类型 | 说明 |
|---|---|---|
| balance | Number | 总余额,包括有价和赠送部分 |
| usedPresentAmount | Number | 使用赠送部分的代币数量 |
| outTradeNo | String | 订单号原样返回 |
使用示例
// 引入 vk-uni-pay 公共模块
const vkPay = require('vk-uni-pay');
exports.main = async (event, context) => {
let openid = ''; // 用户的openid
let userIp = ''; // 用户的ip地址
let amount = 1; // 扣减代币数量
let out_trade_no = ''; // 商户订单号
// 获取用户的sessionKey
let sessionKey = await wxpayVirtualManager.getSessionKey(openid);
// 获取微信虚拟支付实例
const wxpayVirtualManager = await vkPay.getWxpayVirtualManager();
// 扣减代币余额
let res = await wxpayVirtualManager.currencyPay({
openid, // 用户的openid
userIp, // 用户的ip地址
amount: Number(amount), // 扣减代币数量
outTradeNo: out_trade_no, // 商户订单号
payitem, // 商品详情(需要转成json字符串)
remark, // 备注
deviceType: 1, // 平台类型1-安卓 仅支持传1
sessionKey, // 用户的sessionKey
});
console.log('res: ', res);
return res;
};
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
# cancelCurrencyPay(代币支付退款)
代币支付退款,currencyPay 接口的逆操作
接口名
cancelCurrencyPay
入参说明
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| openid | String | 是 | - | 用户的 openid |
| userIp | String | 是 | - | 用户的 ip 地址 |
| amount | Number | 是 | - | 退款金额 |
| outTradeNo | String | 是 | - | 订单号 |
| outRefundNo | String | 是 | - | 本次退款单的单号 |
| deviceType | Number | 是 | - | 平台类型 1-安卓 2-苹果 |
返回值说明
| 参数名 | 类型 | 说明 |
|---|---|---|
| outRefundNo | String | 退款订单号 |
使用示例
// 引入 vk-uni-pay 公共模块
const vkPay = require('vk-uni-pay');
exports.main = async (event, context) => {
let openid = ''; // 用户的openid
let userIp = ''; // 用户的ip地址
let out_trade_no = ''; // 需要回退的商户订单号
let amount = 1; // 需要回退的代币数量
let lastFourDigits = Date.now().toString().substr(-4);
// 获取微信虚拟支付实例
const wxpayVirtualManager = await vkPay.getWxpayVirtualManager();
// 回退扣减代币
let res = await wxpayVirtualManager.cancelCurrencyPay({
openid, // 用户的openid
userIp, // 用户的ip地址
amount: Number(amount), // 需要回退的代币数量
outTradeNo: out_trade_no, // 需要回退的商户订单号
outRefundNo: `${out_trade_no}-${lastFourDigits}`, // 商户退款单号
deviceType: 1, // 平台类型1-安卓 仅支持传1
});
console.log('res: ', res);
return res;
};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# presentCurrency(代币赠送)
接口名
presentCurrency
入参说明
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| openid | String | 是 | - | 用户的 openid |
| userIp | String | 是 | - | 用户的 ip 地址 |
| amount | Number | 是 | - | 退款金额 |
| outTradeNo | String | 是 | - | 订单号 |
| deviceType | Number | 是 | - | 平台类型 1-安卓 2-苹果 |
返回值说明
| 参数名 | 类型 | 说明 |
|---|---|---|
| balance | String | 赠送后用户的代币余额 |
| presentBalance | String | 用户收到的总赠送金额 |
| outTradeNo | String | 赠送单号 |
使用示例
// 引入 vk-uni-pay 公共模块
const vkPay = require('vk-uni-pay');
exports.main = async (event, context) => {
let openid = ''; // 用户的openid
let userIp = ''; // 用户的ip地址
let out_trade_no = ''; // 商户订单号
let amount = 1; // 赠送代币数量
// 获取微信虚拟支付实例
const wxpayVirtualManager = await vkPay.getWxpayVirtualManager();
// 赠送代币
let res = await wxpayVirtualManager.presentCurrency({
openid, // 用户的openid
userIp, // 用户的ip地址
amount: Number(amount), // 赠送代币数量
outTradeNo: out_trade_no, // 商户订单号
deviceType: 1, // 平台类型1-安卓 仅支持传1
});
console.log('res: ', res);
return res;
};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22