Ultra-detailed enterprise WeChat push (everything can be pushed)

Table of contents

1. Background

2. Enterprise WeChat registration and configuration

1. Register

2. Configuration

(1) Join the enterprise

(2) Open the WeChat plug-in

(3) Test whether you can receive messages on WeChat

3. Method 1 Send messages through self-built applications

1. Add self-built application

 2. Obtain application interface credentials (access_token)

 (1) Obtain the enterprise id (corp_id)

​Edit (2) Get the Secret of the application

(3) Get access_token

3. Configure ip whitelist and trusted domain name

(1) Configure a trusted domain name 

(2) Configure trusted ip whitelist

4. Send message

(1) Get the application id (agent_id) 

(2) Send a message

4. Method 2 Enterprise WeChat robot push

(1) Create and add robots

 (2) Send a message

V. Summary


1. Background

        Tips in the front row: The article containing the source code has been released, and with a little configuration, it can be directly pushed to   the enterprise WeChat to push the weather, class schedule, anniversary, daily sentence, etc. (including source code and detailed steps)

        Recently, I was researching and pushing the daily class schedule. At the beginning, I used the WeChat official account interface test account to push, but now the official account message display has been changed. It will not be displayed in the message list, but hidden in the "subscription account message". You can’t see it if you look carefully, and it is easy to be ignored, as shown in the following picture:

        So I have been looking for other methods, and I thought of enterprise WeChat - which can be displayed on the WeChat message homepage, and the reminder is obvious, as shown in the figure below.

 

        Effect example 

         The following two methods are described below. Note: If you want to push regularly every day, you need to have your own server, or use Alibaba Cloud function

2. Enterprise WeChat registration and configuration

1. Register

Everyone can register for Enterprise WeChat (the maximum number of people in the free version of the enterprise is 200, and the use of the api will not be affected by non-certification, which is enough for our personal use)

Website:  Enterprise WeChat (qq.com)   Registration:

At the same time, download the enterprise WeChat client on your mobile phone or computer 

2. Configuration

(1) Join the enterprise

         After successful registration, enter the management background. Let yourself and the people you want to push join the enterprise

(2) Open the WeChat plug-in

        In order to allow our corporate WeChat to be viewed directly on WeChat, we need to enable the WeChat plug-in

 ​

(3) Test whether you can receive messages on WeChat

 Being able to receive announcements on WeChat means that you have successfully entered the company and successfully used the WeChat plug-in

3. Method 1 Send messages through self-built applications

Note: The requirements for this method - have your own server and domain name (and the server ip is a fixed ip, and the domain name is filed through ICP )   

        If you do not meet the requirements, you can see method 2

1. Add self-built application

 Add it as shown below

 

 2. Obtain application interface credentials (access_token)

 This credential can have all the permissions of the application, please keep it safe, do not expose access_token and secret on the front end

 (1) Obtain the enterprise id (corp_id)

 Scroll to the bottom of this page

(2) Get the Secret of the application

 Go back to the application management page, find the self-built application we just created, click on it, and you can see the secret

 After sending, open the enterprise WeChat client (must be enterprise WeChat, not WeChat), and find the secret sent to you by the "enterprise WeChat team"

(3) Get access_token

Send a get request to https://qyapi.weixin.qq.com/cgi-bin/gettoken  , and the query parameters are the newly obtained enterprise id and application key (refer to the document  to obtain access_token - Documentation - Enterprise WeChat Developer Center (qq. com) )

 The following is an example of nodejs (note that the access_token is valid for two hours and can be cached to reduce the number of requests)

There was an error in the code of the official document, I corrected it (the request parameter name was wrongly written)


const corp_id = '';// 企业 corp_id

