Spring?Boot?結(jié)合?WxJava?實(shí)現(xiàn)文章上傳微信公眾號(hào)草稿箱與群發(fā)
Spring Boot 結(jié)合 WxJava 實(shí)現(xiàn)文章上傳微信公眾號(hào)草稿箱與群發(fā)
在數(shù)字化營(yíng)銷與內(nèi)容傳播日益重要的今天,微信公眾號(hào)已成為企業(yè)和個(gè)人進(jìn)行信息發(fā)布與推廣的重要平臺(tái)。對(duì)于開發(fā)者而言,通過代碼實(shí)現(xiàn)自動(dòng)化的文章管理操作,如上傳文章到草稿箱、群發(fā)文章等,能夠極大提高工作效率。本文將詳細(xì)介紹如何使用 Spring Boot 框架結(jié)合 WxJava 開發(fā)工具包,實(shí)現(xiàn)文章上傳到微信公眾號(hào)草稿箱以及群發(fā)功能。
一、項(xiàng)目環(huán)境準(zhǔn)備
1.1 開發(fā)環(huán)境
JDK:建議使用 JDK 1.8 及以上版本,以確保與 Spring Boot 和 WxJava 的兼容性。
IDE:推薦使用 IntelliJ IDEA 或 Eclipse,兩者都對(duì) Spring Boot 項(xiàng)目有良好的支持。
Maven:用于項(xiàng)目依賴管理和構(gòu)建,版本建議在 3.6 以上。
1.2 微信公眾號(hào)準(zhǔn)備
在開始開發(fā)前,需要提前準(zhǔn)備好微信公眾號(hào)的相關(guān)信息:
公眾號(hào) AppID:用于唯一標(biāo)識(shí)你的公眾號(hào),在微信公眾平臺(tái)后臺(tái)的 “開發(fā) - 基本配置” 中獲取。
公眾號(hào) AppSecret:與 AppID 配合使用,用于獲取接口調(diào)用憑證(access_token),同樣在 “開發(fā) - 基本配置” 中查看。
IP 白名單設(shè)置:為保證接口調(diào)用的安全性,需要將服務(wù)器的 IP 地址添加到微信公眾平臺(tái)后臺(tái)的 “開發(fā) - 基本配置 - IP 白名單” 中。
二、Spring Boot 項(xiàng)目搭建
2.1 創(chuàng)建 Spring Boot 項(xiàng)目
可以通過 Spring Initializr(https://start.spring.io/)快速創(chuàng)建一個(gè) Spring Boot 項(xiàng)目,在創(chuàng)建過程中選擇以下依賴:
Spring Web:用于構(gòu)建 Web 應(yīng)用,方便后續(xù)編寫接口進(jìn)行功能測(cè)試。
Lombok:簡(jiǎn)化 Java 代碼,通過注解自動(dòng)生成 getter、setter、構(gòu)造函數(shù)等。
2.2 添加 WxJava 依賴
在項(xiàng)目的pom.xml文件中添加 WxJava 相關(guān)依賴:
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>4.7.0</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version> <!-- or latest version -->
</dependency>WxJava 是一個(gè)優(yōu)秀的微信開發(fā) Java 工具包,weixin-java-mp模塊專門用于微信公眾號(hào)開發(fā)。然后這里發(fā)現(xiàn)還引入了jsoup,這肯定是大有用處,可接著看后續(xù)的內(nèi)容。
三、配置微信公眾號(hào)信息
在 Spring Boot 項(xiàng)目中,創(chuàng)建一個(gè)配置類用于加載微信公眾號(hào)的 AppID 和 AppSecret 等信息。例如,創(chuàng)建WeChatConfig.java:
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WeChatConfig {
@Value("${wechat.mp.appId}")
private String appId;
@Value("${wechat.mp.appSecret}")
private String appSecret;
@Bean
public WxMpService wxMpService() {
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
return wxMpService;
}
@Bean
public me.chanjar.weixin.mp.config.WxMpConfigStorage wxMpConfigStorage() {
me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl wxMpConfigStorage = new me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl();
wxMpConfigStorage.setAppId(appId);
wxMpConfigStorage.setSecret(appSecret);
return wxMpConfigStorage;
}
}同時(shí),在application.properties或application.yml文件中添加微信公眾號(hào)的配置信息:
wechat.mp.appId=your_app_id wechat.mp.appSecret=your_app_secret
將your_app_id和your_app_secret替換為實(shí)際獲取到的公眾號(hào) AppID 和 AppSecret。
四、實(shí)現(xiàn)文章上傳到草稿箱
4.1 定義文章實(shí)體類
創(chuàng)建一個(gè) Java 類用于表示微信公眾號(hào)文章,例如WeChatArticle.java:
import lombok.Data;
@Data
public class WeChatArticle {
private String title;
private String content;
private String author;
// 其他文章屬性,如封面圖片URL等可根據(jù)需求添加
}該類定義了文章的基本屬性,如標(biāo)題、內(nèi)容和作者,可根據(jù)實(shí)際需求擴(kuò)展更多屬性。
4.2 編寫上傳草稿箱代碼
創(chuàng)建一個(gè)服務(wù)類,如WeChatArticleService.java,用于實(shí)現(xiàn)上傳文章到草稿箱的邏輯:
這里要特別注意,由于微信有些html標(biāo)簽不支持,所以需要將文章內(nèi)容復(fù)制到專門的微信markdown編輯器中格式化后,在從編輯器復(fù)制出html出來,然后在通過代碼上傳。
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMassArticle;
import me.chanjar.weixin.mp.bean.material.WxMpMassArticleArticle;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialArticleUploadResult;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class WeChatArticleService {
@Resource
private WxMpService wxMpService;
public String addDraft(String title, String content, String thumbnailUrl) throws WxErrorException {
// 提取圖片URL并替換
List<String> imageUrls = extractImageUrls(content);
for (String imgUrl : imageUrls) {
String wechatUrl = uploadImage(imgUrl);
content = content.replace(imgUrl, wechatUrl);
}
WxMpDraftArticles article = new WxMpDraftArticles();
article.setAuthor("拾壹");
article.setContent(content);
article.setTitle(title);
article.setThumbMediaId(mediaUploadInImage(thumbnailUrl));
// 可根據(jù)需求設(shè)置更多文章屬性,如封面圖片等
WxMpAddDraft news = new WxMpAddDraft();
news.setArticles(Collections.singletonList(article));
return wxMpService.getDraftService().addDraft(news);
}
/**
* 根據(jù)url上傳永久素材
* @param url 圖片url
* @return 微信素材ID
*/
public String mediaUploadInImage(String url) throws IOException, WxErrorException {
byte[] bytes = this.downloadImage(url);
File file = convert(bytes);
String mediaId = materialFileUpload("image",file);
FileUtil.del(file);
return mediaId;
}
/**
* 根據(jù)文件上傳永久素材
* @param type 文件類型
* @param file 文件
* @return 微信素材ID
*/
public String materialFileUpload(String type,File file) throws IOException, WxErrorException {
WxMpMaterial wxMpMaterial = new WxMpMaterial();
wxMpMaterial.setFile(file);
WxMpMaterialUploadResult image = wxMpService.getMaterialService().materialFileUpload(type,wxMpMaterial);
return image.getMediaId();
}
/**
* 根據(jù)url上傳圖片
* @param url 圖片url
* @return 微信可訪問的url地址
*/
public String uploadImage(String url) throws IOException, WxErrorException {
byte[] bytes = this.downloadImage(url);
//bytes轉(zhuǎn)成file
File file = convert(bytes);
WxMediaImgUploadResult wxMediaImgUploadResult = wxMpService.getMaterialService().mediaImgUpload(file);
FileUtil.del(file);
return wxMediaImgUploadResult.getUrl();
}
/**
* byte[] 轉(zhuǎn) File
*
* @param bytes
* @return
* @throws IOException
*/
public static File convert(byte[] bytes) throws IOException {
// 創(chuàng)建一個(gè)臨時(shí)文件
File tempFile = File.createTempFile("temp-", ".png");
// 使用 FileOutputStream 將字節(jié)數(shù)組寫入文件
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(bytes);
}
return tempFile;
}
/**
* 下載圖片
*
* @param url
* @return
*/
private byte[] downloadImage(String url) {
return new RestTemplate().getForObject(url, byte[].class);
}
/**
* 提取 HTML 中的圖片 URL
*/
private List<String> extractImageUrls(String html) {
org.jsoup.nodes.Document doc = Jsoup.parse(html);
return doc.select("img").stream()
.map(img -> img.attr("src"))
.collect(Collectors.toList());
}
}上述代碼將WeChatArticle對(duì)象轉(zhuǎn)換為 WxJava 中的文章對(duì)象格式,并調(diào)用WxMpService的接口方法將文章上傳到草稿箱,返回文章的 mediaId,后續(xù)群發(fā)文章時(shí)會(huì)用到該 mediaId。
然后就是因?yàn)楣娞?hào)不能用其他外鏈的圖片,然后我們的圖片基本都是已經(jīng)上傳好了的外鏈地址,所以需要先將圖片上傳到公眾號(hào),然后再替換成返回的公眾號(hào)圖片url地址。
五、實(shí)現(xiàn)文章群發(fā)功能
在WeChatArticleService.java中繼續(xù)添加文章群發(fā)的方法:
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMassArticle;
import me.chanjar.weixin.mp.bean.material.WxMpMassArticleArticle;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialArticleUploadResult;
import me.chanjar.weixin.mp.bean.message.WxMpMassMessage;
import me.chanjar.weixin.mp.bean.message.WxMpMassMessageResult;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class WeChatArticleService {
public void wechatSendAll(String mediaId) {
try {
WxMpDraftInfo draft = wxMpService.getDraftService().getDraft(mediaId);
if (draft == null || draft.getNewsItem() == null || draft.getNewsItem().isEmpty()) {
throw new ServiceException("無效的mediaId: " + mediaId);
}
WxMpMassTagMessage wxMpMassTagMessage = new WxMpMassTagMessage();
wxMpMassTagMessage.setMediaId(mediaId);
wxMpMassTagMessage.setMsgType("mpnews");
wxMpMassTagMessage.setSendAll(true);
wxMpMassTagMessage.setSendIgnoreReprint(true);
wxMpService.getMassMessageService().massGroupMessageSend(wxMpMassTagMessage);
} catch (WxErrorException e) {
log.error("微信群發(fā)失敗", e);
throw new RuntimeException(e);
}
}
}該方法通過傳入文章的 mediaId,構(gòu)建群發(fā)消息對(duì)象,并調(diào)用WxMpService的群發(fā)接口將文章發(fā)送給公眾號(hào)的關(guān)注用戶。
七、總結(jié)與注意事項(xiàng)
通過上述步驟,我們成功實(shí)現(xiàn)了使用 Spring Boot 和 WxJava 將文章上傳到微信公眾號(hào)草稿箱以及群發(fā)的功能。在實(shí)際開發(fā)過程中,還需要注意以下幾點(diǎn):
接口調(diào)用頻率限制:微信公眾號(hào)接口對(duì)調(diào)用頻率有一定限制,需合理控制接口調(diào)用次數(shù),避免因頻率過高導(dǎo)致調(diào)用失敗。
錯(cuò)誤處理:代碼中對(duì)WxErrorException進(jìn)行了簡(jiǎn)單拋出,實(shí)際應(yīng)用中應(yīng)根據(jù)具體錯(cuò)誤碼進(jìn)行更詳細(xì)的錯(cuò)誤處理和日志記錄。
內(nèi)容審核:群發(fā)的文章內(nèi)容需符合微信公眾平臺(tái)的相關(guān)規(guī)定,否則可能導(dǎo)致文章發(fā)送失敗或公眾號(hào)受到處罰。
希望本文能幫助你快速掌握使用 Spring Boot 和 WxJava 進(jìn)行微信公眾號(hào)文章管理開發(fā)的技能,進(jìn)一步拓展公眾號(hào)的自動(dòng)化運(yùn)營(yíng)能力。
上述文章涵蓋了完整的實(shí)現(xiàn)流程與要點(diǎn)。你可以說說對(duì)文章篇幅、某些技術(shù)細(xì)節(jié)講解的看法,若有特殊需求,我可進(jìn)一步修改。
到此這篇關(guān)于Spring Boot 結(jié)合 WxJava 實(shí)現(xiàn)文章上傳微信公眾號(hào)草稿箱與群發(fā)的文章就介紹到這了,更多相關(guān)Spring Boot WxJava上傳微信公眾號(hào)草稿箱與群發(fā)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)橋接方法isBridge()和合成方法isSynthetic()
本文主要介紹了Java實(shí)現(xiàn)橋接方法isBridge()和合成方法isSynthetic(),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
Java實(shí)現(xiàn)刪除Word文檔中水印的示例代碼
在處理 Word 文檔時(shí),很多用戶可能會(huì)遇到水印問題,下面將詳細(xì)介紹如何通過 Java 使用 Spire.Doc 庫(kù)刪除 Word 文檔中的水印,并展示如何實(shí)現(xiàn)批量移除水印的功能吧2025-11-11
IDEA最新激活碼2021(IDEA2020.3.2最新永久激活方法)
這篇文章主要介紹了IDEA最新激活碼2021(IDEA2020.3.2最新永久激活方法),本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
java.net.UnknownHostException異常的一般原因及解決步驟
關(guān)于java.net.UnknownHostException大家也許都比較熟悉,這篇文章主要給大家介紹了關(guān)于java.net.UnknownHostException異常的一般原因及解決步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02
深入解析Spring?AI框架如何在Java應(yīng)用中實(shí)現(xiàn)智能化交互的關(guān)鍵
本文詳細(xì)介紹了SpringAI框架在Java應(yīng)用中的應(yīng)用,包括實(shí)體類映射、函數(shù)回調(diào)等核心功能的實(shí)現(xiàn),通過源碼分析,幫助開發(fā)者更好地理解和使用這些高級(jí)特性,提升業(yè)務(wù)效率,感興趣的朋友跟隨小編一起看看吧2024-11-11
完美解決Eclipse導(dǎo)入的項(xiàng)目上有個(gè)紅叉,但不影響項(xiàng)目運(yùn)行的問題
這篇文章主要介紹了完美解決Eclipse導(dǎo)入的項(xiàng)目上有個(gè)紅叉,但不影響項(xiàng)目運(yùn)行的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-01-01

