Spring?Boot?結(jié)合?WxJava?實現(xiàn)文章上傳微信公眾號草稿箱與群發(fā)
Spring Boot 結(jié)合 WxJava 實現(xiàn)文章上傳微信公眾號草稿箱與群發(fā)
在數(shù)字化營銷與內(nèi)容傳播日益重要的今天,微信公眾號已成為企業(yè)和個人進(jìn)行信息發(fā)布與推廣的重要平臺。對于開發(fā)者而言,通過代碼實現(xiàn)自動化的文章管理操作,如上傳文章到草稿箱、群發(fā)文章等,能夠極大提高工作效率。本文將詳細(xì)介紹如何使用 Spring Boot 框架結(jié)合 WxJava 開發(fā)工具包,實現(xiàn)文章上傳到微信公眾號草稿箱以及群發(fā)功能。
一、項目環(huán)境準(zhǔn)備
1.1 開發(fā)環(huán)境
JDK:建議使用 JDK 1.8 及以上版本,以確保與 Spring Boot 和 WxJava 的兼容性。
IDE:推薦使用 IntelliJ IDEA 或 Eclipse,兩者都對 Spring Boot 項目有良好的支持。
Maven:用于項目依賴管理和構(gòu)建,版本建議在 3.6 以上。
1.2 微信公眾號準(zhǔn)備
在開始開發(fā)前,需要提前準(zhǔn)備好微信公眾號的相關(guān)信息:
公眾號 AppID:用于唯一標(biāo)識你的公眾號,在微信公眾平臺后臺的 “開發(fā) - 基本配置” 中獲取。
公眾號 AppSecret:與 AppID 配合使用,用于獲取接口調(diào)用憑證(access_token),同樣在 “開發(fā) - 基本配置” 中查看。
IP 白名單設(shè)置:為保證接口調(diào)用的安全性,需要將服務(wù)器的 IP 地址添加到微信公眾平臺后臺的 “開發(fā) - 基本配置 - IP 白名單” 中。
二、Spring Boot 項目搭建
2.1 創(chuàng)建 Spring Boot 項目
可以通過 Spring Initializr(https://start.spring.io/)快速創(chuàng)建一個 Spring Boot 項目,在創(chuàng)建過程中選擇以下依賴:
Spring Web:用于構(gòu)建 Web 應(yīng)用,方便后續(xù)編寫接口進(jìn)行功能測試。
Lombok:簡化 Java 代碼,通過注解自動生成 getter、setter、構(gòu)造函數(shù)等。
2.2 添加 WxJava 依賴
在項目的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 是一個優(yōu)秀的微信開發(fā) Java 工具包,weixin-java-mp模塊專門用于微信公眾號開發(fā)。然后這里發(fā)現(xiàn)還引入了jsoup,這肯定是大有用處,可接著看后續(xù)的內(nèi)容。
三、配置微信公眾號信息
在 Spring Boot 項目中,創(chuàng)建一個配置類用于加載微信公眾號的 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;
}
}同時,在application.properties或application.yml文件中添加微信公眾號的配置信息:
wechat.mp.appId=your_app_id wechat.mp.appSecret=your_app_secret
將your_app_id和your_app_secret替換為實際獲取到的公眾號 AppID 和 AppSecret。
四、實現(xiàn)文章上傳到草稿箱
4.1 定義文章實體類
創(chuàng)建一個 Java 類用于表示微信公眾號文章,例如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ù)實際需求擴(kuò)展更多屬性。
4.2 編寫上傳草稿箱代碼
創(chuàng)建一個服務(wù)類,如WeChatArticleService.java,用于實現(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)建一個臨時文件
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對象轉(zhuǎn)換為 WxJava 中的文章對象格式,并調(diào)用WxMpService的接口方法將文章上傳到草稿箱,返回文章的 mediaId,后續(xù)群發(fā)文章時會用到該 mediaId。
然后就是因為公眾號不能用其他外鏈的圖片,然后我們的圖片基本都是已經(jīng)上傳好了的外鏈地址,所以需要先將圖片上傳到公眾號,然后再替換成返回的公眾號圖片url地址。
五、實現(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ā)消息對象,并調(diào)用WxMpService的群發(fā)接口將文章發(fā)送給公眾號的關(guān)注用戶。
七、總結(jié)與注意事項
通過上述步驟,我們成功實現(xiàn)了使用 Spring Boot 和 WxJava 將文章上傳到微信公眾號草稿箱以及群發(fā)的功能。在實際開發(fā)過程中,還需要注意以下幾點:
接口調(diào)用頻率限制:微信公眾號接口對調(diào)用頻率有一定限制,需合理控制接口調(diào)用次數(shù),避免因頻率過高導(dǎo)致調(diào)用失敗。
錯誤處理:代碼中對WxErrorException進(jìn)行了簡單拋出,實際應(yīng)用中應(yīng)根據(jù)具體錯誤碼進(jìn)行更詳細(xì)的錯誤處理和日志記錄。
內(nèi)容審核:群發(fā)的文章內(nèi)容需符合微信公眾平臺的相關(guān)規(guī)定,否則可能導(dǎo)致文章發(fā)送失敗或公眾號受到處罰。
希望本文能幫助你快速掌握使用 Spring Boot 和 WxJava 進(jìn)行微信公眾號文章管理開發(fā)的技能,進(jìn)一步拓展公眾號的自動化運(yùn)營能力。
上述文章涵蓋了完整的實現(xiàn)流程與要點。你可以說說對文章篇幅、某些技術(shù)細(xì)節(jié)講解的看法,若有特殊需求,我可進(jìn)一步修改。
到此這篇關(guān)于Spring Boot 結(jié)合 WxJava 實現(xiàn)文章上傳微信公眾號草稿箱與群發(fā)的文章就介紹到這了,更多相關(guān)Spring Boot WxJava上傳微信公眾號草稿箱與群發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java中靜態(tài)變量和實例變量的區(qū)別詳細(xì)介紹
本篇文章介紹了,java中靜態(tài)變量和實例變量的區(qū)別。需要的朋友參考下2013-05-05
詳解poi+springmvc+springjdbc導(dǎo)入導(dǎo)出excel實例
本篇文章主要介紹了poi+springmvc+springjdbc導(dǎo)入導(dǎo)出excel實例,非常具有實用價值,需要的朋友可以參考下。2017-01-01
深入淺析java web log4j 配置及在web項目中配置Log4j的技巧
這篇文章主要介紹了2015-11-11

