概述
一款基于 js-cookie介时、axios 等碉京,通過微信網(wǎng)頁授權(quán),以獲取 openid unionid 等用戶信息的 js 插件
配置
屬性 | 說明 | 類型 | 必填 | 默認(rèn)值 |
---|---|---|---|---|
appId | 公眾號(hào)的唯一標(biāo)識(shí) | String | 是 | - |
scope | 應(yīng)用授權(quán)作用域 snsapi_base snsapi_userinfo 责掏,詳情請查看微信開發(fā)文檔 |
String | 否 | snsapi_base |
expires | Cookies 過期時(shí)間/天 | Number | 否 | 30 |
state | 重定向后會(huì)帶上 state 參數(shù)砍鸠,開發(fā)者可以填寫 a-zA-Z0-9 的參數(shù)值,最多 128 字節(jié) |
String | 否 | - |
oauthUrl | 服務(wù)器授權(quán)良漱,絕對(duì)地址舞虱,獲取 openid unionid
|
String | 是 | - |
onSuccess | 服務(wù)器授權(quán)成功時(shí)的鉤子,返回字段為 response母市,且鉤子需要返回 openId unionId userInfo 等數(shù)據(jù)做邏輯處理 |
Function | 是 | - |
onFail | 服務(wù)器授權(quán)失敗時(shí)的鉤子矾兜,返回字段為 error | Function | 否 | - |
方法
方法名 | 說明 | 參數(shù) |
---|---|---|
init | 初始化 | - |
oauth | 授權(quán),再調(diào)用可切換賬號(hào) | - |
getUserInfo | 獲取用戶信息 | - |
示例
import WxOauth from "@/utils/wx/oauth";
const wxOauth = new WxOauth({
appId: "your appId",
oauthUrl: "your oauthUrl",
onSuccess: response => {
// 處理成功回調(diào)后患久,獲取unionId openId userInfo等信息并返回
const unionId = "unionId";
const openId = "openId";
const userInfo = "userInfo";
return {
unionId,
openId,
userInfo
};
}
});
wxOauth.init();
代碼
import Cookies from "js-cookie";
import axios from "axios";
class WxOauth {
/**
* @param appId 公眾號(hào)的唯一標(biāo)識(shí)
* @param scope 應(yīng)用授權(quán)作用域snsapi_base|snsapi_userinfo椅寺,默認(rèn)snsapi_base
* @param expires Cookies過期時(shí)間/天浑槽,默認(rèn)30天
* @param state 重定向后會(huì)帶上state參數(shù),開發(fā)者可以填寫a-zA-Z0-9的參數(shù)值返帕,最多128字節(jié)
* @param oauthUrl 服務(wù)器授權(quán)桐玻,絕對(duì)地址,獲取openid unionid
* @param onSuccess 服務(wù)器授權(quán)成功時(shí)的鉤子荆萤,返回字段為 response
* @param onFail 服務(wù)器授權(quán)失敗時(shí)的鉤子镊靴,返回字段為 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 `判斷數(shù)據(jù)是否為對(duì)象`
*
* @param {*} data
*/
_isObject(data) {
return Object.prototype.toString.call(data) === "[object Object]";
}
/**
* @description 獲取請求參數(shù),支持解析帶#的url
*
* @param {name} name 參數(shù)名
*/
_getQueryString(name) {
return (
decodeURIComponent(
(new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
location.href
) || ["", ""])[1].replace(/\+/g, "%20")
) || null
);
}
/**
* @description 獲取拼接后的url链韭,過濾undefined|null數(shù)據(jù)
*
* @param {String} url
* @param {Object} data
*/
_getUrl(url, data) {
if (!this._isObject(data)) {
return url;
}
const params = Object.keys(data).reduce((pre, key) => {
const value = data[key];
value !== undefined &&
value !== null &&
(pre += `&${key}=${value}`);
return pre;
}, "");
return `${url}${params.replace("&", "?")}`;
}
/**
* @description 服務(wù)器授權(quán)偏竟,獲取用戶信息
*/
_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 生成特定cookie名
*/
_getCookieName(name) {
return `wx_oauth_${this.appId}_${name}`;
}
/**
* @description 是否已登錄
*/
_isLogged(openId, unionId) {
return this.isSnsapiBase ? openId : unionId || openId;
}
/**
* @description 登錄,通過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 微信授權(quán)敞峭,支持切換賬號(hào)
*/
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 獲取用戶信息
*/
getUserInfo() {
const userInfo = Cookies.get(this._getCookieName("userInfo"));
return userInfo ? JSON.parse(userInfo) : {};
}
}
export default WxOauth;
github
https://github.com/SuperIron/wx-oauth
作者
SuperIron