Skip to content

Commit

Permalink
Auto Format
Browse files Browse the repository at this point in the history
  • Loading branch information
adaex committed May 26, 2021
1 parent 4176a9a commit 96d308d
Show file tree
Hide file tree
Showing 8 changed files with 42 additions and 50 deletions.
2 changes: 0 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/restrict-plus-operands": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/strict-boolean-expressions": "off"
}
}
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
[![npm downloads](https://img.shields.io/npm/dm/coa-wx-pay-isv.svg?style=flat-square)](http://npm-stat.com/charts.html?package=coa-wx-pay-isv)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/coajs/coa-wx-pay-isv/pulls)

轻量的微信支付SDK服务商版 for Node.js
轻量的微信支付 SDK 服务商版 for Node.js

## 特点

根据日常实际项目使用情况:

- 覆盖了绝大多数使用场景
- 统一了异步表现形式,全部返回 Promise
- 内置类型引用,无需额外查看文档,开箱即用,IDE友好
- 内置类型引用,无需额外查看文档,开箱即用,IDE 友好

## 快速开始

Expand All @@ -35,7 +35,7 @@ const config = {
key: '1125XXXXXXXXXXXXXXXXXXX6E20DE9',
pfx: Buffer.from('XXXXXXX'),
notifyPay: 'https://example.com/api/notify/pay',
notifyRefund: 'https://example.com/api/notify/refund'
notifyRefund: 'https://example.com/api/notify/refund',
}

// 创建BIN实例
Expand Down Expand Up @@ -65,7 +65,7 @@ await service.downloadBill({ date: '20210331' })

### 错误记录

可以使用自定义Bin的方式记录错误信息
可以使用自定义 Bin 的方式记录错误信息

```typescript
import { CoaWxPayIsvBin, CoaWxPayIsvService } from 'coa-wx-pay-isv'
Expand All @@ -77,12 +77,12 @@ const config = {
key: '1125XXXXXXXXXXXXXXXXXXX6E20DE9',
pfx: Buffer.from('XXXXXXX'),
notifyPay: 'https://example.com/api/notify/pay',
notifyRefund: 'https://example.com/api/notify/refund'
notifyRefund: 'https://example.com/api/notify/refund',
}

// 创建自定义Bin类
class MyCoaWxPayIsvBin extends CoaWxPayIsvBin {
protected onRequestError (error: Error, response: Axios.AxiosResponse) {
protected onRequestError(error: Error, response: Axios.AxiosResponse) {
console.log('error:', error.toString())
console.log('data:', response.data)
}
Expand All @@ -96,4 +96,4 @@ const service = new CoaWxPayIsvService(bin)

// 错误调用下载日对账单
await service.downloadBill({ date: '' }) // 此时会触发 onRequestError()
```
```
1 change: 0 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export { CoaWxPayIsvBin } from './lib/CoaWxPayIsvBin'
export { CoaWxPayIsvService } from './service/CoaWxPayIsvService'
export { CoaWxPayIsv } from './typings'

24 changes: 11 additions & 13 deletions src/lib/CoaWxPayIsvBin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,41 +12,40 @@ interface Dic<T = any> {
}

export class CoaWxPayIsvBin {

public readonly config: CoaWxPayIsv.Config
public readonly httpsAgent: Agent

constructor (config: CoaWxPayIsv.Config) {
constructor(config: CoaWxPayIsv.Config) {
this.config = config
this.httpsAgent = new Agent({ pfx: config.pfx, passphrase: config.mchId })
}

// 生成签名
generateSignature (object: Dic) {
generateSignature(object: Dic) {
const paramList: any[] = []
_.forEach(object, (v, k) => {
if (v) paramList.push(k + '=' + v)
})
paramList.sort()
paramList.sort(undefined)
paramList.push('key=' + this.config.key)
const paramString = paramList.join('&')
return secure.md5(paramString).toUpperCase()
}

// 生成随机字符串
generateNonceString () {
generateNonceString() {
return Math.random().toString(36).substr(2, 15)
}

// 转换为已经签名的XML参数
async toSignedXmlParams (param: Dic, signName = 'sign') {
async toSignedXmlParams(param: Dic, signName = 'sign') {
param[signName] = this.generateSignature(param)
return await xml.encode(param)
}

// 进行post请求
async post (url: string, data: Dic | string, config: Axios.AxiosRequestConfig = {}) {
const res = await axios({ url, data, baseURL, method: 'POST', ...config }).catch(e => e)
async post(url: string, data: Dic | string, config: Axios.AxiosRequestConfig = {}) {
const res = await axios({ url, data, baseURL, method: 'POST', ...config }).catch((e) => e)
// 处理结果
try {
return await this.handleResult(res)
Expand All @@ -56,17 +55,16 @@ export class CoaWxPayIsvBin {
}
}

protected onRequestError (error: Error, response: Axios.AxiosResponse) {
}
protected onRequestError(_error: Error, response: Axios.AxiosResponse) {}

// 处理响应结果
private async handleResult (res: Axios.AxiosResponse) {
const text = res.data as string || ''
private async handleResult(res: Axios.AxiosResponse) {
const text = (res.data as string) || ''
if (!text) CoaError.throw('CoaWxPayIsv.ServeCallError', '微信支付服务器数据异常')
if (!text.startsWith('<xml')) return text
const info: any = await xml.decode(text)
info.return_code === 'SUCCESS' || CoaError.throw('CoaWxPayIsv.ServeReturnError', info.return_msg)
info.result_code === 'SUCCESS' || CoaError.throw('CoaWxPayIsv.ServeResultError', info.err_code + ':' + info.err_code_des)
return $.camelCaseKeys(info)
}
}
}
22 changes: 10 additions & 12 deletions src/service/CoaWxPayIsvService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,21 @@ import { xml } from 'coa-xml'
import { CoaWxPayIsvBin } from '../lib/CoaWxPayIsvBin'

export class CoaWxPayIsvService {

private readonly bin: CoaWxPayIsvBin

constructor (bin: CoaWxPayIsvBin) {
constructor(bin: CoaWxPayIsvBin) {
this.bin = bin
}

// 解码微信返回的信息
async decodeInfo (encodeString: string) {
async decodeInfo(encodeString: string) {
const keyDecode = secure.md5(this.bin.config.key)
const xmlData = secure.aes_decode(encodeString, keyDecode)
return await xml.decode(xmlData) || {}
return (await xml.decode(xmlData)) || {}
}

// 获取支付参数
getPaymentParams (data: { appWxaId: string, prepayId: string }) {
getPaymentParams(data: { appWxaId: string; prepayId: string }) {
const prepayId = data.prepayId || CoaError.message('CoaWxPayIsv.MissingField', '缺少prepayId')
const param: any = {
appId: data.appWxaId || CoaError.message('CoaWxPayIsv.MissingField', '缺少appWxaId'),
Expand All @@ -36,7 +35,7 @@ export class CoaWxPayIsvService {
}

// 微信支付统一下单
async unifiedOrder (data: { orderId: string, price: number, appWxaId: string, subMchId: string, openId: string }) {
async unifiedOrder(data: { orderId: string; price: number; appWxaId: string; subMchId: string; openId: string }) {
const param = {
appid: this.bin.config.appId,
mch_id: this.bin.config.mchId,
Expand All @@ -56,7 +55,7 @@ export class CoaWxPayIsvService {
}

// 退款
async payRefund (data: { refundId: string, orderId: string, price: number, rawData: any }) {
async payRefund(data: { refundId: string; orderId: string; price: number; rawData: any }) {
const rawData = data.rawData || CoaError.message('CoaWxPayIsv.MissingField', '数据不存在')
const refundId = data.refundId || CoaError.message('CoaWxPayIsv.MissingField', '缺少退款ID')
const orderId = data.orderId || CoaError.message('CoaWxPayIsv.MissingField', '缺少订单ID')
Expand All @@ -71,14 +70,14 @@ export class CoaWxPayIsvService {
out_refund_no: refundId,
total_fee: price,
refund_fee: price,
notify_url: `${this.bin.config.notifyRefund}.${orderId}`
notify_url: `${this.bin.config.notifyRefund}.${orderId}`,
}
const body = await this.bin.toSignedXmlParams(param)
return await this.bin.post('/secapi/pay/refund', body, { httpsAgent: this.bin.httpsAgent })
}

// 查询订单状态
async queryOrder (data: { orderId: string, appWxaId: string, subMchId: string }) {
async queryOrder(data: { orderId: string; appWxaId: string; subMchId: string }) {
const param = {
appid: this.bin.config.appId,
mch_id: this.bin.config.mchId,
Expand All @@ -92,7 +91,7 @@ export class CoaWxPayIsvService {
}

// 查询订单退款状态
async queryRefund (data: { orderId: string, refundId: string, appWxaId: string, subMchId: string }) {
async queryRefund(data: { orderId: string; refundId: string; appWxaId: string; subMchId: string }) {
const param = {
appid: this.bin.config.appId,
mch_id: this.bin.config.mchId,
Expand All @@ -107,7 +106,7 @@ export class CoaWxPayIsvService {
}

// 下载账单
async downloadBill (data: { date: string }) {
async downloadBill(data: { date: string }) {
const param = {
appid: this.bin.config.appId,
mch_id: this.bin.config.mchId,
Expand All @@ -118,5 +117,4 @@ export class CoaWxPayIsvService {
const body = await this.bin.toSignedXmlParams(param)
return await this.bin.post('/pay/downloadbill', body, { maxBodyLength: 1024 * 1024 * 1024, maxRedirects: 1024 * 1024 * 1024 })
}

}
11 changes: 6 additions & 5 deletions src/test/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const config = {
key: '1125XXXXXXXXXXXXXXXXXXX6E20DE9',
pfx: Buffer.from('XXXXXXX'),
notifyPay: 'https://example.com/api/notify/pay',
notifyRefund: 'https://example.com/api/notify/refund'
notifyRefund: 'https://example.com/api/notify/refund',
}

// 创建BIN实例
Expand All @@ -35,14 +35,15 @@ await service.queryRefund({ refundId: 'refund000001', orderId: 'order000001', ap
// 下载日对账单
await service.downloadBill({ date: '20210331' })


// 创建自定义BIN类
class MyCoaWxPayIsvBin extends CoaWxPayIsvBin {
protected onRequestError (error: Error, response: Axios.AxiosResponse) {
console.log('error:', error.toString())
protected onRequestError(error: Error, response: Axios.AxiosResponse) {
console.log('error:', error)
console.log('data:', response.data)
}
}

// 自定义BIN实例
const bin = new MyCoaWxPayIsvBin(config)
const myBin = new MyCoaWxPayIsvBin(config)

console.log(myBin.config)
14 changes: 7 additions & 7 deletions src/typings.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
export namespace CoaWxPayIsv {
export interface Config {
appId: string,
mchId: string,
key: string,
pfx: Buffer,
notifyPay: string,
notifyRefund: string,
appId: string
mchId: string
key: string
pfx: Buffer
notifyPay: string
notifyRefund: string
}
}
}
4 changes: 1 addition & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,5 @@
"outDir": "dist",
"declaration": true
},
"include": [
"src"
]
"include": ["src"]
}

0 comments on commit 96d308d

Please sign in to comment.