SpringMVC集成weixin4j实现微信开发者接入

简介

本次案例采用的weixin4j版本是weixin4j-0.1.0版本,采用的是SpringBoot做了一个微信开发者接入的示例。

开发步骤

1.新建项目

本次项目名称为:weixin4j-demo-jieru
pom.xml,仅列出了主要部分:

<groupId>org.weixin4j.demo.jieru</groupId>
    <artifactId>weixin4j-demo-jieru</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.weixin4j</groupId>
            <artifactId>weixin4j</artifactId>
            <version>0.1.0</version>
        </dependency>
    </dependencies>

启动程序

package org.weixin4j.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * 程序入口
 *
 * @author yangqisheng
 */
@SpringBootApplication
@ComponentScan
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2.实现普通消息接收实现类

我们需要新建一个普通消息接收实现类来处理我们接收到的微信消息,实现接口INormalMessageHandler

package org.weixin4j.demo.jieru;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.weixin4j.model.message.OutputMessage;
import org.weixin4j.model.message.normal.ImageInputMessage;
import org.weixin4j.model.message.normal.LinkInputMessage;
import org.weixin4j.model.message.normal.LocationInputMessage;
import org.weixin4j.model.message.normal.ShortVideoInputMessage;
import org.weixin4j.model.message.normal.TextInputMessage;
import org.weixin4j.model.message.normal.VideoInputMessage;
import org.weixin4j.model.message.normal.VoiceInputMessage;
import org.weixin4j.model.message.output.TextOutputMessage;
import org.weixin4j.spi.INormalMessageHandler;

/**
 * 自定义普通消息处理器
 *
 * @author yangqisheng
 */
public class AtsNormalMessageHandler implements INormalMessageHandler {

    protected final Logger LOG = LoggerFactory.getLogger(AtsNormalMessageHandler.class);

    @Override
    public OutputMessage textTypeMsg(TextInputMessage msg) {
        LOG.debug("文本消息:" + msg.getContent());
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("您发的消息是:" + msg.getContent());
        return out;
    }

    @Override
    public OutputMessage imageTypeMsg(ImageInputMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }

    @Override
    public OutputMessage voiceTypeMsg(VoiceInputMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }

    @Override
    public OutputMessage videoTypeMsg(VideoInputMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }

    @Override
    public OutputMessage shortvideoTypeMsg(ShortVideoInputMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }

    @Override
    public OutputMessage locationTypeMsg(LocationInputMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }

    @Override
    public OutputMessage linkTypeMsg(LinkInputMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }
}

3.再实现事件消息接收实现类

事件消息实现接口:IEventMessageHandler

package org.weixin4j.demo.jieru;

import org.weixin4j.model.message.OutputMessage;
import org.weixin4j.model.message.event.ClickEventMessage;
import org.weixin4j.model.message.event.LocationEventMessage;
import org.weixin4j.model.message.event.LocationSelectEventMessage;
import org.weixin4j.model.message.event.PicPhotoOrAlbumEventMessage;
import org.weixin4j.model.message.event.PicSysPhotoEventMessage;
import org.weixin4j.model.message.event.PicWeixinEventMessage;
import org.weixin4j.model.message.event.QrsceneScanEventMessage;
import org.weixin4j.model.message.event.QrsceneSubscribeEventMessage;
import org.weixin4j.model.message.event.ScanCodePushEventMessage;
import org.weixin4j.model.message.event.ScanCodeWaitMsgEventMessage;
import org.weixin4j.model.message.event.SubscribeEventMessage;
import org.weixin4j.model.message.event.UnSubscribeEventMessage;
import org.weixin4j.model.message.event.ViewEventMessage;
import org.weixin4j.model.message.output.TextOutputMessage;
import org.weixin4j.spi.IEventMessageHandler;

/**
 * 自定义事件消息处理器
 *
 * @author yangqisheng
 */
public class AtsEventMessageHandler implements IEventMessageHandler {

    @Override
    public OutputMessage subscribe(SubscribeEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("感谢您的关注!");
        return out;
    }

    @Override
    public OutputMessage unSubscribe(UnSubscribeEventMessage msg) {
        //取消关注
        return null;
    }

    @Override
    public OutputMessage qrsceneSubscribe(QrsceneSubscribeEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("感谢您的关注!,来源:" + msg.getEventKey());
        return out;
    }

    @Override
    public OutputMessage qrsceneScan(QrsceneScanEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }

    @Override
    public OutputMessage location(LocationEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("你的消息已经收到!");
        return out;
    }

    @Override
    public OutputMessage click(ClickEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("点击了菜单!");
        return out;
    }

    @Override
    public OutputMessage view(ViewEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("点击了链接!");
        return out;
    }

    @Override
    public OutputMessage scanCodePush(ScanCodePushEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("扫码!");
        return out;
    }

    @Override
    public OutputMessage scanCodeWaitMsg(ScanCodeWaitMsgEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("扫码等待中!");
        return out;
    }

    @Override
    public OutputMessage picSysPhoto(PicSysPhotoEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("发起拍照!");
        return out;
    }

    @Override
    public OutputMessage picPhotoOrAlbum(PicPhotoOrAlbumEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("选择相册!");
        return out;
    }

    @Override
    public OutputMessage picWeixin(PicWeixinEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("上次图片!");
        return out;
    }

    @Override
    public OutputMessage locationSelect(LocationSelectEventMessage msg) {
        TextOutputMessage out = new TextOutputMessage();
        out.setContent("选择地理位置!");
        return out;
    }
}

