Commit 15bc2478 by zhengxiao

feat: 修改余额接口,新增组合支付控制

parent 79773fc5
...@@ -14,7 +14,8 @@ export type OrderStateCallBack = (params: BackInfo & { isPay: boolean, isLimit?: ...@@ -14,7 +14,8 @@ export type OrderStateCallBack = (params: BackInfo & { isPay: boolean, isLimit?:
export type PaymentParams = { export type PaymentParams = {
payChannels?: PayChannel[], payChannels?: PayChannel[],
supportCombination?: boolean supportCombination?: boolean,
isEnabledCombinationPay?: boolean,
} }
export enum PayType { export enum PayType {
......
...@@ -3,7 +3,7 @@ import md5 from 'blueimp-md5' ...@@ -3,7 +3,7 @@ import md5 from 'blueimp-md5'
import qs from 'qs' import qs from 'qs'
import {Utils} from "@/Utils/Utils"; import {Utils} from "@/Utils/Utils";
import Decimal from 'decimal.js'; import Decimal from 'decimal.js';
import {createRequest, defaultRequest, DefaultResponse} from "@/Request/Request"; import {defaultRequest, DefaultResponse} from "@/Request/Request";
import { import {
BACK_ORDER_ID, BACK_ORDER_ID,
BackInfo, BackInfo,
...@@ -18,97 +18,70 @@ import { ...@@ -18,97 +18,70 @@ import {
PayType, PayType,
ToPayParams, ToPayParams,
ToPayReturns, ToPayReturns,
BalanceReturns,
WechatPayParams WechatPayParams
} from "./Defined"; } from "./Defined";
import {ACCESS_TOKEN, UID} from "@/Const";
export * from './Defined' export * from './Defined'
const SESSION_KEY = 'dc59cf294f37d237c1f06240568ffe21'
const createRequestForPhp = () => {
const comp = (a: string, b: string): number => {
if (a > b) {
return -1;
} else if (a == b) return 0;
else return 1;
}
const genSign = (data: Record<string, any>): string => {
let keyArr: string[] = [];
for (let i in data) {
keyArr.push(i);
}
keyArr.sort(comp);
const tempArr: string[] = [];
for (let i in keyArr) {
tempArr.push(keyArr[i] + "=" + data[keyArr[i]]);
}
return md5(tempArr.join("&") + SESSION_KEY);
}
const request = createRequest()
request.interceptors.request.use((config) => {
const requestData = {
...config.data,
ts: parseInt((Date.now() / 1000).toString()).toString(),
[UID]: Utils.getQueryString(UID) || Utils.getCookie(UID),
[ACCESS_TOKEN]: Utils.getQueryString(ACCESS_TOKEN) || Utils.getCookie(ACCESS_TOKEN)
}
return {
...config,
transformRequest: [function (data: any, headers: any) {
return qs.stringify(requestData)
}],
headers: {
'content-type': 'application/x-www-form-urlencoded',
Authorization: `Ydl ${genSign(requestData)}`,
[UID]: Utils.getQueryString(UID) || Utils.getCookie(UID),
[ACCESS_TOKEN]: Utils.getQueryString(ACCESS_TOKEN) || Utils.getCookie(ACCESS_TOKEN)
}
}
})
return request
}
const requestForPhp = createRequestForPhp()
const requestForJava = defaultRequest const requestForJava = defaultRequest
export class Payment { export class Payment {
balance = 0; balance = 0;
limitPayChannels: PayChannel[] = []; limitPayChannels: PayChannel[] = [];
supportCombination: boolean = true isEnabledCombinationPay: boolean = true; // 配置的是否开始组合支付
supportCombination: boolean = true; // 余额开关的改变是否支持组合支付
constructor(paymentParams?: PaymentParams) { constructor(paymentParams?: PaymentParams) {
this.limitPayChannels = paymentParams?.payChannels ?? Object.keys(PayChannel).map(key => key) as PayChannel[]; this.limitPayChannels = paymentParams?.payChannels ?? Object.keys(PayChannel).map(key => key) as PayChannel[];
if (typeof paymentParams?.supportCombination === 'boolean') { if (typeof paymentParams?.supportCombination === 'boolean') {
this.supportCombination = typeof paymentParams?.supportCombination === 'boolean' && paymentParams.supportCombination this.supportCombination = typeof paymentParams?.supportCombination === 'boolean' && paymentParams.supportCombination
} }
if (typeof paymentParams?.isEnabledCombinationPay === 'boolean') {
this.isEnabledCombinationPay = typeof paymentParams?.isEnabledCombinationPay === 'boolean' && paymentParams.isEnabledCombinationPay
}
} }
//isHandleErr 是否要自定义处理异常 setIsSupportCombination (value: boolean) {
async getBalance(handleErr: (err: BalanceReturns) =>void): Promise<number|null> { this.supportCombination = value
try { }
const {data: res} = await requestForPhp.post(MY_BALANCE, {balance: 1})
if (res.data && res.data.balance) { getBalance() {
this.balance = Number(res.data.balance) return new Promise<number|null>(async (resolve, reject) =>{
} try {
if(handleErr && res.msg !== 'success'){ const res = await requestForJava.get<Record<string, string>, DefaultResponse>(MY_BALANCE)
handleErr && handleErr(res) if (res.code === '200') {
return null this.balance = Number(res.data)
resolve(this.balance)
} else {
reject(res)
}
} catch (error) {
reject(error)
} }
return this.balance })
} catch (err) { }
handleErr && handleErr({success: false})
return !!handleErr ? null : 0 // 获取被禁止的支付方式列表
} getDisabledPayMethodList():Promise<number[]> {
return new Promise<number[]>((resolve, reject) => {
resolve([])
})
} }
getPayMethodList (totalAmount:number) { getPayMethodList (totalAmount:number) {
return this.supportCombination ? this.getPayMethodListForCombination(totalAmount) : this.getPayMethodListForNotCombination(totalAmount) // 计算支付方式列表
const List = this.supportCombination ? this.getPayMethodListForCombination(totalAmount) : this.getPayMethodListForNotCombination(totalAmount)
return new Promise(async (resolve, reject) => {
try {
const res = await this.getDisabledPayMethodList()
// 从list中过滤出被禁止的支付方式
const filterList = List.filter(({value}) => !res.includes(value))
resolve(filterList)
} catch (error) {
reject(error)
}
})
} }
private getPayMethodListForNotCombination(totalAmount: number): PayMethod[] { private getPayMethodListForNotCombination(totalAmount: number): PayMethod[] {
...@@ -124,12 +97,19 @@ export class Payment { ...@@ -124,12 +97,19 @@ export class Payment {
return !Utils.isWechat() return !Utils.isWechat()
} }
}).map(item => { }).map(item => {
let caclCombination = false
if (this.isEnabledCombinationPay) {
caclCombination = this.supportCombination ? (this.balance > 0 && this.balance < totalAmount) : true
} else {
caclCombination = this.balance < totalAmount
}
switch (item.value) { switch (item.value) {
case PayType.BALANCE: case PayType.BALANCE:
return { return {
...item, ...item,
label: `余额<span class="balance">(可用¥${this.balance})</span>`, label: `余额<span class="balance">(可用¥${this.balance})</span>`,
disabled: this.supportCombination ? (this.balance > 0 && this.balance < totalAmount) : true disabled: caclCombination,
} }
} }
return item return item
...@@ -154,7 +134,6 @@ export class Payment { ...@@ -154,7 +134,6 @@ export class Payment {
return this.balance > 0 && this.balance < totalAmount && !Utils.isWechat() return this.balance > 0 && this.balance < totalAmount && !Utils.isWechat()
} }
}).map(item => { }).map(item => {
const {payBalance} = this.computeAmountForCombination(totalAmount, this.balance)
switch (item.value) { switch (item.value) {
case PayType.BALANCE: case PayType.BALANCE:
return { return {
...@@ -181,6 +160,7 @@ export class Payment { ...@@ -181,6 +160,7 @@ export class Payment {
} }
computeAmountForCombination(totalAmount: number, balance: number = 0): { payAmount: number, payBalance: number } { computeAmountForCombination(totalAmount: number, balance: number = 0): { payAmount: number, payBalance: number } {
console.log("🚀 ~ file: Payment.ts:171 ~ Payment ~ computeAmountForCombination ~ balance:", balance)
let payBalance = 0, payAmount = 0 let payBalance = 0, payAmount = 0
if (balance === 0) { if (balance === 0) {
payAmount = totalAmount payAmount = totalAmount
...@@ -196,6 +176,7 @@ export class Payment { ...@@ -196,6 +176,7 @@ export class Payment {
} }
async toPay(params: ToPayParams): Promise<ToPayReturns> { async toPay(params: ToPayParams): Promise<ToPayReturns> {
console.log("🚀 ~ file: Payment.ts:179 ~ Payment ~ toPay ~ params:", params)
const {totalAmount, payType, returnUrl, orderId, subOrderIds, redirectUrl} = params const {totalAmount, payType, returnUrl, orderId, subOrderIds, redirectUrl} = params
let quitUrl = params.quitUrl let quitUrl = params.quitUrl
// validate start >>> // validate start >>>
...@@ -382,7 +363,7 @@ export class Payment { ...@@ -382,7 +363,7 @@ export class Payment {
static createBackInfoUrl(url: string, backOrderId: number): string { static createBackInfoUrl(url: string, backOrderId: number): string {
const [path, queryString] = url.split('?') const [path, queryString] = url.split('?')
const query = queryString ? qs.parse(queryString, {ignoreQueryPrefix: true}) : {} const query = queryString ? qs.parse(queryString, {ignoreQueryPrefix: true}) : {}
query[BACK_ORDER_ID] = backOrderId.toString() query[BACK_ORDER_ID] = backOrderId?backOrderId.toString(): ''
return `${path}?${qs.stringify(query)}` return `${path}?${qs.stringify(query)}`
} }
......
...@@ -15,6 +15,7 @@ defaultRequest.interceptors.request.use((config) => { ...@@ -15,6 +15,7 @@ defaultRequest.interceptors.request.use((config) => {
} }
}) })
defaultRequest.interceptors.response.use((response) => { defaultRequest.interceptors.response.use((response) => {
console.log("🚀 ~ file: Request.ts:20 ~ defaultRequest.interceptors.response.use ~ response:", response)
return response.data return response.data
}, err => Promise.reject(err)) }, err => Promise.reject(err))
export {defaultRequest} export {defaultRequest}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment