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

发布时间:2024年01月23日

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

文章来源:https://blog.csdn.net/lele66688888/article/details/135762960
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。