文档链接: https://developers.weixin.qq.com/doc/offiaccount/Publish/Get_article_from_id.html
通过微信公众号提供的API接口https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token=ACCESS_TOKEN获取已发布的所有文章
如果需要每篇文章的详情用返回的article_id调取接口即可
具体实现
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/getWxArticle")
public class Wx extends BaseController {
private static final String APP_ID = ""; // 换成自己的公众号的AppID
private static final String APP_SECRET = ""; // 换成自己的公众号的AppSecret
private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/";
private static final String ACCESS_TOKEN_URL = API_URL + "token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET; // 获取access_token
private static final String ARTICLELiST_URL = API_URL + "freepublish/batchget?access_token="; //获取成功发布文章的列表
/**
* 获取微信公众号发布的文章,用于互联网+作展示
*/
@GetMapping()
public R<JSONArray> getArticleList() {
// 获取ACCESS_TOKEN
String accessToken = getAccessToken();
// 获取文章列表信息
JSONArray articles = getArticles(accessToken);
JSONArray articleList = new JSONArray();
articles.forEach(item -> {
JSONObject wz = new JSONObject();
JSONObject article = (JSONObject) item;
JSONObject content = article.getJSONObject("content");
JSONObject newsItem = content.getJSONArray("news_item").getJSONObject(0);
wz.put("title", newsItem.getStr("title"));
wz.put("url", newsItem.getStr("url"));
wz.put("createTime", content.getStr("create_time"));
articleList.add(wz);
});
return R.ok(articleList);
}
private static String getAccessToken() {
String response = HttpUtil.get(ACCESS_TOKEN_URL);
JSONObject json = new JSONObject(response);
return json.getStr("access_token");
}
private static JSONArray getArticles(String accessToken) {
JSONObject params = new JSONObject();
params.put("offset", 0);
params.put("count", 20);
String response = HttpUtil.post(ARTICLELiST_URL + accessToken, params.toString());
JSONObject json = new JSONObject(response);
return json.getJSONArray("item");
}
}