在微信公众号开发中,我们需要使用到微信 OAuth2.0 授权,以获取用户的基本信息。然而,每个公众号都需要自行开发授权功能,并针对不同的微信 API 进行接口开发,这样非常繁琐。因此,一个可以直接使用的 npm 包 wxoauth 就应运而生。
本文将详细介绍如何使用 wxoauth 包来快速开发微信 OAuth2.0 授权。
安装
要使用 wxoauth 包,您需要在项目目录下使用 npm 安装它。
npm install wxoauth --save
使用
首先,我们需要获取一个微信开发者账号,并在其中新建一个公众号。在公众号的 接口配置 中,填写以下信息:
- URL(必须为
https协议,或者符合http://localhost格式的域名) - Token(自定义,用于验证开发者服务器)
- EncodingAESKey(加解密消息体时使用,是 AES 密钥的 Base64 编码)
接下来,我们就可以使用 wxoauth 来获取 OAuth2.0 授权了。
// www.javascriptcn.com code example
const WxOAuth = require('wxoauth');
// 配置
const config = {
appid: 'YOUR_APP_ID', // 公众号的唯一标识
secret: 'YOUR_SECRET', // 公众号的 appsecret
redirect_uri: 'REDIRECT_URI', // 授权后重定向的回调链接地址 (要进行 url encode)
state: 'STATE', // 传递给授权后页面的参数,用于防止 CSRF 攻击(可以为空)
scope: 'snsapi_userinfo' // 授权类型,分为:snsapi_base 和 snsapi_userinfo
};
// 实例化 wxoauth 对象
const wxoauth = new WxOAuth(config);
// 获取 OAuth2.0 授权页面 url
const authUrl = wxoauth.getAuthorizeUrl();
// 获取用户基本信息
wxoauth.getUserInfo(code).then(userInfo => {
console.log(userInfo);
}).catch(error => {
console.log(error);
});示例代码
对于初学者而言,更直观地理解一个功能往往需要代码的示例。因此,下面提供基于 Express 框架的 OAuth2.0 授权示例代码。
// www.javascriptcn.com code example
const express = require('express');
const WxOAuth = require('wxoauth');
// 创建一个 express 实例
const app = express();
// 配置
const config = {
appid: 'YOUR_APP_ID', // 公众号的唯一标识
secret: 'YOUR_SECRET', // 公众号的 appsecret
redirect_uri: 'REDIRECT_URI', // 授权后重定向的回调链接地址 (要进行 url encode)
state: '', // 传递给授权后页面的参数,用于防止 CSRF 攻击(可以为空)
scope: 'snsapi_userinfo' // 授权类型,分为:snsapi_base 和 snsapi_userinfo
};
const wxoauth = new WxOAuth(config);
// 授权接口
app.get('/oauth', (req, res) => {
// 生成 OAuth2.0 授权页面 url
const authUrl = wxoauth.getAuthorizeUrl();
// 重定向到授权页面
res.redirect(authUrl);
});
// 授权回调接口
app.get('/oauth/callback', (req, res) => {
const code = req.query.code; // 获取授权码
wxoauth.getUserInfo(code).then(userInfo => {
// 获取用户信息成功
res.send(userInfo);
}).catch(error => {
// 获取用户信息失败
res.send('Error: ' + error.message);
});
});
// 启动服务器
app.listen(3000, () => {
console.log('Server started on port 3000');
});总结
在本文中,我们详细介绍了如何使用 wxoauth 包来快速开发微信 OAuth2.0 授权。通过使用 npm 包,我们可以极大地减少开发 OAuth2.0 授权模块的时间和精力,从而更加专注于业务逻辑的开发。
在进行微信公众号开发时,这样的便利将给我们带来不少的启迪。因此,我们强烈建议大家尝试使用 wxoauth 包来优化自己的开发流程。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/600671188dd3466f61ffe71b