utils.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. const axios = require('axios');
  18. const { region } = require('./config');
  19. const { sign } = require('../common');
  20. /**
  21. * 请求腾讯云人脸核身公共方法
  22. * @param {string} action - 接口请求action
  23. * @param {object} payload - 接口请求体
  24. * @returns {object} API返回的有效数据
  25. */
  26. async function request(action, payload) {
  27. if (!region) {
  28. throw new Error('请在云函数FACEID模块中配置region');
  29. }
  30. const [timestamp, authorization] = sign('faceid', JSON.stringify(payload));
  31. const options = {
  32. url: 'https://faceid.tencentcloudapi.com',
  33. method: 'POST',
  34. headers: {
  35. 'Content-Type': 'application/json',
  36. 'X-TC-Action': action,
  37. 'X-TC-Version': '2018-03-01',
  38. 'X-TC-Timestamp': timestamp,
  39. 'X-TC-Region': region,
  40. Authorization: authorization
  41. },
  42. responseType: 'json',
  43. data: payload
  44. };
  45. const response = await axios(options);
  46. const { status, statusText, data } = response;
  47. if (status !== 200) {
  48. throw new Error(`${action}接口调用失败[${status} - ${statusText}]`);
  49. }
  50. if (data.Response.Error) {
  51. throw new Error(data.Response.Error.Message);
  52. }
  53. return data.Response;
  54. }
  55. module.exports = { request };