Commit 8a3ffbd2 by 郑炬波

feat: 支付统一化

parent d0df7fdc
......@@ -10,6 +10,7 @@ const globalDatabase: any = {
* https://testnewm.ydl.com/consult/#/pages/jieyou/DownOrder?product_id=88220606058062&uid=130959612&accessToken=33441f9c4be74a357b1d416d4aa616eaMjIwNw&ffrom=m
*/
MOCK_GOODS: {
orderId: 94220829005145,
productId: 88220606058062,
productSpecs: [
{
......@@ -33,21 +34,21 @@ beforeAll(async () => {
* 测试账号:15706780002 ydl123456
* 请保证账户余额为0元
*/
Utils.setCookie(UID, '130959612')
Utils.setCookie(ACCESS_TOKEN, '33441f9c4be74a357b1d416d4aa616eaMjIwNw')
globalDatabase.payment = new Payment()
Utils.setCookie(UID, '130960056')
Utils.setCookie(ACCESS_TOKEN, 'eccf89e37fb96ef67c4c2cfbe53a05ceMjIwNw')
globalDatabase.payment = new Payment({supportCombination: true})
})
describe('测试无余额支付情况', () => {
test('test:获取账户余额', async () => {
const balance = await globalDatabase.payment.getBalance()
expect(balance).toBe(0)
expect(balance).toBe(1.99)
})
test('test: 测试余额支付', async () => {
const res = await globalDatabase.payment.toPay({
totalAmount: 1,
totalAmount: 3,
payType: PayType.BALANCE,
orderId: globalDatabase.MOCK_GOODS.orderId,
redirectUrl: window.encodeURIComponent('https://www.baidu.com'),
......@@ -80,7 +81,7 @@ describe('测试无余额使用微信支付', () => {
const {orderId, money} = await createOrder()
const res = await globalDatabase.payment.toPay({
totalAmount: money,
payType: PayType.WECHAT_BALANCE,
payType: PayType.WECHAT,
orderId,
redirectUrl: window.encodeURIComponent('https://www.baidu.com'),
returnUrl: 'https://www.baidu.com',
......
......@@ -2,6 +2,21 @@ import {describe, expect, test} from '@jest/globals'
import {BACK_ORDER_ID, BACK_PAY_ID, PayChannel, PayError, PayErrorMessage, Payment, PayType} from "@/Payment/Payment";
describe('测试: 创建实例', () => {
test('supportCombination', () => {
const payment1 = new Payment({
supportCombination: false
})
expect(payment1.supportCombination).toBe(false)
const payment2 = new Payment({
supportCombination: true
})
expect(payment2.supportCombination).toBe(true)
const payment3 = new Payment()
expect(payment3.supportCombination).toBe(true)
})
test('payChannels', () => {
const payment = new Payment({
payChannels: [PayChannel.WX_MWEB, PayChannel.WX_JSAPI]
......@@ -33,7 +48,7 @@ test('测试订单查询链接', () => {
expect(backUrl).toContain(window.location.origin)
})
test('测试价格计算', () => {
test('测试组合支付价格计算', () => {
const payment = new Payment()
const goodsPrice = 0.3
const balance = 0.1
......@@ -42,6 +57,15 @@ test('测试价格计算', () => {
expect(payBalance).toBe(0.1)
})
test('测试非组合支付价格计算', () => {
const payment = new Payment({supportCombination: false})
const goodsPrice = 0.3
payment.balance = 0.1
const {payAmount, payBalance} = payment.computeAmount(goodsPrice)
expect(payAmount).toBe(0.3)
expect(payBalance).toBe(0)
})
describe('测试支付入参校验', () => {
const othersParams = {
orderId: 111111111111,
......@@ -133,3 +157,8 @@ test('测试微信浏览器支付方式', () => {
expect(methods.length).toBe(1)
expect(methods[0].value).toBe(PayType.WECHAT)
})
test('测试时间接口', async () => {
const interval = await Payment.PayCheckIntervaL()
expect(interval).toBe(2000)
})
\ No newline at end of file
{
"name": "@ydl-packages/toolkit",
"version": "1.0.1-next.15",
"version": "1.0.2",
"description": "",
"main": "./dist/index.umd.js",
"scripts": {
......@@ -8,7 +8,9 @@
"test": "npx jest __tests__",
"doc": "npx typedoc",
"prepublishOnly": "npm run lib",
"commit": "git add . && npx cz-customizable"
"commit": "git add . && npx cz-customizable",
"async": "npm run lib && yalc push",
"watch": "nodemon --ignore dist/ --ignore node_modules/ --watch src/ -C -e ts --debug -x npm run async"
},
"keywords": [
"pay",
......
const BASE_URL_JAVA = process.env.NODE_ENV === 'production' ? 'https://api.ydl.com' : 'https://testapi.ydl.com'
const BASE_GATEWAY = process.env.NODE_ENV === 'production' ? 'https://app2.yidianling.com' : 'https://testapp2.yidianling.com'
let BASE_URL_JAVA = "";
let BASE_GATEWAY = "";
const isDev = typeof window !== 'undefined' ? window.location.hostname.indexOf("dev") > -1 : false;
const isTest = typeof window !== 'undefined' ? window.location.hostname.indexOf("test") > -1 : false;
if(isDev || isTest){
BASE_URL_JAVA = 'https://testapi.ydl.com';
BASE_GATEWAY = 'https://testapp2.yidianling.com'
}
else{
BASE_URL_JAVA = 'https://api.ydl.com';
BASE_GATEWAY = 'https://app2.yidianling.com'
}
/**
* doc: http://47.96.181.183:8806/api/swagger-ui.html#!/finance45v45245controller/doUnityPayUsingPOST
*/
......@@ -19,3 +26,5 @@ export const COMMIT_ORDER = `${BASE_URL_JAVA}/api/consult/consult/commit-order`
export const IS_PAY = `${BASE_URL_JAVA}/api/auth/Order/isPay`
export const MY_BALANCE = `${BASE_GATEWAY}/v3/uc/mybalance`
export const PAY_CHECK_INTERVAL = `${BASE_URL_JAVA}/api/pay/auth/pay/payCheckInterval`
\ No newline at end of file
......@@ -13,10 +13,11 @@ export type BackInfo = {
orderId: number;
payId: number
}
export type OrderStateCallBack = (params: BackInfo & { isPay: boolean }) => void
export type OrderStateCallBack = (params: BackInfo & { isPay: boolean, isLimit?: boolean }) => void
export type PaymentParams = {
payChannels?: PayChannel[]
payChannels?: PayChannel[],
supportCombination?: boolean
}
export enum PayType {
......@@ -94,11 +95,6 @@ export type ToPayParams = {
*/
redirectUrl?: string;
/**
* 用户在微信公众号或小程序的openId
*/
openId?: string;
appId?: string;
/**
* 支付记录id, 采用余额支付的时候如果前端有此值就带过来
*/
payId?: number;
......@@ -118,21 +114,19 @@ export enum PayErrorMessage {
WECHAT_REDIRECT_URL_MISSING= `请填写微信回调地址页面 'redirectUrl`,
WECHAT_REDIRECT_URL_ENCODE = 'redirectUrl需要encode',
WECHAT_PAY_CHANNEL_MISSING =`缺少渠道参数:'WX_MWEB','WX_JSAPI'`,
WECHAT_APPID_MISSING = '缺少微信APPID入参',
ALIPAY_QUIT_URL_MISSING = `缺少支付失败回调地址:'quitUrl'`,
ALIPAY_RETURN_URL_MISSING = `缺少支付成功回调地址:'returnUrl'`,
ALIPAY_PAY_CHANNEL_MISSING = `缺少持的渠道参数:'ALI_WAP'`,
WECHAT_JSSDK_PAY_ERROR = '微信JSSDK支付失败',
WECHAT_H5_PAY_BREAK = '微信h5支付中断',
ALIPAY_H5_PAY_BREAK = '支付宝支付中断',
ALIPAY_APPID_MISSING = '缺少微信APPID入参',
}
export type ToPayReturns = {
errorMessage?: PayErrorMessage
errorType: PayError
success: boolean
redirectUrl?: string
payUrl?: string
}
export interface DoUnifiedParams extends Omit<ToPayParams, 'totalAmount' | 'redirectUrl'> {
......
import {UNIT_PAY, IS_PAY, MY_BALANCE} from "./API";
import {UNIT_PAY, IS_PAY, MY_BALANCE, PAY_CHECK_INTERVAL} from "./API";
import md5 from 'blueimp-md5'
import qs from 'qs'
import {Utils} from "@/Utils/Utils";
......@@ -81,13 +81,16 @@ const requestForJava = defaultRequest
export class Payment {
balance = 0;
limitPayChannels: PayChannel[] = []
limitPayChannels: PayChannel[] = [];
supportCombination: boolean = true
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') {
this.supportCombination = typeof paymentParams?.supportCombination === 'boolean' && paymentParams.supportCombination
}
}
public async getBalance(): Promise<number> {
async getBalance(): Promise<number> {
try {
const {data: res} = await requestForPhp.post(MY_BALANCE, {balance: 1})
if (res.data && res.data.balance) {
......@@ -98,16 +101,43 @@ export class Payment {
return 0
}
}
getPayMethodList (totalAmount:number) {
return this.supportCombination ? this.getPayMethodListForCombination(totalAmount) : this.getPayMethodListForNotCombination(totalAmount)
}
public getPayMethodList(totalAmount: number): PayMethod[] {
private getPayMethodListForNotCombination(totalAmount: number): PayMethod[] {
return FULL_PAY_METHODS.filter(({value}) => {
switch (value) {
case PayType.BALANCE:
return this.balance > 0
case PayType.WECHAT:
return !Utils.isAlipay()
case PayType.ALIPAY:
return !Utils.isWechat()
case PayType.HUABEI:
return !Utils.isWechat()
}
}).map(item => {
switch (item.value) {
case PayType.BALANCE:
return {
...item,
label: `余额支付(¥${this.balance})`,
disabled: this.balance > 0 && this.balance < totalAmount
}
}
return item
})
}
private getPayMethodListForCombination(totalAmount: number): PayMethod[] {
return FULL_PAY_METHODS.filter(({value}) => {
switch (value) {
case PayType.BALANCE:
return this.balance > 0
case PayType.WECHAT:
return this.balance === 0
return this.balance === 0 && !Utils.isAlipay()
case PayType.WECHAT_BALANCE:
return this.balance > 0 && this.balance < totalAmount
return this.balance > 0 && this.balance < totalAmount && !Utils.isAlipay()
case PayType.ALIPAY:
return this.balance === 0 && !Utils.isWechat()
case PayType.ALIPAY_BALANCE:
......@@ -117,9 +147,8 @@ export class Payment {
case PayType.HUABEI_BALANCE:
return this.balance > 0 && this.balance < totalAmount && !Utils.isWechat()
}
return true
}).map(item => {
const {payBalance} = this.computeAmount(totalAmount, this.balance)
const {payBalance} = this.computeAmountForCombination(totalAmount, this.balance)
switch (item.value) {
case PayType.BALANCE:
return {
......@@ -132,13 +161,26 @@ export class Payment {
})
}
computeAmount(totalAmount: number, balance: number): { payAmount: number, payBalance: number } {
computeAmount(totalAmount: number, payType: PayType): { payAmount: number, payBalance: number } {
let payBalance = 0, payAmount = 0
if(payType == PayType.BALANCE){
payBalance = totalAmount;
payAmount = 0;
}
else{
payBalance = 0;
payAmount = totalAmount;
}
return {payAmount, payBalance}
}
computeAmountForCombination(totalAmount: number, balance: number = 0): { payAmount: number, payBalance: number } {
let payBalance = 0, payAmount = 0
if (balance === 0) {
payAmount = totalAmount
} else if (balance > 0 && balance < totalAmount) {
payBalance = balance
payAmount = subtract(bignumber(totalAmount), bignumber(balance)).toNumber()
payBalance = balance;
payAmount = totalAmount - balance;
} else {
payBalance = totalAmount
}
......@@ -146,7 +188,7 @@ export class Payment {
}
async toPay(params: ToPayParams): Promise<ToPayReturns> {
const {totalAmount, payType, returnUrl, orderId, redirectUrl, openId, appId, payId,} = params
const {totalAmount, payType, returnUrl, orderId, redirectUrl, payId} = params
let quitUrl = params.quitUrl
// validate start >>>
switch (payType) {
......@@ -164,18 +206,6 @@ export class Payment {
success: false,
errorType: PayError.VALIDATE
}
} else if (decodeURIComponent(redirectUrl) === redirectUrl) {
return {
errorMessage: PayErrorMessage.WECHAT_REDIRECT_URL_ENCODE,
success: false,
errorType: PayError.VALIDATE
}
} else if (!appId) {
return {
success: false,
errorMessage: PayErrorMessage.WECHAT_APPID_MISSING,
errorType: PayError.VALIDATE
}
}
} else {
return {
......@@ -204,12 +234,6 @@ export class Payment {
success: false,
errorType: PayError.VALIDATE
}
} else if (!appId) {
return {
success: false,
errorMessage: PayErrorMessage.ALIPAY_APPID_MISSING,
errorType: PayError.VALIDATE
}
}
} else {
return {
......@@ -226,15 +250,15 @@ export class Payment {
if (payChannel === PayChannel.WX_MWEB || payChannel === PayChannel.WX_JSAPI) {
quitUrl = redirectUrl
}
const { payAmount, payBalance } = this.supportCombination ? this.computeAmountForCombination(totalAmount, this.balance) : this.computeAmount(totalAmount, payType);
const doUnifiedParams: DoUnifiedParams = {
returnUrl,
quitUrl,
orderId,
payType,
openId,
appId,
payId,
...this.computeAmount(totalAmount, this.balance),
payAmount,
payBalance
}
if (payChannel !== null) {
doUnifiedParams.payChannel = payChannel
......@@ -244,7 +268,7 @@ export class Payment {
if (params.payType === PayType.BALANCE && res.data) {
return {success: res.data.result, errorType: PayError.BALANCE}
} else if (payChannel === PayChannel.WX_JSAPI) {
const isPaySucc = await this.wechatPayJSSDK(res.data)
const isPaySucc = await this.wechatPayJSSDK(res.data.content)
return {
errorMessage: isPaySucc ? undefined : PayErrorMessage.WECHAT_JSSDK_PAY_ERROR,
success: isPaySucc,
......@@ -252,14 +276,14 @@ export class Payment {
}
} else if (payChannel === PayChannel.WX_MWEB) {
return {
redirectUrl: res.data.content,
payUrl: res.data.content.link,
success: false,
errorType: PayError.WECHAT_H5_BREAK,
errorMessage: PayErrorMessage.WECHAT_H5_PAY_BREAK
}
} else if (payChannel === PayChannel.ALI_WAP) {
return {
redirectUrl: res.data.content,
payUrl: res.data.content.link,
success: false,
errorType: PayError.ALIPAY_H5_BREAK,
errorMessage: PayErrorMessage.ALIPAY_H5_PAY_BREAK
......@@ -285,7 +309,8 @@ export class Payment {
}
private wechatPayJSSDK(wechatPayParams: WechatPayParams): Promise<boolean> {
const {appId, timeStamp, nonceStr, signType, paySign, package: packageAlias} = wechatPayParams
const {appId, timeStamp, nonceStr, signType, paySign, package: packageAlias} = wechatPayParams;
return new Promise((resolve) => {
window.WeixinJSBridge.invoke(
"getBrandWCPayRequest",
......@@ -309,17 +334,19 @@ export class Payment {
})
}
static async loopValidateOrderState(count = 0, callBack: OrderStateCallBack): Promise<void> {
static async loopValidateOrderState(count = 0, callBack: OrderStateCallBack, pollTime = 3000): Promise<void> {
const [, queryString] = window.location.href.split('?')
const query = queryString ? qs.parse(queryString, {ignoreQueryPrefix: true}) : {}
const returnParams: BackInfo = {payId: Number(query[BACK_PAY_ID]), orderId: Number(query[BACK_ORDER_ID])}
let timer: any = null;
const checkLoop = () => {
if (--count > 0) {
setTimeout(() => {
this.loopValidateOrderState(count, callBack)
}, 1000)
timer = setTimeout(() => {
this.loopValidateOrderState(count, callBack, pollTime)
}, pollTime)
} else {
callBack({isPay: false, ...returnParams})
callBack({isPay: false, ...returnParams, isLimit:true})
timer && clearTimeout(timer)
}
}
if (query[BACK_PAY_ID]) {
......@@ -329,6 +356,7 @@ export class Payment {
})
if (res.code === '200' && res.data === true) {
callBack({isPay: true, ...returnParams})
timer && clearTimeout(timer)
} else {
checkLoop()
}
......@@ -351,4 +379,14 @@ export class Payment {
query[BACK_ORDER_ID] = backOrderId.toString()
return `${path}?${qs.stringify(query)}`
}
static async PayCheckIntervaL(): Promise<number> {
const res = await requestForJava.get<Record<string, string>, DefaultResponse>(PAY_CHECK_INTERVAL)
let interval = 3000;
if(res.code === '200'){
interval = res.data * 1000;
return interval
}
return interval;
}
}
\ No newline at end of file
......@@ -4,6 +4,9 @@ export class Utils {
static isWechat(): boolean {
return /MicroMessenger/i.test(window.navigator.userAgent)
}
static isAlipay(): boolean {
return /AlipayClient/i.test(window.navigator.userAgent)
}
static getCookie(key: string): string | null {
return Cookies.get(key) || null
}
......
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