首页 > 其他分享 >微信公众号开发---基础消息能力开发

微信公众号开发---基础消息能力开发

时间:2023-05-29 14:36:42浏览次数:53  
标签:nonce String 微信 --- 开发 参数 signature 服务器

微信公众号接收普通消息

1.配置开发服务器

微信公众平台->开发->开发者工具->公众平台测试账号

微信公众号开发---基础消息能力开发_服务器

appid:是微信公众号的唯一标识,通过和appsecret进行验证。 URL:开发服务器的路径,接收微信服务器发送的数据。 Token:自设定的token,和开发服务器中进行验证的token保持一致。 微信公众号用户,微信服务器和开发服务器三者之间的关系:微信公众号用户发送信息时,发送到微信服务器,微信服务器将消息转发给开发服务器,交互都是通过xml格式。如果你是用本地tomcat,可以使用像natapp这样的内网穿透工具,生成一个外网域名,通过域名访问本地localhost:8080.

注册链接

登录之后 ,购买免费通道

微信公众号开发---基础消息能力开发_服务器_02

需要修改成自己项目的ip和端口

微信公众号开发---基础消息能力开发_服务器_03

运行natapp

config.ini方式 (推荐)

根据操作系统下载不同的config.ini文件到刚才下载的natapp.exe同级目录 下载链接

将免费通道得到的authtoken填进去 (其他地方都不填),然后保存

微信公众号开发---基础消息能力开发_服务器_04

windows下,直接双击natapp.exe 即可.

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:

参数

描述

signature

微信加密签名,结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。

timestamp

时间戳

nonce

随机数

echostr

随机字符串

wei-java-tools依赖

<dependency>
            <groupId>me.chanjar</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>me.chanjar</groupId>
            <artifactId>weixin-java-common</artifactId>
            <version>1.3.3</version>
        </dependency>

代码:

//微信配置服务器 验证
    @RequestMapping(value="/wxserver",method={RequestMethod.GET})
    public  void check(HttpServletRequest request, HttpServletResponse response)  {
        //微信服务器get传递的参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
 
        //微信工具服务类
        WxMpService wxService=new WxMpServiceImpl();
        //注入token的配置参数
        /**
         * 生产环境 建议将WxMpInMemoryConfigStorage持久化
         */
        WxMpInMemoryConfigStorage wxConfigProvider=new WxMpInMemoryConfigStorage();
        //注入token值
        wxConfigProvider.setToken("weixin");
        wxService.setWxMpConfigStorage(wxConfigProvider);
        boolean flag=wxService.checkSignature(timestamp, nonce, signature); //验证token跟微信配置的是否一样
        PrintWriter out= null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(flag){
            out.print(echostr);
        }
        out.close();
    }

signature: signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。将这三个参数采用sha1算法进行加密.

boolean flag=wxService.checkSignature(timestamp, nonce, signature)

根据这三个参数,在开发服务器里面重新sha1算法加密,生成新的signature,然后和请求参数中的signature比较,相同则验证成成,成功之后返回随机字符串。配置阶段则成功。

2.简单的实现文字回复的操作

微信公众号开发---基础消息能力开发_微信_05

URL:验证的时候会携带参数以GET方法去请求这个url。而验证成功之后,微信公众号用户发送数据时,微信服务器会将数据以POST方法发送到这个url。

所以说我们应该写两个相同路径,请求方法不同的controller。

@RequestMapping(value="/wxserver",method={RequestMethod.GET});
 @RequestMapping(value="/wxserver",produces={"application/xml;charset=UTF-8;"},method={RequestMethod.POST})

普通消息

文本消息事例

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <Content><![CDATA[this is a test]]></Content>
  <MsgId>1234567890123456</MsgId>
</xml>

参数

描述

ToUserName

开发者微信号

FromUserName

发送方帐号(一个OpenID)

CreateTime

消息创建时间 (整型)

MsgType

消息类型,文本为text

Content

文本消息内容

MsgId

消息id,64位整型

MsgType:消息类型,文本为text,图片为image,语音为voice等官方文档

推送事件

菜单点击事件事例

用户点击自定义菜单后,微信会把点击事件推送给开发者,请注意,点击菜单弹出子菜单,不会产生上报。

点击菜单拉取消息时的事件推送

推送XML数据包示例:

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[FromUser]]></FromUserName>
  <CreateTime>123456789</CreateTime>
  <MsgType><![CDATA[event]]></MsgType>
  <Event><![CDATA[CLICK]]></Event>
  <EventKey><![CDATA[EVENTKEY]]></EventKey>
</xml>

参数说明:

微信公众号开发---基础消息能力开发_xml_06

代码:

@ResponseBody()
    @RequestMapping(value="/wxserver",produces={"application/xml;charset=UTF-8;"},method={RequestMethod.POST})
    public  String  receive(HttpServletRequest request, HttpServletResponse response)  throws  Exception{
        //因为微信服务器返回的是xml  所以我们需要解析
        //获取消息流
        WxMpXmlMessage message=WxMpXmlMessage.fromXml(request.getInputStream());
        String fromUserName = message.getFromUserName();
        String toUserName = message.getToUserName();
        logger.info("【猎人MM微信公众号】被请求,用户openId:"+fromUserName);
        //消息类型
        String messageType=message.getMsgType();
        if("text".equals(messageType)){
          //  String res= wxTextReceiveService.receiveText(message);
            String str="";

            //文本消息  文本内容
            String content = message.getContent();

            //将回复消息按格式封装成xml
            //toUser(fromUserName).fromUser(toUserName)  发送者变成接受者
            WxMpXmlOutTextMessage text = WxMpXmlOutTextMessage.TEXT().toUser(fromUserName).fromUser(toUserName).content("您发送的消息是\n"+content ).build();
            str = text.toXml();
            return str;

        }else if("event".equals(messageType)){
            String str="";
            WxMpXmlOutTextMessage text = WxMpXmlOutTextMessage.TEXT().toUser(fromUserName).fromUser(toUserName).content("欢迎关注\n" ).build();
            str = text.toXml();
            return str;
        }
        return "";
    }

messageType类型 官方文档

标签:nonce,String,微信,---,开发,参数,signature,服务器
From: https://blog.51cto.com/u_16096846/6370702

相关文章

  • linphone-PresenceNoteImpl文件对应的JNI层文件分析
    说明这个很短,自己看。native函数privatenativelongnewPresenceNoteImpl(Stringcontent,Stringlang);privatenativevoidunref(longnativePtr);privatenativeStringgetContent(longnativePtr);privatenativeintsetContent(longnativePtr,String......
  • linphone-TunnelConfigImpl文件对应的JNI层文件分析
    说明native函数privatenativeStringgetHost(longnativePtr);privatenativevoidsetHost(longnativePtr,Stringhost);privatenativeintgetPort(longnativePtr);privatenativevoidsetPort(longnativePtr,intport);privatenativeintgetRem......
  • linphone-LinphoneService.java文件分析
    说明主要是处理接听电话的逻辑,监听linphone拨打电话的状态逻辑。官方注释/****Linphoneservice,reactingtoIncomingcalls,...<br/>**Rolesinclude:<ul>*<li>InitializingLinphoneManager</li>*<li>StartingClibLinphonethroughLinphoneManage......
  • linphone-LinphoneCallParams.java文件分析
    说明专门作为Audio和Video的参数功能设置视频的带宽设置音频的带宽设置媒体的加密数据(encryption)设置是否允许低带宽设置RecordFile设置Sdp设置会话名称等是否允许多个rtp请求UML类图LinphoneCallParamsImpl.javapackageorg.linphone.core;importorg.linphone.core.LinphoneCor......
  • linphone-CallManager.java文件分析
    说明进行会话的管理,重新加入会话等功能创建会话重新进入Video重新设置参数更新会话UML类图CallManger.javapackageorg.linphone;importorg.linphone.core.LinphoneAddress;importorg.linphone.core.LinphoneCall;importorg.linphone.core.LinphoneCallParams;importorg.l......
  • linphone-PayloadType.java文件分析
    说明这个类主要是设置一些类型的参数,如MIME,RATE,FMTP等功能设置MIME设置RATE设置FMTUML类图PayloadType.javapackageorg.linphone.core;publicinterfacePayloadType{/***Obtaintheregisteredmime-type(actuallysubmime)ofthePayloadType.Forexample:......
  • linphone-LinphoneProxyConfig.java文件分析
    说明这个是linphone的纯配置文件,可能需要保存到文件中,是长久的数据.如何保存c/c++分析.功能设置Identity设置Address设置Proxy设置register设置Domain设置Dial设置Route设置Route设置Expires设置AVPF设置Realm设置ContactParameters设置PublichExpiresUML类图LinphoneProxyConfi......
  • linphone-LinphonePreferences.java文件分析
    说明这个文件比较长,主要是对于linphone的配置文件等设置。对于前面文章中文件的调用。其中大多数是对底层的调用设置。功能设置用户信息设置端口号设置显示名称设置密码设置代理设置编码设置编码速率设置DMTF等设置加密解密设置是否使用ipv6设置tunnel设置相机等UML类图LinphonePre......
  • JNI-记录一个内存泄露的问题
    android:channelisunrecoverablybrokenandwillbedisposed记录一个关于内存泄漏的问题:RT,在停止播放音乐时,每过一段时间就会报05-2510:52:21.125491-528/system_processE/InputDispatcher:channel'4a8b59f4activity.MainActivity(server)'~Channelisun......
  • linphone-NetworkManger.java文件分析
    功能InterceptnetworkstatechangesandupdatelinphonecorethroughLinphoneManger翻译拦截网络状态的变化,并通过LinphoneManger更新linphone核心内容。NetworkManager.java/**......