海康互联开放平台对接-node

312 阅读1分钟

获取身份及授权

  1. 用户访问凭证
  2. 申请授权码
  3. 授权码获取用户访问凭证

1、2步基本上不会遇到什么问题,到第3步,开始报错“无法获取到加密参数,请按照API调用规范对请求加密”😭

API调用规范

遇到问题看文档,找到API调用规范。发现其接口请求参数以及返回的数据需要用RSA加密算法,且官方只有JAVA示例。

rsa加解密文件-node版本 github.com/Yhhhhhhh/ha…

如何用node去调用

我这边用的是express + axios

axios.js

const axios = require('axios')
const localStorage = require('../store/store')
const RSAUtils = require('../until/rsa')
const header = {'Content-Type': 'application/json'}
const key = {
  appKey: '你的appKey',
  appSecret: '你的appSecret'
}
const baseUrl = 'https://open-api.hikiot.com'

// 创建axios实例
const service = axios.create({
  baseURL: baseUrl, // api的base_url
  timeout: 5000, // 请求超时时间
  headers: header
});

const privateKey = key.appSecret;

function isHasParams(params){
  if(!params || params ==='undefined') return false
  const isObject = params instanceof Object && params !== null
  if(isObject){
    return Object.keys(params).length
  }
  return Object.keys(JSON.parse(params)).length
}

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 可以在这里添加请求头等信息
    if (localStorage.getItem('appAccessToken')) {
      config.headers['App-Access-Token'] = localStorage.getItem('appAccessToken');
    }
    if (localStorage.getItem('userAccessToken')) {
      config.headers['User-Access-Token'] = localStorage.getItem('userAccessToken');
    }
    if (config.method === 'post' && !['/auth/third/applyAuthCode','/auth/exchangeAppToken'].includes(config.url) && isHasParams(config.data)) {
      const encodeData = RSAUtils.encryptByPrivateKey(JSON.stringify(config.data), privateKey)
      config.data = {bodySecret: encodeData}
    }
    if (config.method === 'get' && isHasParams(config.params)) {
      const searchParams = new URLSearchParams(config.params)
      const encodeData = RSAUtils.encryptByPrivateKey(searchParams.toString(), privateKey)
      config.url = config.url + '?querySecret=' +encodeURIComponent(encodeData)
      delete config.params
    }
    return config;
  },
  error => {
    // 请求错误处理
    console.log(error); // for debug
    Promise.reject(error);
  }
);
 
// 响应拦截器
service.interceptors.response.use(
  response => {
    // 对响应数据做处理,例如只返回data部分
    const res = response.data;
    if(res.data && typeof res.data === 'string'){
      res.data = JSON.parse(RSAUtils.decryptByPrivateKey(res.data, privateKey))
      console.log(res.data)
    }
    return res;
  },
  error => {
    console.log('err' + error); // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // });
    return Promise.reject(error);
  }
);
 
module.exports = service;

store.js

LocalStorage = require('node-localstorage').LocalStorage;
const localStorage = new LocalStorage('./scratch');

module.exports = localStorage

创建express项目,安装所需包,正常调用就可以啦。