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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章