当前位置: 首页 > article >正文

cool 框架 node 后端封装三方Api post请求函数

1.需求

现在一些数据源 ,需要从三方地址拿到一些数据 比如说电影列表 信息了 影院列表信息了 等一些展示的数据,但是人家这种东西 害需要使用 appkey appserect 这种验签

这种需求 你前端调用接口是直接调用不了的 因为需要用到验签 需要后端接口转接一下 前端再去调用接口

import { Body, Config, Provide } from '@midwayjs/decorator';
import { Inject } from '@midwayjs/decorator';
import { BusinessStudentEntity } from '../entity/student';
import { BusinessUserEntity } from '../entity/user';
import { BusinessBaseConfigEntity } from '../entity/base/config';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

import { BaseService } from '@cool-midway/core';
import * as request from 'request';
import * as _ from 'lodash';
import * as crypto from 'crypto';
import { Context } from '@midwayjs/koa';

/**
 * http请求封装
 */
@Provide()
export class BussinessRequestService extends BaseService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(BusinessStudentEntity)
  businessStudentEntity: Repository<BusinessStudentEntity>;

  @InjectEntityModel(BusinessBaseConfigEntity)
  businessBaseConfigEntity: Repository<BusinessBaseConfigEntity>;

  @InjectEntityModel(BusinessUserEntity)
  businessUserEntity: Repository<BusinessUserEntity>;

  @Config('module.business')
  coolConfig;

  /**
   * post
   */
  async post(url, data = {}) {
    const { userId } = this.ctx.clientInfo;
    //学员信息
    const studentInfo = await this.businessStudentEntity.findOneBy({
      id: userId,
    });
    //对应 导员信息
    const adminInfo = await this.businessBaseConfigEntity.findOneBy({
      userId: String(studentInfo?.userId),
    });
    const requestConfig = this.coolConfig.request;
    let time = new Date().getTime();
    let pararm = {};
    pararm['appId'] = adminInfo.liangPiaoAppId;
    pararm['timestamp'] = time;
    let sign = this.generateSignature(
      pararm,
      data,
      adminInfo.liangPiaoSecret,
      adminInfo.liangPiaoAppId
    );
    return new Promise((resolve, reject) => {
      var option = {
        url:
          requestConfig.base_url +
          url +
          `?appId=${adminInfo.liangPiaoAppId}&sign=${sign}&timestamp=${time}`,
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'content-type': 'application/json',
        },
        body: data,
      };
      request(option, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          const { state, data } = body;
          if (state === 200) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
  /**
   * get
   */
  // get(url, params = {}) {
  //   const requestConfig = this.mangoConfig.request;
  //   params['appId'] = requestConfig.appKey;
  //   params['timestamp'] = new Date().getTime();
  //   params['sign'] = this.generateSignature(
  //     params,
  //     requestConfig.appSecret,
  //     requestConfig.appKey,
  //     params['timestamp']
  //   );

  //   return new Promise((resolve, reject) => {
  //     var option = {
  //       url: requestConfig.base_url + url,
  //       method: 'GET',
  //       timeout: 30000,
  //       qs: params,
  //     };
  //     request(option, function (error, response, body) {
  //       if (!error && response.statusCode == 200) {
  //         const { code, data } = body;
  //         if (code === 1) {
  //           resolve(data);
  //         } else {
  //           reject(body);
  //         }
  //       } else {
  //         reject(error); // 返回错误信息
  //       }
  //     });
  //   });
  // }

  //计算签名
  generateSignature(params, body, secretKey, keys) {
    const joinedParams = this.joinRequestParams(params, body, secretKey, keys);
    const md5Hash = crypto
      .createHash('md5')
      .update(joinedParams)
      .digest('hex')
      .toUpperCase();

    return md5Hash;
  }
  //计算签名
  joinRequestParams(params, body, secretKey, keys) {
    const sb = [secretKey]; // 前面加上 secretKey
    const sortedParams = Object.keys(params)
      .filter(key => key !== 'sign' && params[key]) // 过滤掉不需要的键
      .sort(); // 对键进行排序

    for (const key of sortedParams) {
      sb.push(key + params[key]);
    }
    sb.push(JSON.stringify(body));
    sb.push(secretKey); // 最后加上 secretKey

    return sb.join('');
  }
}

当然一般 这种三方API 都有人家规定的验签规则 让你 写什么样的格式 拼接成什么样的格式

得看实际的需求 我这里主要介绍的是 post 请求的封装 (在jsNode 中书写后端接口)  是需要引入request 插件


http://www.kler.cn/news/233794.html

相关文章:

  • NLP_Bag-Of-Words(词袋模型)
  • 如何进行游戏服务器的负载均衡和扩展性设计?
  • VUE学习——事件参数
  • 每天一个数据分析题(一百五十六)
  • moduleID的使用
  • 【学习笔记】【内核】offsetof 的用法
  • 算法学习——LeetCode力扣二叉树篇1
  • c# 时间帮助类
  • 2.6:冒泡、简选、直插、快排,递归,宏
  • VMware虚拟机安装openEuler系统(一)(2024)
  • Idea里自定义封装数据警告解决 Spring Boot Configuration Annotation Processor not configured
  • Qt QML学习(一):Qt Quick 与 QML 简介
  • 【资料分享】基于单片机大气压监测报警系统电路方案设计、基于飞思卡尔的无人坚守点滴监控自动控制系统设计(程序,原理图,pcb,文档)
  • MySQL-SQL优化
  • JAVA设计模式之观察者模式详解
  • GPT原始论文:Improving Language Understanding by Generative Pre-Training论文翻译
  • Unity UGUI实现点击事件穿透
  • java多线程的四种创建方式、程序、线程、进程、并行、串行、Thread、Runnable、Callable、线程池技术
  • 二分查找的应用
  • 二维火API连接,实现无代码开发广告推广与用户运营集成
  • thinkphp数据批量提交(群发消息)
  • 烟火可禁却难禁,灵境难及终将及
  • 17、ELK
  • 785. 快速排序
  • 【数据分享】1929-2023年全球站点的逐日平均风速数据(Shp\Excel\免费获取)
  • Spring Boot 自定义指标
  • Matplotlib交互
  • Linux运行级别 | 管理Linux服务
  • Springboot集成rabbitmq
  • linux系统非关系型数据库memcached