SoFunction
Updated on 2024-10-30

nodejs development enterprise wechat third-party application tutorials

Recently, the company to develop enterprise WeChat Worktile, previously done is the enterprise WeChat internal application, so only applies to private deployment of customers, and for the public cloud customers can not be used, all ready to develop enterprise WeChat third-party applications, this article mainly introduces in the research stage of the encountered mountainous delicacies.

Before development you need to register as a third-party service provider, and then use the account of the third-party service provider to create the application, after the creation of only the administrator needs to authorize the application, the third-party service provider can provide services to users.

I. Registration of a third hair service provider

Log in to the official website of the service provider, register as a service provider, and log in to the service provider management background.

II. Configuring development information

Before creating the application, first configure the generic development parameters

When filling in the system event receiving url, you have to respond correctly to the request of enterprise WeChat verification url. You can refer to the background of enterprise WeChat, the api setting for receiving message of self-built application.

In the administrator background of the enterprise, enter the target application that needs to be set up to receive messages, and click the "Set API Receive" button of "Receive Messages" to enter the configuration page.

Requires the URL, Token, and EncodingAESKey of the application.

  • URL is the access protocol and address for the enterprise backend to receive enterprise WeChat push requests, supporting http or https protocol (https is recommended to improve security).
  • Token can be filled in arbitrarily by the enterprise and used to generate a signature.
  • EncodingAESKey is used for message body encryption and is a Base64 encoding of the AES key.

 2.1 Validating url validity

When Save is clicked, Enterprise WeChat generates a get request to the filled-in url

For example, the url is set to , Enterprise WeChat will send the following verification request:

Request Address:/?msg_signature=ASDFQWEXZCVAQFASDFASDFSS×tamp=13500001234&nonce=123412323&echostr=ENCRYPT_STR

parameters clarification
msg_signature The enterprise WeChat encrypted signature, msg_signature, combines the token filled in by the enterprise, the timestamp and nonce parameters in the request, and the encrypted message body.
timestamp timestamp
nonce random number
echostr Encrypted string. Need to decrypt the message content plaintext, after decryption there are four fields: random, msg_len, msg, receiveid, where msg is the message content plaintext.

2.1.1 Checking the request with the parameter msg_signature

First, we need to sha1 encrypt the token, timestamp, nonce, and msg_encrypt that we just randomly generated during configuration. Here, we can use the npm module to sha1 encrypt the token, and then we can determine whether the str we get is equal to the msg_signature.

function sha1(str) {
 const md5sum = ('sha1');
 (str);
 const ciphertext = ('hex');
 return ciphertext;
}
function checkSignature(req, res, encrypt) {
 const query = ;
 ('Request URL: ', );
 const signature = query.msg_signature;
 const timestamp = ;
 const nonce = ;
 let echostr;
 ('encrypt', encrypt);
 if (!encrypt) {
  echostr = ;
 } else {
  echostr = encrypt;
 }
 ('timestamp: ', timestamp);
 ('nonce: ', nonce);
 ('signature: ', signature);
 // Sort the token/timestamp/nonce parameters into dictionary order.
 const tmpArr = [token, timestamp, nonce, echostr];
 const tmpStr = sha1(().join(''));
 ('Sha1 String: ', tmpStr);
 // Verify that the sorted and encrypted string is equal to the signature.
 if (tmpStr === signature) {
  // Returns the contents of the echostr parameter as is.
  const result = _decode(echostr);
  ('last', result);
  ('Check Success');
  return result;
 } else {
  ('Check Failed');
  return 'failed';
 }
}

2.1.2 Decrypt echostr to get msg and return it

Ciphertext decryption process:

Perform base64 decoding of the AESKey just generated

const EncodingAESKey = '21IpFqj8qolJbaqPqe1rVTAK5sgkaQ3GQmUKiUQLwRe';
let aesKey = (EncodingAESKey + '=', 'base64');

aes-256-cbc decryption of AESKey

