java配合springboot接入微信公众平台开发

第一步公众号申请

进入https://mp.weixin.qq.com/申请一个订阅号,谁都能申请

请添加图片描述
进去后查看接口权限
![请添加图片描述](https://img-blog.csdnimg.cn/a325986c64674714ab1b6bbf854c0fdf.png = 600x400)
这些重要的接口功能只有认证服务号有,但是我们可以申请一个测试帐号。
点击开发者工具=》测试帐号
请添加图片描述

在这里插入图片描述
注意:这里点提交需要后端开启服务,并且调用接口一直,才可以成功,看不懂的可以看下面的服务器配置后再提交测试! 点击看下面的配置

如果本地调试,需要先开个内网穿透
这里填写url和token。
url=内网穿透ip+/wx/portal/public
Token=随便写

公众号开发基础与内网穿透,建议先学习教程链接

对于需要获取用户权限(头像,昵称)还需要配置一个东西
在这里插入图片描述
在这里插入图片描述
填上你的穿透地址就行,不需要加协议。

第二步后端服务器配置

1.pom.xml引入对应的依赖

<!-- 基于Spring Boot 和 WxJava 实现的微信公众号Java后端Demo,支持多公众号 -->
    <dependency>
        <groupId>com.github.binarywang</groupId>
        <artifactId>weixin-java-mp</artifactId>
        <version>4.5.0</version>
    </dependency>
<!-- 其他的依赖省略。。比如springbootweb之类的必须要配置 -->

依赖出自Binary Wang,他的github中也有具体的使用方法可以去看一下

2.到application.yml相关配置

wx:
  mp:
    # callback:如果本地填写穿透地址,如果是服务器填写服务器地址
    callback: http://sysm8w.natappfree.cc 
    configs:
      - appId: wx71axxxx318444e6 # 第一个公众号的appid
        secret: 11f8d45xxxxxxxxc8c60dd3df48aa9 # 公众号的appsecret
        token: abcc # 对应接口配置里的Token值
        aesKey: sha1 # 接口配置里的EncodingAESKey值,如果是测试号可以不用填写

3.创建对应的配置属性类

WxMpProperties.java


import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

/**
 * wechat mp properties
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Data
@ConfigurationProperties(prefix = "wx.mp")
public class WxMpProperties {
    
    
    /**
     * 是否使用redis存储access token
     */
    private boolean useRedis;

    /**
     * redis 配置
     */
    private RedisConfig redisConfig;

    @Data
    public static class RedisConfig {
    
    
        /**
         * redis服务器 主机地址
         */
        private String host;

        /**
         * redis服务器 端口号
         */
        private Integer port;

        /**
         * redis服务器 密码
         */
        private String password;

        /**
         * redis 服务连接超时时间
         */
        private Integer timeout;
    }

    /**
     * 多个公众号配置信息
     */
    private List<MpConfig> configs;

    @Data
    public static class MpConfig {
    
    
        /**
         * 设置微信公众号的appid
         */
        private String appId;

        /**
         * 设置微信公众号的app secret
         */
        private String secret;

        /**
         * 设置微信公众号的token
         */
        private String token;

        /**
         * 设置微信公众号的EncodingAESKey
         */
        private String aesKey;
    }

    @Override
    public String toString() {
    
    
        return JSONUtil.toJsonStr(this);
    }
}

4.创建微信接口配置类

WxMpConfig.java

    /**
     * 创建并配置一个用于微信公众号操作的 WxMpService 实例。
     * 该方法读取配置属性并为每个公众号配置创建一个 WxMpDefaultConfigImpl 实例,
     * 将这些实例放入 MultiConfigStorages 中,并返回最终的 WxMpService 实例。
     *
     * @return WxMpService 实例,用于微信公众号操作
     * @throws RuntimeException 如果 wxService 配置异常或 Application 相关配置对象缺失
     */
    @Bean
    public WxMpService wxService() {
    
    
        final List<WxMpProperties.MpConfig> configs = wxMpProperties.getConfigs();
        // 检查配置是否存在
        if (configs == null) {
    
    
            throw new RuntimeException("wxService配置异常,请检查Application相关配置对象");
        }
        // 创建 WxMpService 实例
        WxMpService service = new WxMpServiceImpl();
        // 配置 MultiConfigStorages
        service.setMultiConfigStorages(
                configs.stream().map(item -> {
    
    
                    WxMpDefaultConfigImpl wxMpDefaultConfig = new WxMpDefaultConfigImpl();
                    // 设置公众号的 AppId
                    wxMpDefaultConfig.setAppId(item.getAppId());
                    // 设置公众号的 Secret
                    wxMpDefaultConfig.setSecret(item.getSecret());
                    // 设置公众号的 Token
                    wxMpDefaultConfig.setToken(item.getToken());
                    // 设置公众号的 AesKey
                    wxMpDefaultConfig.setAesKey(item.getAesKey());
                    return wxMpDefaultConfig;
                }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o))
        );

        return service;
    }

5.web层验证

WxController.java

package com.wwk.usercenter.controller;


import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author wwk
 * @Date 2023/6/6 13:14
 */
@RestController
@RequestMapping("/wx/portal")
@Slf4j
public class WxController {
    
    
    @Resource
    private WxMpService wxService;

    @RequestMapping("/public")
    public String checkWxServer(@RequestParam Map<String, String> map) {
    
    
        log.info("开始验证消息是否来自微信服务器,传来的参数{}",map);
        String signature = map.get("signature");
        String echostr = map.get("echostr");
        String timestamp = map.get("timestamp");
        String nonce = map.get("nonce");
        if (StringUtils.isAnyBlank(signature, echostr, timestamp, nonce)) {
    
    
            throw new IllegalArgumentException("请求参数非法,请核实!");
        }
        if (wxService.checkSignature(timestamp, nonce, signature)) {
    
    
            log.info("消息来自微信服务器,验证成功,signature;{}",signature);
            return echostr;

        }
        log.warn("消息来自其他服务器,非法请求!!!");
        return "微信非法请求";
    }

}

注意:配置好所有的配置开启服务,就可以点击上面微信接口配置的提交按钮测试了,配置成功代表验证通过!

猜你喜欢

转载自blog.csdn.net/m0_59757074/article/details/131074966