微信公众号常用开发笔记
responMsg(); } } //接受 事件推送并回复 public function responMsg(){ //1、获取微信 推送过来的post数据(xml 格式) $postXml=$GLOBALS['HTTP_RAW_POST_DATA']; // $postXml=file_get_contents('php://input'); //2、处理消息类型,并回复消息类型和内容 $postObj=simplexml_load_string($postXml); //把xml 转换成对象 //事件推送微信官方模板 推送XML数据包示例 /* 开发者微信号 发送方帐号(一个OpenID) 123456789 消息创建时间 (整型) 消息类型,event 事件类型,subscribe(订阅)、unsubscribe(取消订阅) */ //有以下的几个对象属性可调用 //$postObj->ToUserName=''; // //$postObj->FromUserName=''; //$postObj->CreateTime=''; //$postObj->MsgType=''; //$postObj->Event=''; $toUser=$postObj->FromUserName; //接收方 $fromUser=$postObj->ToUserName; //发送方 微信公众号 if(strtolower($postObj->MsgType)=='event'){ if(strtolower($postObj->Event)=='click'){ switch($postObj->EventKey){ case 'V1001_GOOD': $content='感谢您的点赞!!!'; break; default: $content='没有赞成功哦!!!'.$postObj->EventKey; break; } $this->text($toUser,$fromUser,$content); }elseif((strtolower($postObj->Event)=='scan')){ //用户扫描二维码时间 if($postObj->EventKey){ $this->text($toUser,$fromUser,$postObj->EventKey); }else{ $this->text($toUser,$fromUser,'暂时没有用的参数'); } } } } public function text($toUser,$fromUser,$content){ //文本模板xml格式 // ToUserName 接收方帐号(收到的OpenID) // FromUserName 开发者微信号 // CreateTime 消息创建时间 (整型) // MsgType text 文本消息固定格式 // Content 回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示) $template="%s"; $createTime=time(); //格式化xml 把变量替换[]里面的toUser等 $info = sprintf($template,$toUser,$fromUser,$createTime,$content); echo $info; } //curl 发送HTTP请求 public function HttpCurl($url,$type='get',$rst='json',$arr=array()){ //1、初始化curl $ch=curl_init(); //2、设置curl参数 curl_setopt($ch,CURLOPT_URL,$url); //连接参数 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置返回值 if($type=='post'){ curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$arr); } //采集 $info=curl_exec($ch); curl_close($ch); if($rst=='json'){ return json_decode($info,true); }else{ return $info; } } //获取微信access_token并且放在session里 public function getWxAccessToken(){ $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appserect; $info=$this->HttpCurl($url,'get','json'); if($info['errcode']){ exit('错误代码:'.$info['errcode']); } //如果session中存在且没有过期 if($_SESSION['access_token'] && $_SESSION['token_end_time'] > time()){ return $_SESSION['access_token']; }else{ $_SESSION['access_token']=$info['access_token']; $_SESSION['token_end_time']=time()+7000; return $_SESSION['access_token']; } } //获取access_token /*public function getAccessToken(){ //微信获取access_token地址 GET 方式 $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appserect; //1初始化curl $ch=curl_init(); //2设置参数 curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); //3、获取内容 $rst=curl_exec($ch); //4、关闭curl连接 curl_close($ch); //5、如果有curl错误则打印 if(curl_errno($ch)){ exit(curl_errno($ch)); } //微信返回的事json所有要转换成数组 $info=json_decode($rst,true); var_dump($info); } */ //获取微信服务器ip地址列表 public function getWxServerIp(){ $accessToken='PWKMPWaAqx0qxzd1_7aIbZeDA1__Gm19s_MrhvJ3eFhqqTHB5OAKQXeWmeiBehVqray9dm9bQhJwQiqrgcVBFRKGavxZpOtm8BSQrfj1aeLowqRCRxP_x8QG5GCsrdiSVOWiACAIBJ'; //获取微信服务器ip地址 $url='https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token='.$accessToken; $ch=curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $rst=curl_exec($ch); curl_close($ch); if(curl_errno($ch)){ exit(curl_errno($ch)); } $arr=json_decode($rst,true); $this->vdump($arr); } public function vdump($arr){ echo ''; var_dump($arr); echo ''; } //创建自定义菜单 public function addMenu(){ header('content-type:text/html;charset=utf-8'); $access_token=$this->getWxAccessToken(); $url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token; $str=' { "button":[ { "type":"view", "name":"官网", "url":"http://www.90dreamb.com" }, { "name":"菜单", "sub_button":[ { "type":"view", "name":"搜索", "url":"http://www.soso.com/" }, { "type":"view", "name":"视频", "url":"http://v.qq.com/" }, { "type":"click", "name":"赞一下我们", "key":"V1001_GOOD" }] }, { "type":"view", "name":"最新文章", "url":"http://www.90dreamb.com" } ] }'; echo $access_token; // session_destroy(); $info=$this->HttpCurl($url,'post','json',$str); $this->vdump($info); } //推送群发位文本消息 function sendMsgAll(){ //获取access_token $access_token=$this->getWxAccessToken(); //请求地址 预览接口 100次, $url="https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$access_token; //组装群发接口数据 /* 文本模板{ "touser":"OPENID", "text":{ "content":"CONTENT" }, "msgtype":"text" } 图片模板 { "touser":"OPENID", "image":{ "media_id":"123dsdajkasd231jhksad" }, "msgtype":"image" } */ $array=array( 'touser'=>'oB6Zqw_wcTUeMPPUHukP9lRRan8E', //群发接收消息的openid可多个 'image'=>array('media_id'=>'123dsdajkasd231jhksad'), //群发文本内容 'msgtype'=>'image' //消息类型 ); //将数组转成json格式 $jsonInfo=json_encode($array); //调用CURL $info=$this->HttpCurl($url,'post','json',$jsonInfo); $this->vdump($info); } //发送模板消息 function sendTemplateMsg(){ //获取access_token $access_token=$this->getWxAccessToken(); $url='https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token; //添加文本模板内容 /*{ "touser":"OPENID", "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY", "url":"http://weixin.qq.com/download", "data":{ "first": { "value":"恭喜你购买成功!", "color":"#173177" } } }*/ $array=array( 'touser'=>'oB6Zqw_wcTUeMPPUHukP9lRRan8E', //接收者openid 'template_id'=>'xewRYLRYOdDL2zXBLW_YiUOJ1usj1iQ6xokVwADB6Bc', //模板id 'url'=>'http://www.90dreamb.com', 'data'=>array( 'name'=>array('value'=>'我是天蝎你是蝴蝶','color'=>'#88888'),//自定义变量name 'age'=>array('value'=>'你的芳龄18','color'=>'#173333'), //自定义变量age 'sex'=>array('value'=>'你的性别是:女','color'=>'#173333'), //自定义变量sex ) ); //转json格式 $jsonInfo=json_encode($array); //发送curl $info=$this->HttpCurl($url,'post','json',$jsonInfo); $this->vdump($info); } //微信网页授权 步骤1 function getWxUserCode(){ $appId=$this->appid; //跳转地址 $redirectUrl=urlencode('http://www.90dreamb.com/Thinkphp/index.php/Home/Weixin/getWxUserInfo'); $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.$redirectUrl.'&response_type=code&scope=snsapi_userinfo&state=111#wechat_redirect'; //请求地址 返回Code // $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.$redirectUrl.'&response_type=code&scope=snsapi_login&state=111#wechat_redirect'; //请求地址 返回Code header('Location:'.$url); //跳转到getWxUserInfo这个方法,带了code这个参数 } //微信网页授权 步骤2 function getWxUserInfo(){ $appId=$this->appid; $appSecret=$this->appserect; $code=$_GET['code']; $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$appSecret.'&code='.$code.'&grant_type=authorization_code '; $info=$this->HttpCurl($url,'get','json'); $userToken=$info['access_token']; //用户网页授权access_token $userOpenId=$info['openid']; //用户opendi //拉取用户详细信息 $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$userToken.'&openid='.$userOpenId.'&lang=zh_CN'; $info=$this->HttpCurl($url); $this->vdump($info); } //获取微信临时二维码 function getTempCode(){ // 1、首先获取ticket 码 //获取全局token $access_token=$this->getWxAccessToken(); //获取ticket 码 url $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token; //获取ticket 码 数据 {"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}} $array=array( 'expire_seconds'=>'604800', //24*60*60*7 七天有效期最多60天 'action_name' =>'QR_SCENE', 'action_info' =>array( 'scene' =>array( 'scene_id'=>'111111', ), ), ); //转json $jsonInfo=json_encode($array); $info=$this->HttpCurl($url,'post','json',$jsonInfo); //获取ticket 码 $ticket=urlencode($info['ticket']); //获取二维码ticket后,开发者可用ticket换取二维码图片 $url='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket; echo ""; } //获取微信永久二维码 function getCode(){ // 1、首先获取ticket 码 //获取全局token $access_token=$this->getWxAccessToken(); //获取ticket 码 url $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token; //获取ticket 码 数据 {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "123"}}} $array=array( 'action_name' =>'QR_LIMIT_STR_SCENE', 'action_info' =>array( 'scene' =>array( 'scene_str'=>'', //附带参数,事件KEY值,是一个32位无符号整数 ), ), ); //转json $jsonInfo=json_encode($array); $info=$this->HttpCurl($url,'post','json',$jsonInfo); //获取ticket 码 $ticket=urlencode($info['ticket']); //获取二维码ticket后,开发者可用ticket换取二维码图片 $url='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$ticket; echo ""; } //获取微信jsapi_ticket public function getTicket($accessToken){ if(isset($_SESSION['jsapi_ticket']) && $_SESSION['jsapi_ticket_end_time']>time()){ return $_SESSION['jsapi_ticket']; }else{ //获得jsapi_ticket $url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$accessToken.'&type=jsapi'; $info=$this->HttpCurl($url); if($info['errcode']){ die('Get jsapi_ticket ERROR!'); } $_SESSION['jsapi_ticket']=$info['ticket']; $_SESSION['jsapi_ticket_end_time']=time()+7000; return $ticket=$info['ticket']; //获得jsapi_ticket } } //随机获得字符串 public function randStr($num=16){ $array=array( 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',1,2,3,4,5,6,7,8,9,0,'A','B','C','D','E' ); $str=''; $count=count($array); for($i==0;$igetWxAccessToken(); //随机字符串 $noncestr=$this->randStr(); // 获得jsapi_ticket $ticket=$this->getTicket($access_token); //时间戳 $timestamp=time(); //签名算法 $url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; $this->vdump($url); $signature='jsapi_ticket='.$ticket.'&noncestr='.$noncestr.'×tamp='.$timestamp.'&url='.$url; $signature=sha1($signature); // 签名算法 end $this->assign('appid',$this->appid); $this->assign('time_stamp',$timestamp); $this->assign('nonce_str',$noncestr); $this->assign('sigature',$signature); $this->display('share'); } }
Dcr163的博客
http://dcr163.cn/168.html(转载时请注明本文出处及文章链接)