Analysis of WeChat official account subscription development process

Official documents: https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html

1. Login official account management platform: advertising and service template news

Here, you need to add a "message template" (here you need to get the template id), and view the "template message interface document". You can do background development according to the document.

When there is no suitable template in the template library, you need to create a new template yourself. The waiting period for approval is a little long, 7-15 days, so you need to apply for a template in advance

2. Prerequisites:

(1) users should pay attention to your WeChat official account.

(2) You have the openId of the user

3. How to determine who to send to?

(1) If you have related members, such as questions, that need to be sent to the technical experts in the field of the question to answer, you can directly take the users of the related technical experts in the field to traverse and send the subscription message

(2) What if there are no relevant members, such as information or daily questions?

  1. You can place the WeChat official account's two-dimensional code on the page, allowing users to scan the code.

  2. Scan code enters official account, automatically reply to quick link after attention.

  3. Click the subscription database daily question to enter the daily question page and click the give button to subscribe (after subscribing, you can store the subscribed users in the table and get them when sending the subscription message)

4. Specific development steps:

(1) Controller layer: declaration interface

@ApiOperation("Send a daily wechat reminder")
@PreAuthorize("hasRole('sys')")
@PostMapping("/dailys/{dailyId}/remind")
public OperationInfo remindDaily(@PathVariable Integer dailyId) throws EmcsCustomException {
  dailyService.sendWxRemind(dailyId);
  return OperationInfo.success("Sending subscription message succeeded");
}

(2) Asynchronously traverse subscribers and send message reminders

@Async
public void sendWxRemind(Integer dailyId) throws EmcsCustomException {
  ......   //Get subscriber   List<User> users = getSubscribedUsers();   if (users == null || users.isEmpty()) {     log.error("Daily question subscriber is empty");     return;   }   users.forEach(user-> {     wxService.sendLessonRemind(user, "The daily question is updated", title, startTime, "Click to view or unsubscribe", null, pagePath);   }); }

(3) How to send, just look at the document, such as this

public void sendEventStartRemind(User user, String title, String name, String time, String comment, String url) {
  ......
  requestBody.put("template_id", "Template for step 1 ID");
  requestBody.put("url", url);
  requestBody.put("data", data);

  String accessToken = getAccessToken(WxPublicConfig.getInstance()).getAccess_token();
  wechatApi.sendPublicTemplateMessage(accessToken, requestBody);
}

What is more important here is the template id in the first step and the acquisition of accessToken. There are also documents

    /**
     * Get WeChat token, official account, open number, small program
     */
    private WxTokenVO getAccessToken(IWxConfig config) {
        WxTokenVO token = wechatApi.getAccessToken(config.getAppID(), config.getAppSecret());
        if (token.getErrcode() != null && token.getErrcode() != 0) {
            log.error("Get wechat account token abnormal: {}, code: {}, message: {}", config.getAppID(), token.getErrcode(), token.getErrmsg());
        }
        log.info("obtain{}token: {}", config.getAppID(), JSON.toJSONString(token));
        return token;
    }

The following is to do the corresponding things with the interface provided by wechat requested by OpenFeign according to the document, such as:

@FeignClient(name = "wechatApi", url = "https://api.weixin.qq.com")
public interface WechatApi {
    /**
     * Obtain wechat account access token, public account, open account and applet account
     * https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
     */
    @RequestLine("GET /cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}")
    WxTokenVO getAccessToken(@Param("appId") String appId,
                             @Param("appSecret") String appSecret);/**
     * Send WeChat official account template message
     * https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
     */
    @RequestLine("POST /cgi-bin/message/template/send?access_token={accessToken}")
    @Body("body")
    void sendPublicTemplateMessage(@Param("accessToken") String accessToken, JSONObject body);
}

5. Receive wechat server return

If you need to receive the return from the wechat server, then you need to fill in this callback address according to whether the message is sent successfully, and then do some related business.

On wechat public management platform: setting and development - basic configuration - server configuration, here to configure the callback address

See the official documents for details: https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

Posted by BenInBlack on Mon, 18 Apr 2022 22:23:07 +0930