Commit 15bc2478 by zhengxiao

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

parent 79773fc5
......@@ -14,7 +14,8 @@ export type OrderStateCallBack = (params: BackInfo & { isPay: boolean, isLimit?:
export type PaymentParams = {
payChannels?: PayChannel[],
supportCombination?: boolean
supportCombination?: boolean,
isEnabledCombinationPay?: boolean,
}
export enum PayType {
......
......@@ -3,7 +3,7 @@ import md5 from 'blueimp-md5'
import qs from 'qs'
import {Utils} from "@/Utils/Utils";
import Decimal from 'decimal.js';
import {createRequest, defaultRequest, DefaultResponse} from "@/Request/Request";
import {defaultRequest, DefaultResponse} from "@/Request/Request";
import {
BACK_ORDER_ID,
BackInfo,
......@@ -18,97 +18,70 @@ import {
PayType,
ToPayParams,
ToPayReturns,
BalanceReturns,
WechatPayParams
} from "./Defined";
import {ACCESS_TOKEN, UID} from "@/Const";
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
export class Payment {
balance = 0;
limitPayChannels: PayChannel[] = [];
supportCombination: boolean = true
isEnabledCombinationPay: boolean = true; // 配置的是否开始组合支付
supportCombination: boolean = true; // 余额开关的改变是否支持组合支付
constructor(paymentParams?: PaymentParams) {
this.limitPayChannels = paymentParams?.payChannels ?? Object.keys(PayChannel).map(key => key) as PayChannel[];
if (typeof paymentParams?.supportCombination === 'boolean') {
this.supportCombination = typeof paymentParams?.supportCombination === 'boolean' && paymentParams.supportCombination
}
if (typeof paymentParams?.isEnabledCombinationPay === 'boolean') {
this.isEnabledCombinationPay = typeof paymentParams?.isEnabledCombinationPay === 'boolean' && paymentParams.isEnabledCombinationPay
}
}
//isHandleErr 是否要自定义处理异常
async getBalance(handleErr: (err: BalanceReturns) =>void): Promise<number|null> {
try {
const {data: res} = await requestForPhp.post(MY_BALANCE, {balance: 1})
if (res.data && res.data.balance) {
this.balance = Number(res.data.balance)
}
if(handleErr && res.msg !== 'success'){
handleErr && handleErr(res)
return null
setIsSupportCombination (value: boolean) {
this.supportCombination = value
}
getBalance() {
return new Promise<number|null>(async (resolve, reject) =>{
try {
const res = await requestForJava.get<Record<string, string>, DefaultResponse>(MY_BALANCE)
if (res.code === '200') {
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) {
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[] {
......@@ -124,12 +97,19 @@ export class Payment {
return !Utils.isWechat()
}
}).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) {
case PayType.BALANCE:
return {
...item,
label: `余额<span class="balance">(可用¥${this.balance})</span>`,
disabled: this.supportCombination ? (this.balance > 0 && this.balance < totalAmount) : true
disabled: caclCombination,
}
}
return item
......@@ -154,7 +134,6 @@ export class Payment {
return this.balance > 0 && this.balance < totalAmount && !Utils.isWechat()
}
}).map(item => {
const {payBalance} = this.computeAmountForCombination(totalAmount, this.balance)
switch (item.value) {
case PayType.BALANCE:
return {
......@@ -181,6 +160,7 @@ export class Payment {
}
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
if (balance === 0) {
payAmount = totalAmount
......@@ -196,6 +176,7 @@ export class Payment {
}
async toPay(params: ToPayParams): Promise<ToPayReturns> {
console.log("🚀 ~ file: Payment.ts:179 ~ Payment ~ toPay ~ params:", params)
const {totalAmount, payType, returnUrl, orderId, subOrderIds, redirectUrl} = params
let quitUrl = params.quitUrl
// validate start >>>
......@@ -382,7 +363,7 @@ export class Payment {
static createBackInfoUrl(url: string, backOrderId: number): string {
const [path, queryString] = url.split('?')
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)}`
}
......
......@@ -15,6 +15,7 @@ defaultRequest.interceptors.request.use((config) => {
}
})
defaultRequest.interceptors.response.use((response) => {
console.log("🚀 ~ file: Request.ts:20 ~ defaultRequest.interceptors.response.use ~ response:", response)
return response.data
}, err => Promise.reject(err))
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