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