4.将自定义的实现类配置到weixin4j.properties

#微信SDK配置文件
#读取规则:优先读取System.getProperty()
#再从weixin4j.properties读取,key
#如果System.getProperty()与weixin4j.properties都没设置,则默认未NULL

#开发者调试设置
weixin4j.debug=true
#公众号Token
weixin4j.token=weixin4j

#公众号原始ID
weixin4j.oauth.originalid=
#开发者第三方用户唯一凭证
weixin4j.oauth.appid=
#开发者第三方用户唯一凭证密钥
weixin4j.oauth.secret=
#消息加密方式 0:明文模式(默认), 1:兼容模式, 2:安全模式(推荐)
weixin4j.oauth.encodingtype=0
#消息加密密钥(43位字符组成A-Za-z0-9)
weixin4j.oauth.encodingaeskey=0123456789abcedfghijklmnopqrstuvwxyzZXCVBNM
#网页安全授权URL
weixin4j.oauth.url=

#公众平台接口域名
#通用域名(api.weixin.qq.com),使用该域名将访问官方指定就近的接入点;
#上海域名(sh.api.weixin.qq.com),使用该域名将访问上海的接入点;
#深圳域名(sz.api.weixin.qq.com),使用该域名将访问深圳的接入点;
#香港域名(hk.api.weixin.qq.com),使用该域名将访问香港的接入点。
weixin4j.api.domain=api.weixin.qq.com

#微信支付_商户ID
weixin4j.pay.partner.id=
#微信支付_商户密钥
weixin4j.pay.partner.key=
#微信支付_通知URL
weixin4j.pay.notify_url=

#连接超时设置
weixin4j.http.connectionTimeout=25000
#请求超时设置
weixin4j.http.readTimeout=25000
#证书路径
weixin4j.http.cert.path=
weixin4j.http.cert.secret=

#默认消息处理函数
weixin4j.handler=org.weixin4j.spi.DefaultMessageHandler
weixin4j.message.handler.normal=org.weixin4j.demo.jieru.AtsNormalMessageHandler
weixin4j.message.handler.event=org.weixin4j.demo.jieru.AtsEventMessageHandler

最重要的是最后俩行改成我们自己定义的实现类
weixin4j.message.handler.normal=org.weixin4j.demo.jieru.AtsNormalMessageHandler
weixin4j.message.handler.event=org.weixin4j.demo.jieru.AtsEventMessageHandler

5.最后一步,编写接入接口

package org.weixin4j.demo.jieru;

import java.io.IOException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.weixin4j.WeixinException;
import org.weixin4j.spi.HandlerFactory;
import org.weixin4j.spi.IMessageHandler;
import org.weixin4j.util.TokenUtil;

/**
 * 微信开发者接入
 *
 * @author yangqisheng
 */
@Controller
@RequestMapping("/weixin/jieru")
public class WeixinJieruController {

    //开发者接入验证
    @RequestMapping(method = RequestMethod.GET)
    public void get(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //消息来源可靠性验证
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");       // 随机数
        //Token为weixin4j.properties中配置的Token
        String token = TokenUtil.get();
        //1.验证消息真实性
        //http://mp.weixin.qq.com/wiki/index.php?title=验证消息真实性
        //成为开发者验证
        String echostr = request.getParameter("echostr");
        //确认此次GET请求来自微信服务器,原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败
        if (TokenUtil.checkSignature(token, signature, timestamp, nonce)) {
            response.getWriter().write(echostr);
        }
    }

    //接收微信消息
    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //消息来源可靠性验证
        String signature = request.getParameter("signature");// 微信加密签名
        String timestamp = request.getParameter("timestamp");// 时间戳
        String nonce = request.getParameter("nonce");       // 随机数
        //Token为weixin4j.properties中配置的Token
        String token = TokenUtil.get();
        //确认此次GET请求来自微信服务器,原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败
        if (!TokenUtil.checkSignature(token, signature, timestamp, nonce)) {
            //消息不可靠,直接返回
            response.getWriter().write("");
            return;
        }
        //用户每次向公众号发送消息、或者产生自定义菜单点击事件时,响应URL将得到推送
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/xml");
            //获取POST流
            ServletInputStream in = request.getInputStream();
            //非注解方式,依然采用消息处理工厂模式调用
            IMessageHandler messageHandler = HandlerFactory.getMessageHandler();
            //处理输入消息,返回结果
            String xml = messageHandler.invoke(in);
            //返回结果
            response.getWriter().write(xml);
        } catch (IOException | WeixinException ex) {
            response.getWriter().write("");
        }
    }
}

至此,项目已经开发完毕,编译打包,发布。

部署测试

1.发布项目

将我们的项目发布到服务器,此服务必须是以80端口访问,例如我们本次发布到域名为api.weixin.daodianlai.com。

2.修改接入配置

登录微信公众平台,进入“开发->基本配置”页面。
微信开发者接入
点击“修改配置
微信接入配置
注意
URL 为我们部署域名+接入的入口。
TOKEN 为我们再weixin4j.properties中配置weixin4j.token的值。

3.接入完成

点击提交,至此,我们的微信开发接入就完成了。

weixin4j官网链接:http://www.weixin4j.org/
免费开源~,喜欢我小伙伴可以加weixin4j官方VIP群,QQ群:473227872

猜你喜欢

转载自blog.csdn.net/yakson/article/details/79985574