cool框架 Node.js 后端接口实现微信公众号重定向授权登录

1.需求 

做一个获取微信公众号H5 公众号重定向登录授权的接口 

2.代码

controller

/**
   * H5 g公众号
   * @param login
   */
  @Post('/wxCode', { summary: '获取code授权' })
  async getOpenAndatoken(@Body() body) {
    const res: any = await this.businessLoginService.getAccessTokenByWx(body);
    await this.cacheManager.set(
      'access_token',
      JSON.parse(res)['access_token']
    );
    // // 缓存10秒
    // await this.cacheManager.set('a', 1, {
    //   ttl: 10,
    // });

    return this.ok(JSON.parse(res)['openid']);
  }


 @Post('/wxLogin', { summary: '公众号用户登录' })
  async weChatLogin(@Body() body) {
    body['access_token'] = await this.cacheManager.get('access_token');
    console.log(body['access_token'], body);

    const res: any = await this.businessLoginService.weChatLogin(body);
    console.log(res, '用户信息');

    return this.ok(res);
  }

service

  //微信用户公众号登录
  async weChatLogin(user) {
    const config = this.coolConfig;
    const wxUserInfo = JSON.parse(
      await this.WechateService.getSnsapiUuserinfo(user)
    );
    console.log(wxUserInfo);
    const obj = await this.businessStudentEntity.findOneBy({
      wechatOpenid: wxUserInfo?.openid,
    });
    const teacher = await this.businessUserEntity.findOneBy({
      inviteCode: 'FB75FA1F',
    });
    if (!obj) {
      const data = {
        membershipLevel: 0,
        avatar: wxUserInfo?.headimgurl,
        wechatOpenid: wxUserInfo?.openid,
        balance: 0,
        nickname: wxUserInfo?.nickname,
        userId: teacher.id,
      };
      await this.businessStudentEntity.save(data);
    }
    const newUserInfo = await this.businessStudentEntity.findOneBy({
      wechatOpenid: wxUserInfo?.openid,
    });
    if (newUserInfo.phone) {
      // 生成token
      const { expire, refreshExpire } = config.jwt.token;
      const result = {
        expire,
        token: await this.generateToken(newUserInfo, expire),
        refreshExpire,
        refreshToken: await this.generateToken(
          newUserInfo,
          refreshExpire,
          true
        ),
      };
      // 将用户相关信息保存到缓存
      await this.cacheManager.set(
        `${config.name}:token:${newUserInfo.id}`,
        result.token
      );
      await this.cacheManager.set(
        `${config.name}:token:refresh:${newUserInfo.id}`,
        result.token
      );
      return { newUserInfo, token: result.token };
    } else if (!newUserInfo.phone) {
      throw new CoolCommException('没有找到该用户');
    }
    // return await this.WechateService.getSnsapiUuserinfo(user);
  }
  //获取sccessToken
  async getAccessTokenByWx(body) {
    return await this.WechateService.getAccessToken(body);
  }

微信Api

@Provide()
export class WechateService extends BaseService {
  @Config('module.business')
  businessConfig;

  /**
   * 获取openid 和access Token
   */
  getAccessToken(code: string) {
    let appId = ''; // appId
    let secret = ''; //公众号密钥
    const options = {
      url: 'https://api.weixin.qq.com/sns/oauth2/access_token',
      qs: {
        appid: appId,
        secret: secret,
        code: code?.code,
        grant_type: 'authorization_code',
      },
      method: 'GET',
    };

    return new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (error) {
          reject(error);
        } else {
          console.log(body);

          resolve(body); // 这里返回的是 JSON 格式的数据,可以直接解析为对象或数组
        }
      });
    });
  }
  //拉取用户信息
  async getSnsapiUuserinfo(query) {
    const options = {
      url: 'https://api.weixin.qq.com/sns/userinfo',

      qs: {
        access_token: query.access_token,
        openid: query.userName,
        lang: 'zh_CN',
      },
      method: 'GET',
    };

    return new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (error) {
          reject(error);
        } else {
          console.log(body, '拉取用户信息');

          resolve(body); // 这里返回的是 JSON 格式的数据,可以直接解析为对象或数组
        }
      });
    });
  }
}

3.总结 其实就是调用了微信Api 根据一些公众号的信息 获取了 用户的头像昵称和openid

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值