跳到主要内容

参考代码 - Ruby

安装依赖:

gem install http

示例代码:

require 'logger'
require 'securerandom'
require 'jwt'
require 'http'

TOKEN_ALGORITHM = "HS256"
TOKEN_FIELDS = ["exp", "nonce"]
TOKEN_EXPIRES_IN = 30 * 60

BASE_URL = 'https://revenue.ezboti.com/api/v1/server'

class EzrevenueClient
def initialize(project_id:, project_secret:, base_url: BASE_URL)
@project_id = project_id
@project_secret = project_secret
@base_url = base_url
@logger = Logger.new(STDOUT)
end

def decode_token(token)
begin
payload = JWT.decode(
token,
@project_secret,
true,
{
algorithm: TOKEN_ALGORITHM,
verify_expiration: true,
leeway: 30,
required_claims: TOKEN_FIELDS,
}
)[0]
rescue JWT::DecodeError => e
raise e
end
return payload
end

def encode_token(payload)
exp = Time.now.to_i + TOKEN_EXPIRES_IN
nonce = SecureRandom.urlsafe_base64(10)
payload = payload.merge(exp: exp, nonce: nonce)
token = JWT.encode(payload, @project_secret, TOKEN_ALGORITHM, { project_id: @project_id })
return token
end

def call(api, params)
payload = { method: api, params: params }
content = encode_token(payload)
url = "#{@base_url}/#{api}"
response = HTTP.post(url, body: content, headers: { 'Content-Type': 'text/plain' })

unless response.status.success?
err_msg = "#{api} failed status=#{response.status.code}, body=#{response.body}"
@logger.warn(err_msg)
raise StandardError.new(err_msg)
end

result = decode_token(response.body.to_s)
return result['result']
end
end

def main
client = EzrevenueClient.new(
project_id: '', # 艺爪付费项目ID
project_secret: '', # 艺爪付费项目密钥
)

# 接口名称和参数,可参考具体API页面的说明
result = client.call(
'customer.info', # 接口名称
{
paywall_id: nil, # 付费界面ID,ID和别名传一个即可
paywall_alias: nil, # 付费界面别名,ID和别名传一个即可
customer: {
external_id: 'test-user-id', # 商户系统用户ID
nickname: nil, # 商户系统用户用户名/昵称,可选
external_dt_created: nil, # 商户系统用户创建时间,可选
},
include_balance: true, # 是否返回用户余额
}
)

puts result
end

if __FILE__ == $0
main
end