微信公众测试号获取用户信息

2,367 阅读1分钟

为了实现在微信打开的h5网页获取微信用户信息的功能

特意怼了开发文档一天

流程为:1.用户调用login接口 -> 引导到auth接口 -> 微信授权页面 -> 回调接口 -> 获取用户信息 -> 显示用户信息页面

配置项

重要项: appIdappSecret

由于微信公众号的限制,需要配置服务器域名与ip白名单

由于目前没有提供外网的域名。所以我选择了利用natapp内网穿透,将本地ip映射到域名

(注:natapp会不定时更换域名,需要注意)

1.配置ip白名单 开发 -> 基本配置 -> ip白名单

2.配置测试号 开发 -> 开发者工具 -> 开发者文档 -> 开始开发 -> 接口测试号申请

3.安全域名配置

在测试号管理页面配置

关注测试公众号

修改回调域名

到这里就可以写真正的代码了

1.调用login接口

login接口其实就是调到登录页面,然后触发auth接口

  public login(ctx) {
    ctx.res.writeHead(302, {
      'Location': '/login.html',
    });
    ctx.res.end();
  }

login页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test</title>
</head>
<body>
    <a href="/api/wechat-public/auth">授权并获取用户信息</a>
</body>
</html>

2.调用auth接口

  public auth(ctx) {
    ctx.res.writeHead(302, {
      'Location': this.authorizationUrl,
    });
    ctx.res.end();
  }

其中authorizationUrl为https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_CONFIG.APP_ID}&redirect_uri=${host}${redirectUrl}&response_type=code&scope=snsapi_userinfo#wechat_redirect

其中的appId需要换成你自己的

host需要和配置里的回调域名一致

3.回调接口

这边进行的处理为

1.首先拿到地址栏里的code,之后以及用户的openid

2.通过code 获取accessToken

3.通过accessToken以及openid获取用户信息

public async getUserInfo(ctx) {
    try {
      const { code } = ctx.query;
      //通过拿到的code和appID、app_serect获取返回信息
      const { access_token: token, open_id: openId } = await WechatTokenService.getAccessToken(code).catch(err => {
        console.log(err);
      });
      const userObj = await WechatTokenService.getWechatUserinfo(token, openId);
      await ctx.render('userInfo', { userObj: userObj });
    } catch (err) {
      console.log(err);
    }
  }

WechatTokenService实现

import * as rp from 'request-promise';
import { WECHAT_CONFIG } from '../_constants';

export class WechatTokenService {
  private static accessUrl: string;
  public static async getAccessToken(code): Promise<any> {
    this.accessUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WECHAT_CONFIG.APP_ID}&secret=${WECHAT_CONFIG.APP_SECRET}&code=${code}&grant_type=${WECHAT_CONFIG.GRANT_TYPE.authorization_code}`;
    return this.invokeRequest(this.accessUrl);
  }
  public static async getWechatUserinfo(token, openId): Promise<any> {
    const getUserUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openId}&lang=zh_CN`;
    return this.invokeRequest(getUserUrl);
  }
  private static async invokeRequest(url) {
    return new Promise((resolve) => {
      rp(url).then(res => {
        resolve(JSON.parse(res));
      }).catch(err => {
        console.log('occured error!');
      });
    });
  }
}

可以通过微信开发者工具去试

源码地址