如果是自己使用eggjs写 怎么获取用户的openid
时间: 2024-01-24 10:18:30 浏览: 27
要获取用户的openid,需要先了解一下微信公众平台的OAuth2.0授权机制。在用户授权成功后,微信会返回一个包含openid等信息的access_token,通过access_token可以获取用户的基本信息。
以下是一种获取用户openid的方法:
1. 配置公众号的授权回调域名,将其设置为自己的服务器域名。
2. 在需要获取用户openid的地方,生成微信授权链接,跳转至微信授权页并获取授权码。
```
// 跳转至微信授权页,获取授权码
const redirectUrl = encodeURIComponent('http://your.server.com/callback');
const scope = 'snsapi_base'; // snsapi_base 只获取用户openid,snsapi_userinfo 获取用户信息
const appId = 'your_app_id';
const state = 'your_state';
const oauthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
ctx.redirect(oauthUrl);
```
3. 在回调接口中获取access_token,进而获取用户openid。
```
const code = ctx.query.code;
const appId = 'your_app_id';
const appSecret = 'your_app_secret';
const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${code}&grant_type=authorization_code`;
const res = await axios.get(url);
const accessToken = res.data.access_token;
const openid = res.data.openid;
```
注意:这种方式只能获取到用户的openid,如果需要获取更多信息,需要在授权时将scope设置为snsapi_userinfo,然后通过access_token获取用户详细信息。