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

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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不知火猪

如果觉得有帮助,打赏鼓励,3Q

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

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

打赏作者

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

抵扣说明:

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

余额充值