Java connects to WeChat public account to publish articles

Preface

I encountered a need at work and needed to publish an article to the WeChat public account. I finally realized it by querying information and consulting WeChat development documents. WeChat development
documents: https://developers.weixin.qq.com/doc/offiaccount/Getting_Started /Overview.html

1. Preparation work

Through the preliminary preparation work, we found that if we want to realize the function of publishing articles on the WeChat official account, there are mainly three steps. 1. Upload picture materials 2. Publish the draft box 3. Publish the contents of the draft box. Of course, there is another function Implementing these three steps is to obtain the token.

1. Get token

First define the entity

package com.sinosoft.springbootplus.znts.domain.entity;
/**
 * json格式化accessToken
 * @author   mc
 * @version  1.0
 * @创建时间 2023年3月07日
 * @修改时间 2023年3月07日
 */
public class Token {
    
    
    // 接口访问凭证
    private String accessToken;
    // 凭证有效期,单位:秒
    private int expiresIn;

    public String getAccessToken() {
    
    
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
    
    
        this.accessToken = accessToken;
    }

    public int getExpiresIn() {
    
    
        return expiresIn;
    }

    public void setExpiresIn(int expiresIn) {
    
    
        this.expiresIn = expiresIn;
    }
}

Call to obtain the token's address, the required appid (credential) and appsecret (key).

 package com.sinosoft.springbootplus.znts.utils;
/**
 * 微信常量定义
 * 版权:(C) 版权所有 2015-2018 中科软科技股份有限公司
 * <功能名称>
 * <详细描述>
 * @author   mc
 * @version  1.0
 * @创建时间 2021年12月30日
 * @修改时间 2021年12月30日
 */
public class ConstantUtil {
    
    
    // 公众号开发者APPID  
    public final static String app_id = "";
    // 公众号开发者密码  
    public final static String app_secret = "";
    // 凭证获取(GET)
    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    // 获取用户openid集合
    //发布
    public final static String sendSucaiUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";

    //上传素材
    public final static String uploadUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN";

    //发布
    public final static String ufabuUrl = "https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token=ACCESS_TOKEN";

    //新增草稿
    public final static String sendtemplateUrl = "https://api.weixin.qq.com/cgi-bin/draft/add?access_token=ACCESS_TOKEN";

}

Then get the token

    /**
     * 获取接口访问凭证
     *
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static Token getToken(String appid, String appsecret) {
    
    
        Token token = null;
        String requestUrl = ConstantUtil.token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
    
    
            try {
    
    
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
    
    
                token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return token;
    }

2. Upload picture materials

The main reason for uploading pictures is that when adding a new draft box, the picture is needed as the cover, and it must be permanent, so you need to be careful not to choose the wrong interface when calling.
Insert image description here
Insert image description here

    public String uploadimg() throws IOException {
    
    

        final File file = new File("D:\\software\\3.jpg");

        RequestBody fileBody = RequestBody.create(file,okhttp3.MediaType.parse(MediaType.APPLICATION_OCTET_STREAM_VALUE));
        MultipartBody body = new MultipartBody.Builder()
                .setType(Objects.requireNonNull(okhttp3.MediaType.parse("multipart/form-data")))
                .addFormDataPart("media",file.getName(),fileBody)
                .build();
        Request request = new Request.Builder()
                .post(body)
                .url("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + CommonUtil.getToken(ConstantUtil.app_id, ConstantUtil.app_secret).getAccessToken() + "&type=image").build();
        final String string = Objects.requireNonNull(client.newCall(request).execute().body()).string();
        log.info(string);
        return string;
    }

Insert image description here
Just get the media_id after the upload is successful. It should be noted here that if the upload fails, it may be that the image contains sensitive words. You can try another photo first.

3. Add a new draft

Insert image description here

    /**
     * 新增草稿想
     * @return
     */
    public static String addDraft(String title,String author,String content){
    
    
        Object mediaId;
        String access_token = "";
        String strResult = "";
        try {
    
    
            JSONObject EventTraceInput = new JSONObject();
            access_token = CommonUtil.getToken(ConstantUtil.app_id, ConstantUtil.app_secret).getAccessToken();
            String url = ConstantUtil.sendtemplateUrl.replace("ACCESS_TOKEN", access_token);
            JSONArray EventArray = new JSONArray();
            JSONObject jsonArray = new JSONObject();
            jsonArray.put("title", title);
            jsonArray.put("author", author);
            jsonArray.put("content", content);
            jsonArray.put("thumb_media_id", "");
            jsonArray.put("need_open_comment", 0);
            jsonArray.put("only_fans_can_comment", 0);
            EventArray.add(jsonArray);
            EventTraceInput.put("articles", EventArray);
            strResult = WX_TemplateMsgUtil.sendPost(EventTraceInput, url);
            JSONObject jsonObject = JSONObject.parseObject(strResult);
            mediaId = jsonObject.get("media_id");
        }catch (Exception e){
    
    
            log.error("调用微信公众号接口出错,access_token为:【{}】,调用草稿箱接口返回值为:【{}】", access_token,strResult);
            throw new BusinessException(e.getMessage());
        }
       return mediaId.toString();
    }

Here we only need to pass in the corresponding value based on the information in the interface document. thumb_media_id is the media_id returned by uploading the permanent material in the previous step.

4.Publish articles

Publishing an article is relatively simple. You only need to upload the media_id returned by uploading the draft in the previous step. The specific code is as follows:

  /**
     * 发布
     * @return
     */
    public static String publishWx(String mediaId){
    
    
        String info="";
        String access_token="";
      try{
    
    
        access_token = CommonUtil.getToken(ConstantUtil.app_id, ConstantUtil.app_secret).getAccessToken();
        String url = ConstantUtil.sendSucaiUrl.replace("ACCESS_TOKEN",access_token);
        JSONObject jsonObject = new JSONObject();
        //素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news)
        jsonObject.put("media_id", mediaId);
        //发起POST请求
        info = WX_TemplateMsgUtil.sendPost(jsonObject, url);
      }catch (Exception e){
    
    
          log.error("调用微信公众号接口出错,access_token为:【{}】,调用发布文章接口返回值为:【{}】", access_token,info);
          throw new BusinessException(e.getMessage());
      }
       return info;
    }

Guess you like

Origin blog.csdn.net/mcband/article/details/129480182