An overview of the
A JS plug-in based on JS-Cookie, AXIos, etc., to obtain user information such as OpenID UnionID through wechat webpage authorization
configuration
attribute | instructions | type | mandatory | The default value |
---|---|---|---|---|
appId | The unique identifier of the public account | String | is | – |
scope | Apply the authorization scopesnsapi_base snsapi_userinfo , please check the wechat development document for details |
String | no | snsapi_base |
expires | Cookies expiration time/day | Number | no | 30 |
state | It will be redirectedstate Parameter, the developer can fill in the parameter value of A-zA-Z0-9, up to 128 bytes |
String | no | – |
oauthUrl | Server authorization, absolute address, getopenid unionid |
String | is | – |
onSuccess | The hook that was successfully authorized by the server, and the return field is Response, and the hook needs to returnopenId unionId userInfo Data for logical processing |
Function | is | – |
onFail | The hook for server authorization failure with the error return field | Function | no | – |
methods
The method name | instructions | parameter |
---|---|---|
init | Initialize the | – |
oauth | Authorization, then call switchable account | – |
getUserInfo | Obtaining User information | – |
The sample
import WxOauth from "@/utils/wx/oauth";
const wxOauth = new WxOauth({
appId: "your appId".oauthUrl: "your oauthUrl".onSuccess: response= > {
// After the callback is successfully processed, obtain information such as unionId openId userInfo and return
const unionId = "unionId";
const openId = "openId";
const userInfo = "userInfo";
return{ unionId, openId, userInfo }; }}); wxOauth.init();Copy the code
code
import Cookies from "js-cookie";
import axios from "axios";
class WxOauth {
/ * * * @ param appId public unique identification number * @ param scope application authorization scope snsapi_base | snsapi_userinfo, Default snsapi_base * @param Expires Cookies Expiration time/day (default: 30 days) * @param state Redirects with the state parameter. Developers can specify the value of the a-Za-Z0-9 parameter. Up to 128 bytes * @param oauthUrl Server authorization, absolute address, get openID unionID * @param onSuccess Hook for server authorization success, The return field is Response * @param onFail Hook for server authorization failure. The return field is Error */
constructor(options) {
const {
appId,
scope,
expires,
state,
oauthUrl,
onSuccess,
onFail
} = options;
this.appId = appId;
this.scope = scope || "snsapi_base";
this.isSnsapiBase = scope === "snsapi_base";
this.expires = expires || 30;
this.state = state;
this.oauthUrl = oauthUrl;
this.onSuccess = onSuccess;
this.onFail = onFail || function() {};
}
/** * @description 'determines whether the data is an object' ** @param {*} data */
_isObject(data) {
return Object.prototype.toString.call(data) === "[object Object]";
}
/** * @description /** @param {name} name */
_getQueryString(name) {
return (
decodeURIComponent((new RegExp("[? | &]" + name + "=" + "([^ &;] +? (& # | |; | $)").exec(
location.href
) || ["".""[])1].replace(/\+/g."% 20") | |null
);
}
/ * * * @ the description for the url after joining together, filtering undefined | null data * * @ param {String} * @ url param {Object} data * /
_getUrl(url, data) {
if (!this._isObject(data)) {
return url;
}
const params = Object.keys(data).reduce((pre, key) = > {
constvalue = data[key]; value ! = =undefined&& value ! = =null &&
(pre += ` &${key}=${value}`);
return pre;
}, "");
return `${url}${params.replace("&"."?")}`;
}
/** * @description server authorization to obtain user information */
_oauth(code, state) {
return new Promise((resolve, reject) = > {
const options = {
method: "POST".data: {
code,
state
},
url: this.oauthUrl
};
axios
.request(options)
.then(res= > {
const { openId, unionId, userInfo } = this.onSuccess(
res.data
);
Cookies.set(this._getCookieName("unionId"), unionId, {
expires: this.expires
});
Cookies.set(this._getCookieName("openId"), openId, {
expires: this.expires
});
Cookies.set(this._getCookieName("userInfo"), userInfo, {
expires: this.expires
});
resolve();
})
.catch(err= > this.onFail(err));
});
}
/** * @description generates a specific cookie name */
_getCookieName(name) {
return `wx_oauth_The ${this.appId}_${name}`;
}
/** * @description Whether to log in */
_isLogged(openId, unionId) {
return this.isSnsapiBase ? openId : unionId || openId;
}
/** * @description log in and obtain user information */ by code
async _login() {
const code = this._getQueryString("code");
if (code) {
const state = this._getQueryString("state");
await this._oauth(code, state);
return;
}
this.oauth();
}
init() {
const unionId = Cookies.get(this._getCookieName("unionId"));
const openId = Cookies.get(this._getCookieName("openId"));
!this._isLogged(openId, unionId) && this._login();
}
/** * @description wechat authorization, support account switching */
oauth() {
Cookies.remove(this._getCookieName("unionId"));
Cookies.remove(this._getCookieName("openId"));
const url = this._getUrl(
"https://open.weixin.qq.com/connect/oauth2/authorize",
{
appid: this.appId,
redirect_uri: encodeURIComponent(location.href),
response_type: "code".scope: this.scope,
state: this.state
}
);
location.href = `${url}#wechat_redirect`;
}
/** * @description Gets user information */
getUserInfo() {
const userInfo = Cookies.get(this._getCookieName("userInfo"));
return userInfo ? JSON.parse(userInfo) : {}; }}export default WxOauth;
Copy the code
github
Github.com/SuperIron/w…
The author
SuperIron