Before development, it's better to go through the official API first, otherwise it's hard to go on. Enterprise Wechat API
Firstly, several basic concepts are introduced.
- cropid
Every enterprise has a unique cropid. To obtain secondary information, you can view the Enterprise ID under "My Enterprise" - "Enterprise Information" (which requires administrator privileges).
- userid
Each member has a unique userid, which is actually an account. You can see it in the management background - "address book" - by clicking on the details page of a member.
- Departmental id
The unique id of each department, in the management background - "Address Book" - "Organizational Structure" - can be seen by clicking on the small dot on the right of a department.
- tagid
Each tag has a unique id, in the management background - "address book" - "tag", select a tag, in the upper right corner there is a "tag details" button, you can see.
- agentid
Each application has a unique id, in the management background - "applications and small programs" - "applications", click on an application, you can see.
- appid
appid is the developer id, which is the identification code of the development. With the developer's password, the interface capability of the public number can be invoked.
- secret
Secret is the "key" for data security in enterprise applications. Each application has an independent access secret key. In order to ensure data security, secret must not be disclosed.
- access_token
Access_token is an important ticket for enterprises to get information in the background of enterprise Wechat. It is generated by cropid and secret. All interfaces need to carry this information to verify the access rights of the interface when communicating. (access_token)
Request address: https://qyapi.weixin.qq.com/c...
Returning to the front end of the result will get access_token. The result is as follows:
{
"errcode": 0,
"errmsg": "ok",
"access_token": "accesstoken000001",
"expires_in": 7200
}
First, acquiring access_token is the first step to invoke the enterprise Wechat API interface, which is equivalent to creating a login credential and other business API interfaces, which need to rely on access_token to authenticate the identity of the caller. Therefore, before using business interfaces, developers need to identify the source of access_token issuance and use the correct access_token.
Get to the point
- identity authentication
Web Authorized Login: Enterprise Wechat provides OAuth's authorized login mode, which allows users to access the identity information of members from the enterprise Wechat terminal, thus avoiding the login link. URL links in enterprise applications (including links in custom menus or message centers) can obtain UserId identity information of members through the OAuth 2.0 authentication interface.
Before entering our development project, we need to access the OAuth2 link constructed by the third party service (parameters include the identity ID of the current third party service, as well as the redirection URL) to guide the user to the authorization page of the authentication server. It is suggested that the URL links in enterprise applications should fill in the page addresses of their own enterprises directly. When the member operation jumps to the enterprise page, the enterprise background checks whether there is information identifying the identity of the member, and then enters the corresponding page according to the information obtained.
Here's how to get user information:
The first step is to construct the following links to get the code parameters. Here I post the url I constructed in my actual development.
function getToken(str) { const appId = Env.appId const redirectUrl = encodeURIComponent(`${Env.url}?str=${str||0}`) const agentId = Env.agentId window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&agentid=${agentId}&state=STATE#wechat_redirect` }
Explain what each parameter means.
appid: enterprise cropid
redirect_uri: The redirected callback link address after authorization, which is processed using urlencode
response_type: Return type, fixed to: code
scope: Application Authorization scope, Enterprise Self-built Applications Fixed Fill: snsapi_base
State: After redirection, the state parameter will be taken. Enterprises can fill in the parameter value of a-zA-Z0-9. The length should not exceed 128 bytes.
wechat_redirect: The terminal uses this parameter to determine whether it needs to carry identity information.
When an employee clicks, the page will jump to redirect_uri? Code = CODE&state = STATE, when the enterprise can get the employee's userid according to the code it gets.
The following is the landing judgment before entry:
enterWxAuthor () { //Get the user token var _this = this; var wxUserInfo = sessionStorage.getItem("userToken"); var code = GetQueryString("code"); if (!wxUserInfo) { if (code) { _this.getTokenKey(); } else { //No Micro Credit User Information, No Authorization - > Need Authorization, Jump Authorization Page getToken() } } else { //Initialization page _this.init(); } },
getTokenKey method:
getTokenKey: function () { //Get user information, token permissions var _this = this; //Obtain user token through code var url = 'api/....'; //The code here is the code parameter of the OAuth link we constructed above. var code = GetQueryString("code"); ajax(url, { WXTicket: code }, '').then(function (res) { // Remove code from url in order to avoid duplication of code if (window.history.replaceState) { window.history.replaceState('', '', window.location.href.replace( /&code=.*?(?=[&#\/])|code=.*?(?=[&#\/])&?/, '')); } else { if (/code=/.test(window.location.href)) { window.location.href = window.location.href.replace(/&code=.*?(?=[&#\/])|code=.*?(?=[&#\/])&?/, ''); } } _Set('tokenStr', res.data) if (res.data.Data) { sessionStorage.setItem('userToken', res.data.Data.Token) } _this.init() }) },
GetQueryString method:
function GetQueryString(name) { let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)') let r = window.location.search.substr(1).match(reg) if (r !== null) return unescape(r[2]) return null; }
Here we should pay attention to some problems in dealing with the micro-message terminal. Some users like to set the default font of Wechat very large, which will lead to page layout disorder. Here is the way to rewrite the font size of the page:
// Prohibit Weichat Browser from Zooming (function () { if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") { handleFontSize(); } else { if (document.addEventListener) { document.addEventListener("WeixinJSBridgeReady", handleFontSize, false); } else if (document.attachEvent) { document.attachEvent("WeixinJSBridgeReady", handleFontSize); document.attachEvent("onWeixinJSBridgeReady", handleFontSize); } } function handleFontSize() { // Set the page font to the default size WeixinJSBridge.invoke('setFontSizeCallback', {'fontSize': 0}); // Rewrite events that set page font size WeixinJSBridge.on('menu:setfont', function () { WeixinJSBridge.invoke('setFontSizeCallback', {'fontSize': 0}); }); } })();
That's the general process. To sum up, before entering the system, you should first go to the OAuth link of Wechat, get the code, and then use the code to get the token of the user.
After that, I played casually.