function _decode(data) {
 let aesKey = ('21IpFqj8qolJbaqPqe1rVTAK5sgkaQ3GQmUKiUQLwRe' + '=', 'base64');
 let aesCipher = ("aes-256-cbc", aesKey, (0, 16));
 (false);
 let decipheredBuff = ([(data, 'base64'), ()]);
 decipheredBuff = PKCS7Decoder(decipheredBuff);
 let len_netOrder_corpid = (16);
 let msg_len = len_netOrder_corpid.slice(0, 4).readUInt32BE(0);
 const result = len_netOrder_corpid.slice(4, msg_len + 4).toString();
 return result; // Returns a decrypted plaintext -
}
function PKCS7Decoder (buff) {
 var pad = buff[ - 1];
 if (pad < 1 || pad > 32) {
  pad = 0;
 }
 return (0,  - pad);
}

Then you can return the result

(result);

2.2 Callback url validation failure issues

When verifying URLs, the problem of failed URL verification is often encountered, and the solution is to use the WeChat Enterprise No. interface debugging tool

III. Creating applications

IV. Testing applications

After the application is created successfully, the service provider can authorize 10 test companies

When initiating authorization from the Enterprise WeChat App Marketplace, Enterprise WeChat gives the app just now the setting of theCommand callback url Send a post request, for example:

/worktile?msg_signature=b99605616153ffbfbe6ebbb500bd211e67ed714d&timestamp=1551076894&nonce=1551709703 , just return success directly.

The callback of each event, the service provider must return the string "success" directly after receiving the push, if the return value is not "success", the enterprise WeChat will treat the return content as an error message.

('/worktile', function (req, res) {
 ('', );
 ('success');
});

Test Application Notes

  1. The enterprise WeChat account used for the installation test needs to be registered by the service provider, and each application supports adding 10 test enterprise WeChat accounts at the same time.
  2. The enterprise WeChat account installed for testing uses the current application configuration information, and subsequent modifications will not be synchronized; if you need to update the application information, please re-authorize the installation
  3. The same enterprise WeChat account, does not support the simultaneous installation of test applications and officially released applications

V. Application on-line

For service providers who have certified Enterprise WeChat, you can go to Application Management - click Submit Online - check the application - submit online.

VI. User web authorization login

6.1 Constructing Third-Party Application Web Authorization Links

If the third-party application needs to carry the user's identity information in the opened web page, the first step is to construct the following link to get the code:

/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

parameters necessarily clarification
appid be Third-party application id (i.e., suite_id at the beginning of ww or wx). Note that unlike enterprise web authorization logins
redirect_uri be The address of the callback link for post-authorization redirection, please use urlencode to process the link, and note that the domain name needs to be set to the trusted domain name of the third-party application.
response_type be The return type, at this point, is fixed to: code
scope be Application authorization scopes. snsapi_base: silent authorization, can get the member's base information (UserId and DeviceId); snsapi_userinfo: silent authorization, can get the member's detailed information, but does not contain sensitive information such as cell phone, email, etc.; snsapi_privateinfo: manual authorization, can get the member's details, including sensitive information such as cell phone and email.
state clogged After the redirection, the state parameter will be brought along, the enterprise can fill in the parameter value of a-zA-Z0-9, the length should not exceed 128 bytes
#wechat_redirect be The terminal uses this parameter to determine whether it needs to bring identity information or not

After the enterprise employee clicks it, the page will jump to redirect_uri?code=CODE&state=STATE, and the third-party application can get the corpid and userid of the enterprise employee based on the code parameter. code length is up to 512 bytes.

6.2 Obtaining the identity of the accessing user

Request method: GET (HTTPS)

Request address: /cgi-bin/service/getuserinfo3rd?access_token=SUITE_ACCESS_TOKEN&code=CODE

parameters necessarily clarification
access_token be suite_access_token for third-party applications, see the"Obtaining third-party application credentials"
code be The maximum size of the code obtained through member authorization is 512 bytes. The code will be different for each member authorization. The code can only be used once and will expire after 5 minutes of non-use.

 6.2.1 Getting the suite_access_token of a third-party application

