Record the development record of wechat public account once

Wechat public number development is relatively simple, to write back and forth several times, there has been no detailed record, resulting in each write or check the document, now the development experience is recorded, in case of need.

  • The following tripartite SDK is introduced in the POM.xml file
<! -- Third-Party SDK of wechat public account -->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>wx-java-mp-spring-boot-starter</artifactId>
    <version>3.5.0</version>
</dependency>
Copy the code

Wechat development Java SDK (development kit), the official website has support including wechat payment, open platform, small program, enterprise wechat/enterprise NUMBER SDK, it is easy to use!!

  • Application. Yml configuration
# Public id configuration (required)
wx:
  mp:
    appId: APPID        # AppID of wechat official account
    secret: SECRET      # Wechat official account app corpSecret
    token: TOKEN        # token of wechat public account
    aesKey: AESKEY      # EncodingAESKey
Copy the code

Redirect for wechat web page authorization to get user information and redirect back

  • Train of thought
1. Provide a front redirect entry with a redirect_URL parameter on the URL (representing the page to be redirected back after obtaining user information from wechat), and jump to wechat for webpage authorization. 2. Obtain the code after the authorization succeeds. 3. Obtain the OpenID and access_token through code to adjust wechat interface. 4. Obtain user information. 5. Finally redirect back to the original redirect_URL and spell the desired parameters.Copy the code
  • implementation
1. First, provide an entrance for the front section to be redirected, and the URL carries a redirect_URL parameter (representing the page to be redirected back after obtaining the user information from wechat), and then jump to wechat for webpage authorization.Copy the code
  • Pay attention to

    Redirect_url needs to pass through URLEncoder, and then URLDecoder, otherwise redirect_URL after # will be lost.

    It is best to do two URLEncoder and two URLDecoder, because some browsers will automatically decode.

// Address returned after wechat authorization
private String getCodeUrl = Project Domain name + "redirect/code? redirect_url=";

// The default redirection address defaultUrl
private String defaultUrl = "[DEFAULT_URL]";

// Provides the address of the redirection entry to get user information
@GetMapping("/redirect")
public String redirect(
        @RequestParam(name = "redirect_url", defaultValue = "", required = false) String redirectUrl
) throws UnsupportedEncodingException {

    // The default redirection address defaultUrl
    if (StringUtils.isBlank(redirectUrl)) {
        redirectUrl = defaultUrl;
    } else {
        redirectUrl = URLDecoder.decode(redirectUrl, "utf-8");
        LOGGER.info("Once decode: {}",redirectUrl);
        redirectUrl = URLDecoder.decode(redirectUrl, "utf-8");
        LOGGER.info("Secondary decoding: {}",redirectUrl);
    }
    
    LOGGER.info("redirectUrl:{}",redirectUrl);
    
    // Encode once
    redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
    LOGGER.info("Once encoded URL :{}",redirectUrl);
    // Secondary encoding
    redirectUrl = URLEncoder.encode(getCodeUrl + redirectUrl, "utf-8");
    LOGGER.info("Secondary encoding URL :{}",redirectUrl);
    // Finally get wechat authorized address
    String url = wxMpService.oauth2buildAuthorizationUrl(redirectUrl,"snsapi_userinfo"."123");
    LOGGER.info("Finally get wechat authorized address :{}",url);
    // Redirect authorization
    return "redirect:" + url;
}
Copy the code
2. Obtain the code after the authorization succeeds. 3. Obtain the OpenID and access_token through code to adjust wechat interface. 4. Obtain user information. 5. Finally redirect back to the original redirect_URL and spell the desired parameters.Copy the code
  • Now complete steps 2, 3, 4 and 5

    We need to define a connection, namely the getCodeUrl in the previous step, which will be redirected to this link with code parameters after wechat authorization is successful.

    Since we encoded redirect_URL twice in the previous step, redirect_URL is also passed in.

// errorPage errorPage
private String errorPage = "[ERROR_PAGE]";

// The address here is redirected by wechat with the obtained code parameter.
@GetMapping("/redirect/code")
public void getCode(
        @RequestParam(name = "redirect_url", defaultValue = "", required = false) String redirectUrl,
        @RequestParam(name = "code", defaultValue = "", required = false) String code,
        HttpServletRequest request,HttpServletResponse response
) throws IOException {
    LOGGER.info("redirect_url: {}", redirectUrl);
    LOGGER.info("code: {}", code);
    if (StringUtils.isBlank(code)) {
        LOGGER.error("Failed to get code");
        LOGGER.info("Redirect to errorPage, errorPage: {}",errorPage);
        response.sendRedirect(errorPage + "? error=code-is-null");
    }
    // Decode the redirect address
    redirectUrl = URLDecoder.decode(redirectUrl, "utf-8");

    LOGGER.info("Decode redirect address URL :{}",redirectUrl);

    // Obtain wechat information according to code
    try {
        // Obtain openID and access_token according to code
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);

        // Get wechat user information
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMpOAuth2AccessToken.getOpenId());
        LOGGER.info("userInfo:{}",wxMpUser.toString());
    } catch (WxErrorException e) {
        e.printStackTrace();
        LOGGER.info("Redirect to errorPage, errorPage: {}",errorPage);
        response.sendRedirect(errorPage + "? error=" + e.getMessage());
    }

    // Encode wechat user information directly and redirect it to the original redirect_URL
    response.sendRedirect(redirectUrl + "? wechat_user=" + URLEncoder.encode(wxMpUser.toString(), "utf-8"));
}
Copy the code

Wechat template message push

Wechat template message push is also relatively simple, the core code is only the following few lines, the most important acquisition of user OpenID has been mentioned above, I will not repeat it here.

public String push(a) throws Exception {

    // Push a message
    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
            .toUser("[OPENID]")         // The user openID to push
            .templateId("[TEMPLATEID]") / / template id
            .url("[URL]")               // Click the url to which the template message will go
            .build();

    templateMessage.addData(new WxMpTemplateData("first"."[title]"."[COLOR]"));
    templateMessage.addData(new WxMpTemplateData("keyword1".[Message body]."[COLOR]")); .// Keywordn is specified by the template
    
    templateMessage.addData(new WxMpTemplateData("remark"."[note]"."[COLOR]"));
    
    // Start pushing
    try {        
        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);

        return "true";
    } catch (WxErrorException e) {
        System.out.println("Push failed:" + e.getMessage());
        e.printStackTrace();
        WxError wxError = e.getError();
        if ("43004".equals(wxError.getErrorCode())){
            throw new Exception("The user does not follow the public account");
        }
        throw newException(wxError.getErrorMsg()); }}Copy the code
reference

www.cnblogs.com/hebaibai/p/…

Developers.weixin.qq.com/community/d…