php之微信公众号开发(一)接入微信验证和创建自定义菜单

作者:qq_21405949

0x00首先申请微信测试公众号->记录下aapid以及appsecrt;下载官方实例demo代码;修改token值;把代码上传到服务器;把文件名重命名为index.php或其他。并用浏览器访问一下,为空则通过验证。在微信公众平台配置URL和tokenURL为公网可以访问到的ip或者地址,token随意;验证通过之后删除或注释valid方法;否则后面服务测试任何代码操作;验证通过之后就可以编写自己的代码了0x01 创建自定义菜单:首先得先去获取access_token获取方式打开浏览器请求:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret;请求之后就可以看到你的access_token了,返回内容如下:


<span style="font-size:24px;">{"access_token":"ObNj66mQgTzQYW9ttryDRN2jTrxfo_cKWMN5lZR0rmjSOwITdabWKrjK1U8MdcuxBss40l111pNr-CzfZoaPwnoTV9gwdC7hc1hWh4ZMU6tAMaNzB5DallrgcbHGzG_uJPPjAFAUAA","expires_in":7200}</span>





创建自定义菜单文件 Menu.php


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

//define your token
header("Content-type:text/html;charset=utf-8");
define("ACCESS_TOKEN","你的access_token");

define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg();
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 = $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);
                $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>";             
				if($postObj->MsgType =="event"&&$postObj->Event=="subscribe"){
					$msgType = 'text';
					$cont = '欢迎关注';
					echo sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$cont);
				}elseif($postObj->MsgType =="image"){
					$msgType = 'text';
					$cont = '你长得真好看';
					echo sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$cont);
				
				}elseif($keyword=='音乐'){
							$textTpl="<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>";
									$msgType = 'music';
									$title="mmmm";
									$desc="一首好听的音乐";
									
									$url = "http://chenkaixuan.com/wechat/YoungRisingSons-High.mp3";
							$msgType = 'news';
							$title="默认标题";
							$desc="信息描述";
							
							
					echo sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$title,$desc,$url,$url);
							
				}
				elseif($keyword=='图片消息'){
							$textTpl="<xml>
										<ToUserName><![CDATA[%s]]></ToUserName>
										<FromUserName><![CDATA[%s]]></FromUserName>
										<CreateTime>%s</CreateTime>
										<MsgType><![CDATA[%s]]></MsgType>
										<Image>
										<MediaId><![CDATA[%s]]></MediaId>
										</Image>
										</xml>";
									$msgType = 'image';
									$title="mmmm";
									$desc="一首好听的音乐";
									
									$url = "http://chenkaixuan.com/wechat/YoungRisingSons-High.mp3";
							$msgType = 'news';
							$title="默认标题";
							$desc="信息描述";
							
							
					echo sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$title,$desc,$url,$url);
							
				}

				elseif($postObj->MsgType =="location"){
					$msgType = 'text';
					$jd=$postObj->Location_Y;
					$wd=$postObj->Location_X;
					$cont="目标位于东经{$jd},北纬{$wd}";
					echo sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$cont);
				}elseif($keyword=='图文消息'){
					$msgTpl = "<xml>
								<ToUserName><![CDATA[%s]]></ToUserName>
								<FromUserName><![CDATA[%s]]></FromUserName>
								<CreateTime>%s</CreateTime>
								<MsgType><![CDATA[%s]]></MsgType>
								<ArticleCount>%s</ArticleCount>
								<Articles>
								<item>
								<Title><![CDATA[%s]]></Title> 
								<Description><![CDATA[%s]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
								</item>
								</Articles>
								</xml>";
					echo sprintf($msgTpl, $fromUsername, $toUsername, $time, 'news',1,'测试标题','描述描述描述','http://chenkaixuan.com/wechat/pic.jpg','http://chenkaixuan.com/');			
				}elseif(!empty( $keyword )){
					if($keyword=='天气'){
						$contentStr = "今天天气不错!";	
					}elseif($keyword=='快递'){
						$contentStr = "快递运输中!";	
					}else{
						$contentStr = "不知道你在说什么!";
					}
              		$msgType = "text";
                	//$contentStr = "Welcome to wechat world!";
                	$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;
		}
	}
}




function createMenu($data){
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ObNj66mQgTQYW9ttryDRN2jTrxfo_cKWMN5lZR0rmjSOwITdabWKrjK1U8MdcuxBss40lVYapNr-CzfZoaPwnoTV9gwdC7hc1hWh4ZMU6tAMaNzB5DallrgcbHGzG_uJPPjAFAUAA");

	curl_setopt($ch,CURLOPT_CUSTOMERQUEST,"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,CURL_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;
}

//获取菜单

function getMenu(){
	return file_get_contents("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ObNj66mQgTzQYW9tryDRN2jTrxfo_cKWMN5lZR0rmjSOwITdabWKrjK1U8MdcuxBss40lVYapNr-CzfZoaPwnoTV9gwdC7hc1hWh4ZMU6tAMaNzB5DallrgcbHGzG_uJPPjAFAUAA")
}


//删除菜单

function deleteMenu(){
	return file_get_contents("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ObNj66mQgTzQW9ttryDRN2jTrxfo_cKWMN5lZR0rmjSOwITdabWKrjK1U8MdcuxBss40lVYapNr-CzfZoaPwnoTV9gwdC7hc1hWh4ZMU6tAMaNzB5DallrgcbHGzG_uJPPjAFAUAA")
}


//自定义菜单的json格式数据,需要用单引号包含在里面
$data = '{
    "button": [
        {
            "type": "click", 
            "name": "今日歌曲", 
            "key": "V1001_TODAY_MUSIC"
        }, 
        {
            "name": "菜单", 
            "sub_button": [
                {
                    "type": "view", 
                    "name": "搜索", 
                    "url": "http://weidian.com/?userid=337883018&wfr=wx_profile"
                }, 
                {
                    "type": "view", 
                    "name": "视频", 
                    "url": "http://v.qq.com/"
                }, 
                {
                    "type": "click", 
                    "name": "赞一1下我们", 
                    "key": "V1001_GOOD"
                }
            ]
        }
    ]
}';

echo createMenu($data);


?>







发表评论

0个评论

我要留言×

技术领域:

我要留言×

留言成功,我们将在审核后加至投票列表中!

提示x

微信开发知识库已成功保存至我的图谱现在你可以用它来管理自己的知识内容了

删除图谱提示×

你保存在该图谱下的知识内容也会被删除,建议你先将内容移到其他图谱中。你确定要删除知识图谱及其内容吗?

删除节点提示×

无法删除该知识节点,因该节点下仍保存有相关知识内容!

删除节点提示×

你确定要删除该知识节点吗?