Request method: POST (HTTPS)

Request address: /cgi-bin/service/get_suite_token

parameters compulsory clarification
suite_id be Apply ids beginning with ww or wx (corresponds to the old suite ids beginning with tj)
suite_secret be Application secret
suite_ticket be Enterprise WeChat background push ticket

Because third-party service providers may host a large number of enterprises, the impact of their security issues will be more serious, so in addition to the legitimate source IP verification in the API, additional suite_ticket as a security credentials.

To get the suite_access_token, you need the suite_ticket parameter. suite_ticket is pushed by the enterprise WeChat backend to the "Command Callback URL" at regular intervals, and is updated every 10 minutes, see "Push".suite_ticket

The suite_ticket is actually valid for 30 minutes, which is tolerant of two consecutive failed attempts to get a suite_ticket, but always use the latest received suite_ticket.

The suite_access_token obtained through this interface is valid for 2 hours, developers need to cache it and cannot obtain it frequently.

6.2.2 Getting a push suite_ticket

The enterprise WeChat server pushes out tickets at regular intervals (every ten minutes). tickets change in real time and are used for subsequent interface calls.

Request method: POST (HTTPS)

Request address: /worktile?msg_signature=87276aaf15a13e1eb2ebb6d93732ca668c3ddef8&timestamp=1551850300&nonce=1551051655

In the event of authorization, address book change, ticket change, etc., the enterprise WeChat server will push the corresponding event message to the application's "command callback URL". nodejs receives the xml, parses it to get the encrypt field, and then decrypts it with the and then use the decryption method used to configure the url for the generic development parameters above to get the suite_ticket.

6.3 Access to sensitive user information

Request method: POST (HTTPS)

Request address: /cgi-bin/service/getuserdetail3rd?access_token=SUITE_ACCESS_TOKEN

{
  "user_ticket": "USER_TICKET"
}

parameters necessarily clarification
access_token be The suite_access_token of the third-party application, see "Obtaining Third-Party Application Credentials".
user_ticket be membership note

Returns results:

{
  "errcode": 0,
  "errmsg": "ok",
  "corpid": "wwxxxxxxyyyyy",
  "userid": "lisi",
  "name": "Li Si.",
  "mobile": "15913215421",
  "gender": "1",
  "email": "xxx@",
  "avatar": "/bizmp/xxxxxxxxxxx/0",
  "qr_code": "/wwopen/userQRCode?vcode=vcfc13b01dfs78e981c"
}

VII. Successful user authorization

home page (of a website)

detail page

VIII. Sending messages to users

We can give push text, image, video, file, graphic and other types.

Request method: POST (HTTPS)

Request address: /cgi-bin/message/send?access_token=ACCESS_TOKEN

The push requires an access_token and the agentId of the application, a third-party service provider, which can be accessed via the interfaceObtaining Enterprise Authorization InformationGetting the value of this parameter can actually be done directly through theGet Enterprise Perpetual License Code Fetch both values directly.

After we test and install the app successfully, Enterprise WeChat will post a request to the command callback URL, which can be parsed to the auth_code in the xml by decrypting it in the above manner

and then through/cgi-bin/service/get_permanent_code?suite_access_token=SUITE_ACCESS_TOKEN cap (a poem)auth_code You can get the access_token and agentId, the returned agent is an array, but only the old multi-application suite authorization will return more than one agent, for the new single-application authorization, only one agent will always be returned.

With the access_token and agentId, you can happily send messages to your users.

When clicking on the link, you can jump to a specific task or schedule, etc., only to return to the enterprise WeChat messaging module, and can not automatically open the third-party application, the customer service reply does not support to do so.

IX. Precautions

The api may be time-sensitive, and any discrepancies are referred to asOfficial apiprevail.

Full demo

This is the whole content of this article.