当前位置: 代码网 > it编程>编程语言>Java > Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

2025年07月13日 Java 我要评论
spring boot 结合 wxjava 实现文章上传微信公众号草稿箱与群发在数字化营销与内容传播日益重要的今天,微信公众号已成为企业和个人进行信息发布与推广的重要平台。对于开发者而言,通过代码实现

spring boot 结合 wxjava 实现文章上传微信公众号草稿箱与群发
在数字化营销与内容传播日益重要的今天,微信公众号已成为企业和个人进行信息发布与推广的重要平台。对于开发者而言,通过代码实现自动化的文章管理操作,如上传文章到草稿箱、群发文章等,能够极大提高工作效率。本文将详细介绍如何使用 spring boot 框架结合 wxjava 开发工具包,实现文章上传到微信公众号草稿箱以及群发功能。

一、项目环境准备

1.1 开发环境

jdk:建议使用 jdk 1.8 及以上版本,以确保与 spring boot 和 wxjava 的兼容性。
ide:推荐使用 intellij idea 或 eclipse,两者都对 spring boot 项目有良好的支持。
maven:用于项目依赖管理和构建,版本建议在 3.6 以上。

1.2 微信公众号准备

在开始开发前,需要提前准备好微信公众号的相关信息:
公众号 appid:用于唯一标识你的公众号,在微信公众平台后台的 “开发 - 基本配置” 中获取。
公众号 appsecret:与 appid 配合使用,用于获取接口调用凭证(access_token),同样在 “开发 - 基本配置” 中查看。
ip 白名单设置:为保证接口调用的安全性,需要将服务器的 ip 地址添加到微信公众平台后台的 “开发 - 基本配置 - ip 白名单” 中。

二、spring boot 项目搭建

2.1 创建 spring boot 项目

可以通过 spring initializr(https://start.spring.io/)快速创建一个 spring boot 项目,在创建过程中选择以下依赖:
spring web:用于构建 web 应用,方便后续编写接口进行功能测试。
lombok:简化 java 代码,通过注解自动生成 getter、setter、构造函数等。

2.2 添加 wxjava 依赖

在项目的pom.xml文件中添加 wxjava 相关依赖:

    <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 是一个优秀的微信开发 java 工具包,weixin-java-mp模块专门用于微信公众号开发。然后这里发现还引入了jsoup,这肯定是大有用处,可接着看后续的内容。

三、配置微信公众号信息

在 spring boot 项目中,创建一个配置类用于加载微信公众号的 appid 和 appsecret 等信息。例如,创建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.propertiesapplication.yml文件中添加微信公众号的配置信息:

wechat.mp.appid=your_app_id
wechat.mp.appsecret=your_app_secret

将your_app_id和your_app_secret替换为实际获取到的公众号 appid 和 appsecret。

四、实现文章上传到草稿箱

4.1 定义文章实体类

创建一个 java 类用于表示微信公众号文章,例如wechatarticle.java:
import lombok.data;

@data
public class wechatarticle {
    private string title;
    private string content;
    private string author;
    // 其他文章属性,如封面图片url等可根据需求添加
}

该类定义了文章的基本属性,如标题、内容和作者,可根据实际需求扩展更多属性。

4.2 编写上传草稿箱代码

创建一个服务类,如wechatarticleservice.java,用于实现上传文章到草稿箱的逻辑:

这里要特别注意,由于微信有些html标签不支持,所以需要将文章内容复制到专门的微信markdown编辑器中格式化后,在从编辑器复制出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));
        // 可根据需求设置更多文章属性,如封面图片等
        wxmpadddraft news = new wxmpadddraft();
        news.setarticles(collections.singletonlist(article));
        return wxmpservice.getdraftservice().adddraft(news);
    }
      /**
     * 根据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;
    }
    /**
     * 根据文件上传永久素材
     * @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();
    }
      /**
     * 根据url上传图片
     * @param url 图片url
     * @return 微信可访问的url地址
     */
    public string uploadimage(string url) throws ioexception, wxerrorexception {
        byte[] bytes = this.downloadimage(url);
        //bytes转成file
        file file = convert(bytes);
        wxmediaimguploadresult wxmediaimguploadresult = wxmpservice.getmaterialservice().mediaimgupload(file);
        fileutil.del(file);
        return wxmediaimguploadresult.geturl();
    }
      /**
     * byte[] 转 file
     *
     * @param bytes
     * @return
     * @throws ioexception
     */
    public static file convert(byte[] bytes) throws ioexception {
        // 创建一个临时文件
        file tempfile = file.createtempfile("temp-", ".png");
        // 使用 fileoutputstream 将字节数组写入文件
        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对象转换为 wxjava 中的文章对象格式,并调用wxmpservice的接口方法将文章上传到草稿箱,返回文章的 mediaid,后续群发文章时会用到该 mediaid。
然后就是因为公众号不能用其他外链的图片,然后我们的图片基本都是已经上传好了的外链地址,所以需要先将图片上传到公众号,然后再替换成返回的公众号图片url地址。

五、实现文章群发功能

在wechatarticleservice.java中继续添加文章群发的方法:

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("微信群发失败", e);
            throw new runtimeexception(e);
        }
    }
}

该方法通过传入文章的 mediaid,构建群发消息对象,并调用wxmpservice的群发接口将文章发送给公众号的关注用户。

七、总结与注意事项

通过上述步骤,我们成功实现了使用 spring boot 和 wxjava 将文章上传到微信公众号草稿箱以及群发的功能。在实际开发过程中,还需要注意以下几点:
接口调用频率限制:微信公众号接口对调用频率有一定限制,需合理控制接口调用次数,避免因频率过高导致调用失败。
错误处理:代码中对wxerrorexception进行了简单抛出,实际应用中应根据具体错误码进行更详细的错误处理和日志记录。
内容审核:群发的文章内容需符合微信公众平台的相关规定,否则可能导致文章发送失败或公众号受到处罚。
希望本文能帮助你快速掌握使用 spring boot 和 wxjava 进行微信公众号文章管理开发的技能,进一步拓展公众号的自动化运营能力。
上述文章涵盖了完整的实现流程与要点。你可以说说对文章篇幅、某些技术细节讲解的看法,若有特殊需求,我可进一步修改。

到此这篇关于spring boot 结合 wxjava 实现文章上传微信公众号草稿箱与群发的文章就介绍到这了,更多相关spring boot wxjava上传微信公众号草稿箱与群发内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com