php微信开发源码

<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "landyxy");//只用改这一个TOKEN、任意名称,比如weixin_freddon
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();//验证是否作为微信服务器
//$wechatObj->responseMsg();
//$wechatObj->create_menu();
class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = file_get_contents("php://input");
					//isset($GLOBALS["HTTP_RAW_POST_DATA"])?$GLOBALS["HTTP_RAW_POST_DATA"]  : "";
					//$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 */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
				$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>";
				
				switch($postObj->MsgType)
				{
					case 'event':
						if($event=='subscribe'){
						//echo 'fdsfd';
							$contentStr="欢迎关注Landy!\r\n\r\n 菜单如下 \r\n 1.输入新闻就返回新闻条目";
							$msgType = "text";
							//$contentStr='welcome';
							$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                			echo $resultStr;
						}
						break;
					case 'text':
						if($keyword=='新闻'){

							$tplHeader="<xml>
									<ToUserName><![CDATA[%s]]></ToUserName>
									<FromUserName><![CDATA[%s]]></FromUserName>
									<CreateTime>%s</CreateTime>
									<MsgType><![CDATA[news]]></MsgType>
									<ArticleCount>%s</ArticleCount>
									<Articles>";
							$tplContent="<item>
									<Title><![CDATA[%s]]></Title> 
									<Description><![CDATA[%s]]></Description>
									<PicUrl><![CDATA[%s]]></PicUrl>
									<Url><![CDATA[%s]]></Url>
									</item>";
							$tplfooter="</Articles>
									</xml>";
							
							//连接数据库

							$mysqli=new mysqli('127.0.0.1','root','','landy');
							//mysql_select_db('landy');
							$mysqli->query('SET NAMES UTF8');
							$sql="select title,decription,picUrl,url from newsImages limit 0,10";
							$res=$mysqli->query($sql);
							$itemCount=0;
							$contentStr="";
							while($row=mysqli_fetch_array($res)){
								$contentStr.=sprintf($tplContent,$row['title'],$row['decription'],$row['picUrl'],$row['url']);
								++$itemCount;
							}
							$tplHeader=sprintf($tplHeader,$fromUsername, $toUsername, $time,$itemCount);
							$resultStr = $tplHeader.$contentStr.$tplfooter;
                			echo $resultStr;
						}
						else if($keyword=="听歌"){
							$contentStr="欢迎使用在线听歌!\r\n\r\n 歌单如下 \r\n 1.曹方-海鸥 \r\n 2.曹方-城市稻草人 \r\n 回复歌曲编号,就可听歌! ";
							$msgType = "text";
							$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                			echo $resultStr;
						}
						else if(preg_match('/^[1-9](\d){0,2}$/',$keyword)){
							if($keyword==1){
								$desc="曹方-海鸥";
							}
							else if($keyword==2){
								$desc="曹方-城市稻草人";
							}
							else{
								$desc="曹方-海鸥";
								$keyword=1;
							}

							$musicTpl="<xml>
										<ToUserName><![CDATA[%s]]></ToUserName>
										<FromUserName><![CDATA[%s]]></FromUserName>
										<CreateTime>%s</CreateTime>
										<MsgType><![CDATA[music]]></MsgType>
										<Music>
										<Title><![CDATA[曹方音乐]]></Title>
										<Description><![CDATA[%s]]></Description>
										<MusicUrl><![CDATA[%s]]></MusicUrl>
										<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
										</Music>
										</xml>";
						  $music_url="http://139.199.xxx.xxx/wx/music/{$keyword}.mp3";
						  //echo 'resultStr';
						  $resultStr=sprintf($musicTpl,$fromUsername, $toUsername, $time,$desc,$music_url,$music_url);
						  echo $resultStr;
						}

						else if(preg_match("/^cxwz([\x{4e00}-\x{9fa5}]+)/ui",$keyword,$res)){
							$address=$res[1];
							$mysqli=new mysqli('127.0.0.1','root','','landy');
							//mysql_select_db('landy');
							$mysqli->query('SET NAMES UTF8');
							$sql="select longitude,latitude from members where wxname='{$fromUsername}'";
							$res=$mysqli->query($sql);
							if($row=mysqli_fetch_array($res)){
								$contentStr="请点击该链接,就可以查询到该地点的信息\r\n http://api.map.baidu.com/place/search?query=".urlencode($address)."&location=".$row['latitude'].",".$row['longitude']."&radius=1000&output=html&src=yourCompanyName|yourAppName";
								$msgType = "text";
								$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
								echo $resultStr;
							}
							else{
								$contentStr="你还没上报地理位置,请发送你的地理位置";
								$msgType = "text";
								$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
								echo $resultStr;
							}
						}

						break;

					case 'location':
						$Location_X=$postObj->Location_X;
						$Location_Y=$postObj->Location_Y;
						$contentStr="您好!\r\n 我们已收到您上报的地理位置 \r\n 经度:{$Location_Y} \r\n 维度:{$Location_X} \r\n 请您输入你关心的地方,即可查询,格式cxwz+地名(cxwz肯德基) ";
						$msgType = "text";
						$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                		echo $resultStr;
						$mysqli=new mysqli('127.0.0.1','root','','landy');
						//mysql_select_db('landy');
						$mysqli->query('SET NAMES UTF8');
						$sql="select wxname from members where wxname='{$fromUsername}'";
						$res=$mysqli->query($sql);
						if($row=mysqli_fetch_array($res)){
							//更新
							$sql="update members set longitude='{$Location_Y}',latitude='{$Location_X}',join_time='{$time}' where wxname='{$fromUsername}'";
							$mysqli->query($sql);
						}
						else{
							$sql="insert into members(wxname,longitude,latitude,join_time) values('{$fromUsername}','{$Location_Y}','{$Location_X}','{$time}')";
							$mysqli->query($sql);
						}
						break;
					default:
						break;
				}


				/*if(!empty( $keyword ))
                {
              		$msgType = "text";
					
					$contentStr='回复的内容';
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }else{
                	echo "Input something...";
                }*/

        }else {
        	echo "";
        	//exit;
        }
    }
		
	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 );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}

	public function get_access_token(){
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx26539d4ea08dec80&secret=07ebc292538dd03c07eb2b4881f39821";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		$jsoninfo = json_decode($output, true);
		$access_token = $jsoninfo["access_token"];
		if($access_token){
			return $access_token;
		}
		else{
			return "获取access_token失败";
		}
	}

	public function create_menu(){
		$data="{button\":[{\"type\":\"click\",\"name\":\"今日歌曲\",\"key\":\"V1001_TODAY_MUSIC\"},{\"name\":\"菜单\",\"sub_button\":[{\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://www.soso.com/\"},{\"type\":\"miniprogram\",\"name\":\"wxa\",\"url\":\"http://mp.weixin.qq.com\",\"appid\":\"wx286b93c14bbf93aa\",\"pagepath\":\"pages/lunar/index\"},{\"type\":\"click\",\"name\":\"赞一下我们\",\"key\":\"V1001_GOOD\"}]}]}";
		$access_token=$this->get_access_token();
		echo $access_token;
		$url=" https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		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_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		if (curl_errno($ch)) {
		  return curl_error($ch);
		}
		curl_close($ch);
		return $tmpInfo;
	}
}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值