<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "weixin");
define("appID","xxxxxxxx");
define("appsecret","xxxxxxxxx");
$wechatObj = new wechatCallbackapiTest();
//验证服务器和公众平台建立连接
//如果已经建立连接成功后 就把该方法注释掉[每更改一次url 需要开启一次]
$wechatObj->valid();
/*开发者通过检验signature 对请求进行校验,若请求来自微信服务器,则返回echostr参数,否则接入失败。*/
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
//$this->getAccessToken();
$this->createMenu();
$this->responseMsg();
exit;
}
}
//获得服务器返回给用户的信息
public function responseMsg()
{
//get post data, May be due to the different environments
//接收用户(手机端)发给服务器的信息,可以接收xml格式的数据
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//extract post data
if (!empty($postStr)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
//只解析xml实体,不解析xml结构, 防止XXE攻击
libxml_disable_entity_loader(true);
//解析xml格式数据
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//获取发送者的openid
$fromUsername = $postObj->FromUserName;
//开发者的微信号
$toUsername = $postObj->ToUserName;
//获取发送的文本内容
$keyword = trim($postObj->Content);
//获取用户手机端发送过来的数据格式
$msgType = $postObj->MsgType;
//接收用户事件
$event = $postObj->Event;
$time = time();
/*以下都是服务器端返回给客户端的数据格式*/
//定义发送文本类型的字符串
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
//定义发送图片类型的字符串
$imageTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>";
//定义发送音乐的数据格式
$musicTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>
</xml>";
//定义发送图文消息接口
$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
%s
</Articles>
</xml>";
//定义用户关注后的消息信息
$eventTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Event><![CDATA[%s]]></Event>
</xml>";
//判断用户发送过来的数据格式
if($msgType=='text'){
if(!empty( $keyword ))
{
if($keyword=='音乐'){
echo $this->returnMusic($musicTpl,$fromUsername, $toUsername, $time);
}elseif($keyword=='单图文'){
echo $this->returnNews($newsTpl,$fromUsername, $toUsername,$time);
}elseif($keyword=='多图文'){
echo $this->returnReNews($newsTpl,$fromUsername, $toUsername,$time);
}else{
$msgType = 'text';
//$contentStr = "人痛苦是因为人存在,因为你痛苦的时候是感觉到自己存在最真实的时刻\n我痛苦是因为你没有输入;请输入
// 音乐、单图文、多图文等关键字。";
$contentStr=$this->robot($keyword);
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}else{
echo "Input something...";
}
}elseif($msgType=='image'){
$contentStr = "好美的一张图啊,亮瞎了我的眼!";
echo $this->returnText($textTpl,$fromUsername, $toUsername,$time,$contentStr);
}elseif($msgType=='voice'){
$contentStr = "好好听的声音啊,太6了!";
echo $this->returnText($textTpl,$fromUsername, $toUsername,$time,$contentStr);
}elseif($msgType=='location'){
$contentStr = "叔叔,我们不约哦!";
echo $this->returnText($textTpl,$fromUsername, $toUsername,$time,$contentStr);
}elseif($msgType=='event' && $event=='subscribe'){
//当前事件为订阅(关注)事件
$msgType = "text";
$contentStr = "欢迎关注,我们会为你及时更新最新面试试题!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}else {
echo "";
exit;
}
}
//回复文本消息
public function returnText($textTpl,$fromUsername, $toUsername,$time,$contentStr){
//设置发送类型为:文本类型
$msgType = "text";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
//回复音乐消息
public function returnMusic($musicTpl,$fromUsername, $toUsername, $time){
//设置发送类型为:音乐类型
$msgType = "music";
$title = '烟雨濛濛';
$descripition = '情深深雨蒙蒙主题曲';
$url = 'http://www.xiami.com/play?ids=/song/playlist/id/26751/object_name/default/object_id/0#loaded';
$hqurl = 'http://www.xiami.com/play?ids=/song/playlist/id/26751/object_name/default/object_id/0#loaded';
$resultStr = sprintf($musicTpl, $fromUsername, $toUsername, $time, $msgType, $title, $descripition, $url, $hqurl);
return $resultStr;
}
//回复图文消息
public function returnNews($newsTpl, $fromUsername, $toUsername, $time){
//设置发送类型为:图文类型
$msgType = 'news';
$count = 1;
$str = "<item>
<Title><![CDATA[这是图文回复的标题]]></Title>
<Description><![CDATA[这是图文回复的内容]]></Description>
<PicUrl><![CDATA[http://1.xdycloud.applinzi.com/wx_sample.php/1.jpg]]></PicUrl>
<Url><![CDATA[https://www.baidu.com]]></Url>
</item>";
$resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $count, $str);
echo $resultStr;
}
//回复多图文消息
public function returnReNews($newsTpl, $fromUsername, $toUsername, $time){
//设置发送类型为:图文类型
$msgType = 'news';
$count = 4;
$str = '';
for($i=1;$i<=$count;$i++){
$str .= "<item>
<Title><![CDATA[这是图文回复的标题]]></Title>
<Description><![CDATA[这是图文回复的内容]]></Description>
<PicUrl><![CDATA[http://1.xdycloud.applinzi.com/wx_sample.php/{$i}.jpg]]></PicUrl>
<Url><![CDATA[https://www.baidu.com]]></Url>
</item>";
}
$resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $count, $str);
echo $resultStr;
}
//tulingrobot
public function robot($keyword){
$url="http://www.tuling123.com/openapi/api?key=4fc6ba7cb92b3751a8141c881a60090f&info=".$keyword;
$html=file_get_contents($url);
$arr=json_decode($html,true);
return $arr['text'];
}
private function checkSignature()
{
// you must define TOKEN by yourself
if (!defined("TOKEN")) {
throw new Exception('TOKEN is not defined!');
}
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
return true;
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
public function getAccessToken(){
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode($this->get_php_file("access_token.php"));
if ($data->expire_time < time()) {
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8c42d48c5078c823&secret=eca3c0bc520a3a439dd408cfffeb84cc";
$json=file_get_contents($url);
$res = json_decode($json);
$access_token = $res->access_token;
if ($access_token) {
echo $data->expire_time = time() + 7000;
echo $data->access_token = $access_token;
echo $this->set_php_file("access_token.php", json_encode($data));
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
private function get_php_file($filename) {
return trim(substr(file_get_contents($filename), 15));
}
private function set_php_file($filename, $content) {
$fp = fopen($filename, "w");
fwrite($fp, "<?php exit();?>" . $content);
fclose($fp);
}
public function createMenu(){
$accesstoken=$this->getAccessToken();
$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accesstoken;
$data='{
"button":[
{
"name":"应用软件",
"sub_button":[
{
"type":"view",
"name":"百度一下",
"url":"http://www.baidu.com/"
},
{
"type":"view",
"name":"我的博客",
"url":"http://my.csdn.net/myhuashengmi"
},
{
"type":"view",
"name":"腾讯视频",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}]
},
{
"name": "发图",
"sub_button": [
{
"type": "pic_sysphoto",
"name": "系统拍照发图",
"key": "rselfmenu_1_0",
"sub_button": [ ]
},
{
"type": "pic_photo_or_album",
"name": "拍照或者相册发图",
"key": "rselfmenu_1_1",
"sub_button": [ ]
},
{
"type": "pic_weixin",
"name": "微信相册发图",
"key": "rselfmenu_1_2",
"sub_button": [ ]
}
]
},
{
"name": "发送位置",
"type": "location_select",
"key": "rselfmenu_2_0"
}
]
}';
return $this->curlPost($url,$data,'POST');
}
public function curlPost($url,$data,$method){
$ch = curl_init(); //1.初始化
curl_setopt($ch, CURLOPT_URL, $url); //2.请求地址
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);//3.请求方式
//4.参数如下
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');//模拟浏览器
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));//gzip解压内容
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
if($method=="POST"){//5.post方式的时候添加数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);//6.执行
if (curl_errno($ch)) {//7.如果出错
return curl_error($ch);
}
curl_close($ch);//8.关闭
return $tmpInfo;
}
}
?>
微信解读
最新推荐文章于 2024-08-11 08:30:00 发布