utils.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 { sign } = require('../common');
  19. /**
  20. * 请求腾讯云验证码接口公共方法
  21. * @param {string} action - 接口请求action
  22. * @param {object} payload - 接口请求体
  23. * @returns {object} API返回的有效数据
  24. */
  25. async function request(action, payload) {
  26. const [timestamp, authorization] = sign('captcha', JSON.stringify(payload));
  27. const options = {
  28. url: 'https://captcha.tencentcloudapi.com',
  29. method: 'POST',
  30. headers: {
  31. 'Content-Type': 'application/json',
  32. 'X-TC-Action': action,
  33. 'X-TC-Version': '2019-07-22',
  34. 'X-TC-Timestamp': timestamp,
  35. Authorization: authorization
  36. },
  37. data: payload
  38. };
  39. const response = await axios(options);
  40. const { status, statusText, data } = response;
  41. if (status !== 200) {
  42. throw new Error(`${action}接口调用失败[${status} - ${statusText}]`);
  43. }
  44. if (data.Response.Error) {
  45. throw new Error(data.Response.Error.Message);
  46. }
  47. return data.Response;
  48. }
  49. module.exports = { request };