const secret = ''// 当前应用的 secret
// 获取的 access_token
let {data} = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corp_id}&corpsecret=${secret}`);
let {access_token}= data;
if(access_token){
    console.log('获取 access_token 成功',access_token);
}
else{
    res.render('error');
}

3. Configure ip whitelist and trusted domain name

This step is very critical, and the official document does not explain that without configuration, even with access_token, nothing can be done (this is a new regulation in June 2022, and self-built applications before that do not need these restrictions). In the application management - our self-built application interface, pull to the bottom, you can see the configuration entry.

(1) Configure a trusted domain name 

Enter the domain name that has passed the ICP record, and then click Apply for Verification  

Then the verification process will appear. After downloading the file, put it in the root directory of your domain name 

 

After placing the file, deploy it, and then click the OK button to prompt success.

(2) Configure trusted ip whitelist

Enter your server ip here  

4. Send message

(1) Get the application id (agent_id) 

In the self-built application interface, you can copy the application id

(2) Send a message

POST request, nodejs example is as follows: (In addition to text messages, you can also send pictures, cards, etc. in multiple colors, which are not introduced here one by one. For details, please refer to the official document Sending Application Messages - Documentation  - Enterprise WeChat Developer Center (qq. com) )


const agent_id = '1000063';// 自建应用的 agent_id

const access_token = 'xxxxxx';// access_token

let {data:message_data} = await axios.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`,{
      "touser" : '@all',//意思是发给所有人
      "agentid" : agent_id,
      "msgtype" : "text",//类型为文本,可以是其他的,详情可见官方文档
      "text" : {
        "content" : `Hello World!` //里面填写文本
      },
});

In the content, you can fill in the weather data you get by requesting other APIs (such as Baidu Weather API), or you can enter your own data (such as class schedule)

Parameter list: placed in the request body

4. Method 2 Enterprise WeChat robot push

If your server ip is not fixed, the above method is not suitable for you (because you need to configure the ip whitelist)

The method described below can be applied to everyone -  if you do not have your own server, you can use Alibaba Cloud functions to send push

(1) Create and add robots

Open the enterprise WeChat mobile client   , enter the all-staff group (as long as you join the enterprise, you will automatically enter this group), click the upper right corner to enter the details, and select "group robot"

 

Then enter, click "Add" in the upper right corner, and then click "New" in the upper right corner after entering, and then enter the robot name to create a new robot. After the establishment is successful, a Webhook address will be given to you, keep it safe and do not disclose it  , and then add it to the group

 

 (2) Send a message

Send a post request to the webhook address just now, and put the required parameters in the body

The following is a code example of nodejs sending a text message (the key of the code below is included in the Webhook just given to you)

robot: async (content) => {//参数为内容
            return new Promise(async (resolve, reject) => {
                try {
                    const params = {
                        method: 'POST',
                        url: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxx`,//在这里填你的key
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        data: JSON.stringify({//携带的数据
                            "msgtype": "text",
                            "text": {
                                content,
                            }
                        }),
                    }
                    const { data } = await axios(params)
                    if (data.errcode == 0) {
                        resolve(data)
                    } else {
                        reject(data.errmsg || '发送失败')
                    }

                } catch (error) {
                    reject(error.message || error)
                }
            })

        },

In addition to text messages, you can also send a lot of things. For details, please refer to the official document  Group Robot Configuration Instructions- Documentation- Enterprise WeChat Developer Center (qq.com)

V. Summary

        The above describes how to push, and you can use the pushed content by yourself (weather, class schedule, good morning greetings, daily pictures, etc.)

        If you don’t have the funds to buy your own server, you can try to use vercel (free) + the domain name you purchased yourself (new users can buy it for a few dollars for a year). You can search for other content by yourself about the use of vercel (Note: vercel cannot use scheduled tasks , because the cloud function will only run when it is requested, you can use GitHub Actions to periodically request the cloud function on vercel)

        If there is still something you don’t understand, you can ask me in the comment area. If there is any mistake, please let me know in time. Thank you~ 

Guess you like

Origin blog.csdn.net/m0_64130892/article/details/128533639