日期:2021/06/03 天气:多云

项目背景

云票儿目前没有node-sdk,需要自己封装

  1. /*
  2. * @Descripttion: 云票儿SDK
  3. * @version: v1.0.0
  4. * @Author: nianqing
  5. * @Date: 2021-06-02 14:58:46
  6. */
  7. const axios = require("axios");
  8. const crypto = require('crypto');
  9. // 参考文档: https://docs.cloud.goldentec.com/%E4%BA%91%E5%BC%80%E7%A5%A8/API%E6%96%87%E6%A1%A3/%E5%BC%80%E7%A5%A8%E6%9C%8D%E5%8A%A1%E7%9B%B8%E5%85%B3%E6%8E%A5%E5%8F%A3/%E5%8F%91%E7%A5%A8%E5%BC%80%E5%85%B7%E3%80%81%E6%89%93%E5%8D%B0/%E5%8F%91%E7%A5%A8%E5%BC%80%E5%85%B7.html
  10. class BanuSdk {
  11. /**
  12. * @param {*} appKey 应用Key
  13. * @param {*} algorithm 加密方式
  14. * @param {*} appSecret 应用秘钥
  15. * @param {*} env 环境,测试:test 线上:prod
  16. */
  17. constructor({ appKey = '550c2af56e4b174c9505', algorithm = "HMAC-SHA256", appSecret = '3792950fd36c9c54ee96deacc3ef433a', env = "test" }) {
  18. this.appKey = appKey;
  19. this.appSecret = appSecret;
  20. this.algorithm = algorithm;
  21. this.env = env;
  22. this.host = env === 'test' ? 'https://apigw-test.goldentec.com' : 'https://apigw.goldentec.com';
  23. }
  24. formatParams(args, join) {
  25. let keys = Object.keys(args)
  26. if (join === '|') { keys = keys.sort() }
  27. let newArgs = {}
  28. keys.forEach(function (key) {
  29. if (args[key] != "" && args[key] != 'undefined') { //如果参数的值为空不参与签名;
  30. newArgs[key] = args[key] //参数名区分大小写;
  31. }
  32. })
  33. let string = ''
  34. for (let k in newArgs) {
  35. string += join + k + '=' + newArgs[k]
  36. }
  37. string = string.substr(1)
  38. return string
  39. }
  40. sign(path, params) {
  41. const timeStamp = Math.round(new Date().getTime() / 1000).toString(); //毫秒级时间戳
  42. const nonce = Math.random().toFixed(6).slice(-6); // 6位随机数字
  43. const publicParams = {
  44. algorithm: this.algorithm,
  45. appkey: this.appKey,
  46. nonce: nonce,
  47. timestamp: timeStamp
  48. }
  49. const formatString = this.formatParams(publicParams, '|');
  50. params = JSON.stringify(params)
  51. const oldString = `${formatString}|${path}|${params}`;
  52. const sign = crypto.createHmac('sha256', this.appSecret).update(oldString).digest('base64');
  53. let authParams = Object.assign({}, publicParams);
  54. authParams.signature = sign;
  55. const auth = this.formatParams(authParams, ',')
  56. return auth;
  57. }
  58. request(path, options) {
  59. const auth = this.sign(path, options.post)
  60. const url = `${this.host}${path}`
  61. return axios.post(url, options.post, { headers: { "Authorization": auth, "Content-Type": "application/json" } }).then(res => {
  62. if (res.data && res.data.code === 0) {
  63. return res.data
  64. } else {
  65. console.log(res.data)
  66. const msg = '请求云票儿服务失败'
  67. return msg
  68. }
  69. })
  70. }
  71. }
  72. module.exports = BanuSdk;