Files
kangyuan-mobile/sheep/platform/pay.js
T
2026-05-26 15:52:30 +08:00

561 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sheep from '@/sheep';
// #ifdef H5
import $wxsdk from '@/sheep/libs/sdk-h5-weixin';
// #endif
import { getRootUrl } from '@/sheep/helper';
import PayOrderApi from '@/sheep/api/pay/order';
import { baseUrl } from '@/sheep/config';
/**
* 支付
*
* @param {String} payment = ['wechat','alipay_app','wallet','mock'] - 支付方式
* @param {String} orderType = ['goods','recharge','groupon'] - 订单类型
* @param {String} id - 订单号
*/
export default class SheepPay {
constructor(payment, orderType, id) {
this.payment = payment;
this.id = id;
this.orderType = orderType;
this.payAction();
}
payAction() {
const payAction = {
WechatOfficialAccount: {
wechat: () => {
this.wechatOfficialAccountPay();
},
alipay_app: () => {
this.redirectPay(); // 现在公众号可以直接跳转支付宝页面
},
wallet: () => {
this.walletPay();
},
mock: () => {
this.mockPay();
},
},
WechatMiniProgram: {
wechat: () => {
this.wechatMiniProgramPay();
},
hf_wx_app: () => {
this.hfWxPay();
},
alipay_app: () => {
this.copyPayLink();
},
wallet: () => {
this.walletPay();
},
mock: () => {
this.mockPay();
},
},
App: {
wechat: () => {
this.wechatAppPay();
},
alipay_app: () => {
this.alipay();
},
wallet: () => {
this.walletPay();
},
mock: () => {
this.mockPay();
},
hf_wx_app: () => {
this.hfWxPay();
},
hf_alipay_app: () => {
this.hfAlipayPay();
},
},
H5: {
wechat: () => {
this.wechatWapPay();
},
alipay_app: () => {
this.redirectPay();
},
wallet: () => {
this.walletPay();
},
mock: () => {
this.mockPay();
},
hf_wx_app: () => {
this.hfWxPay();
},
hf_alipay_app: () => {
this.hfAlipayPay();
},
},
};
return payAction[sheep.$platform.name][this.payment]();
}
// 预支付
prepay(channel) {
// console.log('预支付:' + channel);
return new Promise(async (resolve, reject) => {
let data = {
id: this.id,
channelCode: channel,
channelExtras: {},
};
console.log('发起预支付 API 调用前:' + JSON.stringify(data));
if (['wx_pub', 'wx_lite', 'hf_wx_app'].includes(channel)) {
// console.log(1111111111111111111111);
const openid = await sheep.$platform.useProvider('wechat').getOpenid();
// console.log('获取到的 openid:' + openid);
if (!openid) {
this.bindWeixin();
return;
}
data.channelExtras.openid = openid;
}
console.log('发起预支付 API 调用' + JSON.stringify(data));
// 发起预支付 API 调用
PayOrderApi.submitOrder(data).then((res) => {
// 成功时
res.code === 0 && resolve(res);
// 失败时
if (res.code !== 0 && res.msg.indexOf('无效的openid') >= 0) {
// 特殊逻辑:微信公众号、小程序支付时,必须传入 openid 不正确的情况
if (
res.msg.indexOf('无效的openid') >= 0 || // 获取的 openid 不正确时,或者随便输入了个 openid
res.msg.indexOf('下单账号与支付账号不一致') >= 0
) {
// https://developers.weixin.qq.com/community/develop/doc/00008c53c347804beec82aed051c00
this.bindWeixin();
}
}
});
});
}
// #ifdef H5
// 微信公众号 JSSDK 支付
async wechatOfficialAccountPay() {
let { code, data } = await this.prepay('wx_pub');
if (code !== 0) {
return;
}
const payConfig = JSON.parse(data.displayContent);
$wxsdk.wxpay(payConfig, {
success: () => {
this.payResult('success');
},
cancel: () => {
sheep.$helper.toast('支付已手动取消');
},
fail: (error) => {
if (error.errMsg.indexOf('chooseWXPay:没有此SDK或暂不支持此SDK模拟') >= 0) {
sheep.$helper.toast(
'发起微信支付失败,原因:可能是微信开发者工具不支持,建议使用微信打开网页后支付',
);
return;
}
this.payResult('fail');
},
});
}
// 浏览器微信 H5 支付 TODO 芋艿:待接入(注意:H5 支付是给普通浏览器,不是微信公众号的支付,绝大多数人用不到,可以忽略)
async wechatWapPay() {
const { error, data } = await this.prepay();
if (error === 0) {
const redirect_url = `${getRootUrl()}pages/pay/result?id=${this.id}&payment=${this.payment
}&orderType=${this.orderType}`;
location.href = `${data.pay_data.h5_url}&redirect_url=${encodeURIComponent(redirect_url)}`;
}
}
// 支付链接(支付宝 wap 支付)
async redirectPay() {
let { code, data } = await this.prepay('alipay_wap');
if (code !== 0) {
return;
}
location.href = data.displayContent;
}
// #endif
// 微信小程序支付
async wechatMiniProgramPay() {
// let that = this;
let { code, data } = await this.prepay('wx_lite');
if (code !== 0) {
return;
}
// 调用微信小程序支付
const payConfig = JSON.parse(data.displayContent);
uni.requestPayment({
provider: 'wxpay',
timeStamp: payConfig.timeStamp,
nonceStr: payConfig.nonceStr,
package: payConfig.packageValue,
signType: payConfig.signType,
paySign: payConfig.paySign,
success: (res) => {
this.payResult('success');
},
fail: (err) => {
if (err.errMsg === 'requestPayment:fail cancel') {
sheep.$helper.toast('支付已手动取消');
} else {
this.payResult('fail');
}
},
});
}
// 余额支付
async walletPay() {
const { code } = await this.prepay('wallet');
code === 0 && this.payResult('success');
}
// 模拟支付
async mockPay() {
// console.log('模拟支付')
// return
const { code } = await this.prepay('mock');
code === 0 && this.payResult('success');
}
// 支付宝复制链接支付(通过支付宝 wap 支付实现)
async copyPayLink() {
let { code, data } = await this.prepay('alipay_wap');
if (code !== 0) {
return;
}
// 引入 showModal 点击确认:复制链接;
uni.showModal({
title: '支付宝支付',
content: '复制链接到外部浏览器',
confirmText: '复制链接',
confirmColor: '#FA7E31',
success: (res) => {
if (res.confirm) {
sheep.$helper.copyText(data.displayContent);
}
},
});
}
// 支付宝支付(App)
async alipay() {
let that = this;
const { code, data } = await this.prepay('alipay_app');
if (code !== 0) {
return;
}
console.log(data.displayContent)
uni.requestPayment({
provider: 'alipay',
orderInfo: data.displayContent, // 直接使用返回的支付参数
success: (res) => {
that.payResult('success');
},
fail: (err) => {
if (err.errMsg === 'requestPayment:fail [paymentAlipay:62001]user cancel') {
sheep.$helper.toast('支付已手动取消');
} else {
that.payResult('fail');
}
},
});
}
// 微信支付(App)
async wechatAppPay() {
let that = this;
// 获取预支付信息
let { code, data } = await this.prepay('wx_app');
if (code !== 0) {
sheep.$helper.toast('获取支付信息失败');
return;
}
// 解析支付参数
let payConfig = JSON.parse(data.displayContent);
if (typeof payConfig.appId === 'undefined') {
payConfig.appId = payConfig.appid;
}
if (typeof payConfig.nonceStr === 'undefined') {
payConfig.nonceStr = payConfig.noncestr;
}
if (typeof payConfig.timeStamp === 'undefined') {
payConfig.timeStamp = payConfig.timestamp;
}
// 调用微信支付
uni.requestPayment({
provider: 'wxpay',
timeStamp: payConfig.timeStamp,
nonceStr: payConfig.nonceStr,
package: payConfig.packageValue,
signType: payConfig.signType,
paySign: payConfig.paySign,
success: (res) => {
that.payResult('success');
},
fail: (err) => {
if (err.errMsg === 'requestPayment:fail cancel') {
sheep.$helper.toast('支付已手动取消');
} else {
sheep.$helper.toast('支付失败:' + err.errMsg);
that.payResult('fail');
}
},
});
}
// 支付结果跳转,success:成功,fail:失败
payResult(resultType) {
goPayResult(this.id, this.orderType, resultType);
}
// 引导绑定微信
bindWeixin() {
goBindWeixin();
}
// 汇付微信支付
hfWxPay() {
let that = this;
console.log('token:' + uni.getStorageSync('token'));
console.log('orderId:' + that.id);
// #ifdef APP-PLUS
plus.share.getServices(services => {
const weixinService = services.find(service => service.id === 'weixin');
if (weixinService) {
weixinService.launchMiniProgram({
// appid: 'wx23b0c321b5d74d63',
id: 'gh_c69ddc78e1cd', // 替换为实际小程序原始ID
type: 0, // 类型:// 版本:0-正式版 1-测试版 2-体验版
path: 'pages/pkgD/pay?token=' + uni.getStorageSync('token') + '&orderId=' + that.id, // 可选跳转路径
});
} else {
uni.showToast({ title: '未检测到微信客户端', icon: 'none' });
}
}, err => {
console.error('获取服务失败:', err);
});
// #endif
}
//检测code是否过期
verify_wechat_code(code) {
let appid = 'wx23b0c321b5d74d63'
let secret = 'aff28ef70e00c12245e77a9804dfd8a2'
let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
return uni.request({
url: url,
method: 'GET',
success(res) {
console.log('verify_wechat_code 成功:' + JSON.stringify(res.data));
},
fail(err) {
console.log('verify_wechat_code 失败:' + JSON.stringify(err));
},
})
}
//检测是否开通支付
is_open_wxPay(pay_info) {
uni.requestPayment({
provider: 'wxpay',
orderInfo: pay_info,
success(res) {
console.log('开通支付:', res);
},
fail(err) {
console.error('开通支付失败:', err);
}
});
}
// 汇付支付宝支付
async hfAlipayPay() {
let { code, data } = await this.prepay('hf_alipay_app');
console.log(data)
if (code !== 0) return
if (data.displayMode.toLowerCase() == sheep.$platform.name.toLowerCase()) {
//拼接支付宝内部功能,直接打开支付页面
let url = `alipays://platformapi/startapp?saId=10000007&qrcode=${encodeURI(data.displayContent)}?_s=web-other`;
console.log(url)
let platform = uni.getSystemInfoSync().platform;//获取平台判断
if (platform == 'android') {
plus.runtime.openURL(url)
} else if (platform == 'ios') {
plus.runtime.launchApplication({
action: url
})
}
} else {
sheep.$helper.toast(`请使用${data.displayMode}进行支付`);
}
}
}
export function getPayMethods(channels) {
const payMethods1 = [
{
icon: '/static/pay/wechat.svg',
title: '微信支付',
value: 'wechat',
disabled: false,
},
{
icon: '/static/pay/alipay.svg',
title: '支付宝支付',
value: 'alipay_app',
disabled: false,
},
{
icon: '/static/pay/wallet.svg',
title: '余额支付',
value: 'wallet',
disabled: false,
},
{
icon: '/static/pay/apple.svg',
title: 'Apple Pay',
value: 'apple',
disabled: false,
},
{
icon: '/static/pay/wallet.svg',
title: '模拟支付',
value: 'mock',
disabled: false,
},
{
icon: '/static/pay/wechat.svg',
title: 'H微信支付',
value: 'hf_wx_app',
disabled: false,
},
{
icon: '/static/pay/alipay.svg',
title: 'H支付宝支付',
value: "hf_alipay_app",
disabled: false,
},
];
let payMethods = [];
// 1. 处理【微信支付】
let wechatMethod = null;
// 2. 处理【支付宝支付】
let alipayMethod = null;
// 3. 处理【余额支付】
let walletMethod = null;
// 4. 处理【苹果支付】TODO 芋艿:未来接入
// 5. 处理【模拟支付】
let mockMethod = null;
// 6. 处理【汇付微信支付】
let hfWxMethod = null;
// 7. 处理【汇付支付宝支付】
let hfAlipayMethod = null;
payMethods1.forEach((e) => {
if (channels.indexOf(e.value) !== -1) {
payMethods.push(e);
if (e.value == 'wechat') {
wechatMethod = e;
} else if (e.value == 'alipay_app') {
alipayMethod = e;
} else if (e.value == 'wallet') {
walletMethod = e;
} else if (e.value == 'mock') {
mockMethod = e;
} else if (e.value == 'hf_wx_app') {
hfWxMethod = e;
} else if (e.value == 'hf_alipay_app') {
hfAlipayMethod = e;
}
}
});
const platform = sheep.$platform.name;
if (
(platform === 'WechatOfficialAccount' && channels.includes('wx_pub')) ||
(platform === 'WechatMiniProgram' && channels.includes('wx_lite')) ||
(platform === 'App' && channels.includes('wx_app'))
) {
wechatMethod.disabled = false;
}
if (
(platform === 'H5' && channels.includes('alipay_wap')) ||
(platform === 'WechatOfficialAccount' && channels.includes('alipay_wap')) ||
(platform === 'WechatMiniProgram' && channels.includes('alipay_wap')) ||
(platform === 'App' && channels.includes('alipay_app'))
) {
alipayMethod.disabled = false;
}
if (channels.includes('wallet')) {
walletMethod.disabled = false;
}
if (channels.includes('mock')) {
mockMethod.disabled = false;
}
if (platform === 'App' && channels.includes('hf_wx_app') && hfWxMethod) {
hfWxMethod.disabled = false;
}
if (platform === 'App' && channels.includes('hf_alipay_app') && hfAlipayMethod) {
hfAlipayMethod.disabled = false;
}
return payMethods;
}
// 支付结果跳转,success:成功,fail:失败
export function goPayResult(id, orderType, resultType) {
// sheep.$router.redirect('/pages/pay/result', {
// id,
// orderType,
// payState: resultType,
// });
uni.redirectTo({
url: '/pages/pay/result?id=' + id + '&orderType=' + orderType + '&payState=' + resultType,
})
}
export function goBindWeixin() {
uni.showModal({
title: '微信支付',
content: '请先绑定微信再使用微信支付',
confirmColor: '#FA7E31',
success: function (res) {
if (res.confirm) {
sheep.$platform.useProvider('wechat').bind();
}
},
});
}
// 获取微信支付渠道码
export function getWeixinPayChannelCode() {
const platform = sheep.$platform.name;
switch (platform) {
case 'WechatOfficialAccount':
return 'wx_pub';
case 'WechatMiniProgram':
return 'wx_lite';
case 'App':
return 'wx_app';
case 'H5':
return 'wx_wap';
default:
return '';
}
}