I’m participating in nuggets Creators Camp # 4, click here to learn more and learn together!

Dear, hello, everyone. I am “Front-end Xiaoxin”. 😇 has been engaged in front-end development and Android development for a long time


In the team’s internal knowledge sharing meeting on 18th yesterday, colleagues shared in detail the enterprise micro robot they had done for team engineering recently. The main reason was that they spent a lot of time every day dealing with Merge or searching for colleagues. In order to optimize the time, our colleague uses NodeJs development service to connect the worker bee platform and enterprise micro platform, so as to automatically send and remind corresponding colleagues to do code review, and inform initiators to complete the merger after the review is passed.

So what do I want to do?

Before, I wrote an article “[Serverless Version] Development of Enterprise micro group Robots”, which is mainly to inform enterprise micro robot by taking the initiative to resolve the request regularly. This time, I want to use Tencent cloud function to do the service of opening up Github to enterprise Micro message notification, so as to further expand our understanding of cloud function. So let’s do it.

In this case, we need to prepare to create GitHub demonstration project, Tencent cloud function and an enterprise micro robot. When a user adds a comment, it can inform the management of enterprise micro group.

Configure Webhooks for the demo project:

The Github project in the demo is self-created without requiring Webhook to send a POST request to our pre-configured URL interface when a specified event occurs.

  1. Menu location: Demo project /Settings/Webhooks;
  2. Click Add Webhook to start the configuration;
  3. The configuration information includes:
    • Request address, can wait to create a good cloud function after configuration;
    • Content format: select the most common Json data transmission;
    • Security key: Configures a random key with a length of 32 bits. The key can be generated by the tool and used for data verification by the cloud function.
    • Select events: checkLet me select individual events.chooseIssue comments.
  4. Event document:webhook-events-and-payloads

Developing cloud functions:

Create a cloud function:

This time we will create a cloud function based on the template to save time, selectExpress framework template, we specify the function name as [github- webhook-issues-Comments] to distinguish it from its existing functions.

Check service connectivity:

/logo route /user route /user/: ID route /404 route /500 route /user/:id route /404 route /500 route In addition to keeping the default route to check whether the service is normal, we can consider deleting other routes.

If you open the home page and see “Welcome to Express.js application Tencent Cloud Serverless provides services for you”, the service has started normally.

Configuring /Webhook routing:

  1. We booked the route as/webhook, the mode of receiving requests isPOST, the format of the received content isJSONAt this time, we can go to GitHub Webhook to fill in the information.

  1. Add/Webhook routing through the cloud editor, the specific implementation is not done for the moment, we want to submit Issues on Github once to verify the connectivity.
    app.post(`/webhook`.(req, res) = > {
      res.send({code: 200});
    });
    Copy the code

    View the request logs on Github:

Implementing /Webhook routing:

  1. For debugging (local) convenience, we’d better download the cloud code and write it in the local VSCode, and then pull the code throughnodemon ./app.jsStart the service. The default service port is9000And in the cloud function is not allowed to change, this need to pay special attention;

  1. Remember when we configured the Webhook configuration security key on Github? To keep the data secure, we need to use the same key in the cloud functions to verify the validity of the data (GitHub documentation).

    app.post(`/webhook`.(req, res) = > {
      const signature = req.headers["x-hub-signature-256"];
      if (signature) {
        const payload = req.body;
        const ret = verify(signature, payload);
        // Output validation structure
        console.log("[ ret ] >", ret);
      }
      res.send({ code: 200 });
    });
    Copy the code
    const crypto = require("crypto");
    const SECRET_TOKEN = "";
    
    function sign(data) {
      return `sha256=${crypto
        .createHmac("sha256", SECRET_TOKEN)
        .update(JSON.stringify(data))
        .digest("hex")}`;
    }
    
    module.exports = {
      verify: (signature, data) = > {
        const sig = Buffer.from(signature);
        const signed = Buffer.from(sign(data));
        if(sig.length ! == signed.length) {return false;
        }
        returncrypto.timingSafeEqual(sig, signed); }};Copy the code

    Description:

    • Because encryption and decryption is rarely done, the 16-bit secret key set at the beginning makes the two encryption results are not the same, it takes a long time, so pay attention to the need to set at least 32 bits of the secret key, XD can explain the understanding of this piece 😘.
    • The secret keys are recommended to be stored in server environment variables rather than directly in code.
  2. Consult the Github documentation to determine the fields for which we need to assemble information. I will put the code below without explaining the fields. More fields can be found in the documentation:

    packaging: (issue, comment, repository, sender) = > {
        return '** has a new comment ** : \n user [${sender.login}] (${sender.html_url}) in [[${issue.title}] (${issue.html_url}) a new comment was added under the theme "[${comment.body}] (${comment.html_url}), please pay attention! <font color="info">[${repository.name}] (${repository.html_url}</font> <font color="comment">${comment.updated_at}</font>\n
        `;
    },
    Copy the code
  3. Again modified/Webhook routing, support to send messages to the enterprise micro robot, enterprise micro robot configuration and send please see the last article “[Serverless version] enterprise micro group robot development”, the source code lost, the cloud code need can leave a message contact:

    if (verify(signature, payload)) {
      const { action, issue, comment, repository, sender } = payload;
      if (action === "created") {
        constcontent = packaging(issue, comment, repository, sender); notice.requestMDNotice(config.ENTERPRISE_WECHAT_ROBOT_WEB_HOOK, { content, }); }}Copy the code

    We can receive the following card information in the enterprise Micro:

Steps to synchronize local code to the cloud:

  1. Select the local code root folder:

  2. Click Deploy to upload:

  3. Code deployment uploaded:

  4. Inconsistency detected with current deployment needs to be republished:

  5. After creating Issuse on Github, you can query the correct feedback through the cloud log:

Conclusion:

We configure WebHook on Github to listen to the event of Issuse comments. When the event occurs, the message will be sent to the Cloud function created by us in a fixed format. After verifying the validity of the data, the message will be analyzed and the card will be assembled and forwarded to the enterprise micro robot. Encountered in the development of rarely used Hmac256 encryption delay the longest, due to the secret key length is not enough. Do not know this article cloud function development has spoken clearly? 🤔


Welcome to follow my public account “Front-end Xiaoxin students”, the first time to push original technical articles.