SpringBoot整合微信小程序开发工具

一、介绍

  • 通常进行微信开发时,不建议直接使用restful的方式调用微信官方提供的开发文档。一方面在于微信官方文档杂乱,影响开发效率;另一方面开源社区提供了众多微信开发的工具的封装。

  • 本文将为快速开发微信小程序后端提供解决方案,并集成推荐使用的微信小程序开发工具包,参考:

    https://github.com/Wechat-Group/weixin-java-tools

  • 附:微信小程序开发文档:

    https://mp.weixin.qq.com/debug/wxadoc/dev/api/

二、框架集成

  • 引入pom

      <!-- 微信小程序开发工具包 -->
     <dependency>
     	<groupId>com.github.binarywang</groupId>
     	<artifactId>weixin-java-miniapp</artifactId>
     	<version>2.9.6.BETA</version>
     </dependency>
    
  • application.properties配置项中添加如下配置

     ###################微信小程序配置信息####################
     wechat.miniapp.appid=小程序的appid
     wechat.miniapp.secret=小程序的secret
     wechat.miniapp.token=
     wechat.miniapp.aesKey=
    
  • 注入配置项信息

         import org.apache.commons.lang3.builder.ToStringBuilder;
     import org.apache.commons.lang3.builder.ToStringStyle;
     import org.springframework.boot.context.properties.ConfigurationProperties;
     
     /**
      * @author xiaojin_wu
      */
     @ConfigurationProperties(prefix = "wechat.miniapp")
     public class WxMaProperties {
         /**
          * 设置微信小程序的appid
          */
         private String appid;
     
         /**
          * 设置微信小程序的Secret
          */
         private String secret;
     
         /**
          * 设置微信小程序的token
          */
         private String token;
     
         /**
          * 设置微信小程序的EncodingAESKey
          */
         private String aesKey;
     
         /**
          * 消息格式,XML或者JSON
          */
         private String msgDataFormat;
     
         public String getAppid() {
             return this.appid;
         }
     
         public void setAppid(String appid) {
             this.appid = appid;
         }
     
         public String getSecret() {
             return this.secret;
         }
     
         public void setSecret(String secret) {
             this.secret = secret;
         }
     
         public String getToken() {
             return this.token;
         }
     
         public void setToken(String token) {
             this.token = token;
         }
     
         public String getAesKey() {
             return this.aesKey;
         }
     
         public void setAesKey(String aesKey) {
             this.aesKey = aesKey;
         }
     
         public String getMsgDataFormat() {
             return msgDataFormat;
         }
     
         public void setMsgDataFormat(String msgDataFormat) {
             this.msgDataFormat = msgDataFormat;
         }
     
         @Override
         public String toString() {
             return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
         }
     }
    
  • 如果需要使用模板功能,通过以下配置注入

         import cn.binarywang.wx.miniapp.api.WxMaService;
     import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
     import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
     import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
     import cn.binarywang.wx.miniapp.config.WxMaConfig;
     import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
     import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
     import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
     import com.google.common.collect.Lists;
     import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
     import me.chanjar.weixin.common.exception.WxErrorException;
     import org.springframework.beans.factory.annotation.Autowired;
     import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
     import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
     import org.springframework.boot.context.properties.EnableConfigurationProperties;
     import org.springframework.context.annotation.Bean;
     import org.springframework.context.annotation.Configuration;
     
     import java.io.File;
     
     /**
      * @author xiaojin_wu
      */
     @Configuration
     @ConditionalOnClass(WxMaService.class)
     @EnableConfigurationProperties(WxMaProperties.class)
     public class WxMaConfiguration {
         private static final WxMaMessageHandler templateMsgHandler = (wxMessage, context, service, sessionManager) ->
                 service.getMsgService().sendTemplateMsg(WxMaTemplateMessage.builder()
                         .templateId("此处更换为自己的模板id")
                         .formId("自己替换可用的formid")
                         .data(Lists.newArrayList(
                                 new WxMaTemplateMessage.Data("keyword1", "339208499", "#173177")))
                         .toUser(wxMessage.getFromUser())
                         .build());
     
         private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
             System.out.println("收到消息:" + wxMessage.toString());
             service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())
                     .toUser(wxMessage.getFromUser()).build());
         };
     
         private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) ->
                 service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
                         .toUser(wxMessage.getFromUser()).build());
     
         private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
             try {
                 WxMediaUploadResult uploadResult = service.getMediaService()
                         .uploadMedia("image", "png",
                                 ClassLoader.getSystemResourceAsStream("tmp.png"));
                 service.getMsgService().sendKefuMsg(
                         WxMaKefuMessage
                                 .newImageBuilder()
                                 .mediaId(uploadResult.getMediaId())
                                 .toUser(wxMessage.getFromUser())
                                 .build());
             } catch (WxErrorException e) {
                 e.printStackTrace();
             }
         };
     
         private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
             try {
                 final File file = service.getQrcodeService().createQrcode("123", 430);
                 WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
                 service.getMsgService().sendKefuMsg(
                         WxMaKefuMessage
                                 .newImageBuilder()
                                 .mediaId(uploadResult.getMediaId())
                                 .toUser(wxMessage.getFromUser())
                                 .build());
             } catch (WxErrorException e) {
                 e.printStackTrace();
             }
         };
         @Autowired
         private WxMaProperties properties;
     
         @Bean
         @ConditionalOnMissingBean
         public WxMaConfig config() {
             WxMaInMemoryConfig config = new WxMaInMemoryConfig();
             config.setAppid(this.properties.getAppid());
             config.setSecret(this.properties.getSecret());
             config.setToken(this.properties.getToken());
             config.setAesKey(this.properties.getAesKey());
             config.setMsgDataFormat(this.properties.getMsgDataFormat());
     
             return config;
         }
     
         @Bean
         @ConditionalOnMissingBean
         public WxMaService wxMaService(WxMaConfig config) {
             WxMaService service = new WxMaServiceImpl();
             service.setWxMaConfig(config);
             return service;
         }
     
         @Bean
         public WxMaMessageRouter router(WxMaService service) {
             final WxMaMessageRouter router = new WxMaMessageRouter(service);
             router
                     .rule().handler(logHandler).next()
                     .rule().async(false).content("模板").handler(templateMsgHandler).end()
                     .rule().async(false).content("文本").handler(textHandler).end()
                     .rule().async(false).content("图片").handler(picHandler).end()
                     .rule().async(false).content("二维码").handler(qrcodeHandler).end();
             return router;
         }
     
     }
    

三、如何使用

  • 在业务层(Controller)调用时,只需要通过自动装配即可;

     import cn.binarywang.wx.miniapp.api.WxMaService;
    
     /** 小程序工具服务 */
     @Autowired
     private WxMaService wxService;
    
  • 获取openid实例,此处会抛出WxErrorException异常,微信网关返回的信息通过该异常打出;

     import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
     import me.chanjar.weixin.common.exception.WxErrorException;
    
     WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
     		String openid = session.getOpenid();
     		String unionid = session.getUnionid();
    
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值