微信公众号开发(九)——用户消息接收

目录

文本消息

 图像消息

语音消息

视频及小视频消息

接收到的数据信息如下,小视频唯一区别就是MsgType=shortvideo

 地理位置

 


当任何一个微信用户,打开你的公众号,通过键盘输入文字、选择图片等信息发送时,你设置的接口,就会收到对方的信息。这个信息结构大致和被动回复(前面讲的点击菜单回复)类似。

文本消息

<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>

接收对象WXMessgeBean。

import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class WXMessgeBean {
    private String FromUserName;
    private String ToUserName;
    private long CreateTime;
    private String MsgType;
    private String Event;
    private String EventKey;
    private String Content;
    private String Url;
    private String PicUrl;
    private String MediaId;
    private String Format;
    private String Recognition;
    private String ThumbMediaId;
//地理位置
    private float Location_X;
    private float Location_Y;
    private float Scale;

    private long MsgId;
//省略了stter和getter
    ......
}

接收代码,当接收到对方的消息后,我们给他回复一句问候。

    @PostMapping(value = "/checktoken", produces = MediaType.APPLICATION_XML_VALUE)
    public String receiveWX(HttpServletRequest request, HttpServletResponse response  ){
        try {
            Marshaller marshaller;
            Unmarshaller unmarshal;
            //你要解析成哪个bean对象,newInstance的参数就是哪个对象
            JAXBContext jaxbContext = JAXBContext.newInstance(WXMessgeBean.class);
            unmarshal = jaxbContext.createUnmarshaller();
            //xml解码成bean对象
            WXMessgeBean wxMessgeBean = (WXMessgeBean) unmarshal.unmarshal(request.getInputStream());
            if ("text".equals(wxMessgeBean.getMsgType())){
                WXMessgeBean bean = new WXMessgeBean();
                bean.setFromUserName(wxMessgeBean.getToUserName());
                bean.setToUserName(wxMessgeBean.getFromUserName());
                bean.setCreateTime(new Date().getTime());
                bean.setMsgType("text");
                bean.setContent("你好,欢迎浏览我的公众号");
                marshaller = jaxbContext.createMarshaller();
                StringWriter writer = new StringWriter();
                marshaller.marshal(bean,writer);
                return writer.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

接收到的信息如下: 

 图像消息

当用户从相册选择一个图片后,系统会将此图片提交到服务端,并生成PicUrl和MediaId

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[image]]></MsgType>
  <PicUrl><![CDATA[this is a url]]></PicUrl>
  <MediaId><![CDATA[media_id]]></MediaId>
  <MsgId>1234567890123456</MsgId>
</xml>

语音消息

<xml>
  <ToUserName>< ![CDATA[toUser] ]></ToUserName>
  <FromUserName>< ![CDATA[fromUser] ]></FromUserName>
  <CreateTime>1357290913</CreateTime>
  <MsgType>< ![CDATA[voice] ]></MsgType>
  <MediaId>< ![CDATA[media_id] ]></MediaId>
  <Format>< ![CDATA[Format] ]></Format>
  <Recognition>< ![CDATA[腾讯微信团队] ]></Recognition>
  <MsgId>1234567890123456</MsgId>
</xml>

 接收方法同上,接收信息如下:

视频及小视频消息

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1357290913</CreateTime>
  <MsgType><![CDATA[video]]></MsgType>
  <MediaId><![CDATA[media_id]]></MediaId>
  <ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId>
  <MsgId>1234567890123456</MsgId>
</xml>

接收到的数据信息如下,小视频唯一区别就是MsgType=shortvideo

 地理位置

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1351776360</CreateTime>
  <MsgType><![CDATA[location]]></MsgType>
  <Location_X>23.134521</Location_X>
  <Location_Y>113.358803</Location_Y>
  <Scale>20</Scale>
  <Label><![CDATA[位置信息]]></Label>
  <MsgId>1234567890123456</MsgId>
</xml>

 

接入第三方登录是让用户方便快捷地使用已有账号登录你的网站或应用程序,提高用户体验的一种方式。本文将介绍如何使用 PHP 实现微信公众号第三方登录。 1. 获取微信授权 首先,需要获取微信用户的授权。具体步骤如下: 1)引导用户打开微信授权页面: ```php $appid = 'your_appid'; $redirect_uri = urlencode('http://yourdomain.com/callback.php'); $scope = 'snsapi_userinfo'; $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=STATE#wechat_redirect"; header("Location: $url"); ``` 其中,`$appid` 是你的微信公众号的 AppID,`$redirect_uri` 是授权后回调的 URL,`$scope` 是授权作用域,可以是 `snsapi_base` 或 `snsapi_userinfo`,`$state` 是自定义参数,用于防止 CSRF 攻击。 2)获取授权码: 用户同意授权后,会重定向到 `$redirect_uri` 指定的 URL,带上授权码 `code` 和 `state` 参数。 ```php $code = $_GET['code']; $state = $_GET['state']; ``` 3)获取 access_token 和 openid: 使用授权码 `code` 获取 `access_token` 和 `openid`。 ```php $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; $response = file_get_contents($access_token_url); $result = json_decode($response, true); $access_token = $result['access_token']; $openid = $result['openid']; ``` 其中,`$secret` 是你的微信公众号的 AppSecret。 2. 获取用户信息 获取到 `access_token` 和 `openid` 后,可以使用以下代码获取用户信息: ```php $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN"; $response = file_get_contents($userinfo_url); $userinfo = json_decode($response, true); ``` 其中,`$userinfo` 包含用户的昵称、头像等信息。 3. 将用户信息保存到数据库 最后,将获取到的用户信息保存到数据库中,以便下次使用时快速登录。 ```php // 连接数据库 $con = mysqli_connect('localhost', 'username', 'password', 'database'); mysqli_set_charset($con, "utf8"); // 查询用户是否已存在 $sql = "SELECT * FROM users WHERE openid='$openid'"; $result = mysqli_query($con, $sql); if (mysqli_num_rows($result) == 0) { // 用户不存在,插入新用户信息 $nickname = mysqli_real_escape_string($con, $userinfo['nickname']); $headimgurl = mysqli_real_escape_string($con, $userinfo['headimgurl']); $sql = "INSERT INTO users (openid, nickname, headimgurl) VALUES ('$openid', '$nickname', '$headimgurl')"; mysqli_query($con, $sql); } // 保存用户登录状态 $_SESSION['openid'] = $openid; ``` 以上就是使用 PHP 实现微信公众号第三方登录的步骤。需要注意的是,为了确保安全性,应该对用户输入的数据进行过滤和验证,防止 SQL 注入和 XSS 攻击等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bdmh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值