跳到主要内容

参考代码 - JavaScript/NodeJS

安装依赖:

npm install --save jsonwebtoken string-random axios

示例代码:

const jwt = require('jsonwebtoken')
const stringRandom = require('string-random')
const axios = require('axios')

function EzrevenueClient({ projectId, projectSecret }) {
const BASE_URL = 'https://revenue.ezboti.com/api/v1/server'
const self = {
decodeToken(token) {
const decoded = jwt.verify(token, projectSecret, { complete: true })
const { result } = decoded.payload
return result
},
encodeToken(payload) {
payload.exp = Date.now() + 30 * 60 // 过期时间,建议当前时间+30分钟
payload.nonce = stringRandom(32) // 随机字符串,32个字符以内
const header = { project_id: projectId }
return jwt.sign(payload, projectSecret, { header })
},
sendRequest({ url, content }) {
return axios({
method: 'POST',
url: url,
headers: {
'Content-Type': 'text/plain',
},
data: content,
})
},
call(api, params) {
const token = self.encodeToken({ method: api, params: params })
const url = BASE_URL + '/' + api
return self
.sendRequest({ url, content: token })
.then(function(response) {
return self.decodeToken(response.data)
})
.catch(error => {
if (error.response) {
const { status, data } = error.response
console.log(`${api} failed status=${status}, body ==>`, data)
}
return Promise.reject(error)
})
},
}
return self
}

function main() {
const projectId = 'project-id' // 艺爪付费项目ID
const projectSecret = 'project-secret' // 艺爪付费项目密钥
// 接口名称和参数,可参考具体API页面的说明
const api = 'customer.info' // 接口名称
const params = {
paywall_id: 'xxx', // 付费界面ID,ID和别名传一个即可
paywall_alias: '', // 付费界面别名,ID和别名传一个即可
customer: {
external_id: 'test-user-id', // 商户系统用户ID
nickname: null, // 商户系统用户用户名/昵称,可选
external_dt_created: null, // 商户系统用户创建时间,可选
},
include_balance: true, // 是否返回用户余额
}
const client = EzrevenueClient({ projectId, projectSecret })
return client
.call(api, params)
.then(result => {
console.log('result ==>', result)
})
.catch(error => {
console.log('error ==>', error)
})
}

main()