1
收藏
评论

微信公众号获取场景id

微信公众号获取场景id

<?php
namespace app\weixin\controller;
use think\Db;
use think\Controller;
use think\Cache;
 define('TOKEN', 'walaibao');
class Wx extends Common
{
 public  $ToUserName;
   public  $FromUserName;
   public  $MsgType;
   function __construct()
    {
        $this->appid ='*************';
        $this->secrect ='********';
       $accessToken=Cache::get('accessToken');
     if($accessToken){
          $this->accessToken = $accessToken;
        }else{
          $this->accessToken = $this->getToken($this->appid,  $this->secrect);
          Cache::set('accessToken',$this->accessToken ,7200);
       }  
    }
  //入口
   public function wx()
   {
     if (isset($_GET["echostr"])) 
     {   
     	 $echoStr = $_GET["echostr"];
     	if($this->checkSignature()){
          echo  $echoStr;
          exit;
        }
     }else
     {  
            $this->response();
      }
   }
   //验证签名
   public function checkSignature()
   {   
 
   	   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);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature )
        {
            return true;
        }else
        {
            return false;
        }
   }
  //回应
   public function response()
   {
        $postStr=$GLOBALS["HTTP_RAW_POST_DATA"];
  //  file_put_contents('./db.xml', $postStr.PHP_EOL,FILE_APPEND);
   	  if(!empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
   	  	  $postStr=simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
	   	  $this->ToUserName=$postStr->ToUserName;
	   	  $this->FromUserName=$postStr->FromUserName;
	   	  $this->MsgType=$postStr->MsgType;
	   	  $data=$this->dealdata($postStr);
	   	  echo $data;
   	  }else{
   	  	echo '';
   	  }
   	
   }
 
 
 
   //处理数据
   public function  dealdata($postStr){
	   switch ($this->MsgType) {
         case  'event':
             $result=$this->receiveEvent($postStr);
                break;
		     case 'text':
		     $result=$this->receiveText($postStr);
		     break;
		     default:
		    		# code...
		    		break;
		    }
        return $result;
   }
  
   //接收关注消息
    public  function  receiveEvent($postStr){
        $event=$postStr->Event;
        switch($event){
          case "subscribe":
              //查找是否首次关注
             //  $openid=$postStr->FromUserName;
                  //file_put_contents('./dbx.txt', $postStr.PHP_EOL,FILE_APPEND);
               $Content='欢迎关注';
              if (isset($postStr->EventKey)){
                 //file_put_contents('./dbx.txt', $postStr.PHP_EOL,FILE_APPEND);
                 //更新用户对应的场景id
                 
                 $scnce_id=substr($postStr->EventKey,8);
                 db('buyuserinfo')->where('openid',$postStr->FromUserName)->update(['activity_id'=>$scnce_id]);
                 $Content = "关注二维码场景 ".$scnce_id;
            }
         
              $result= $this->transmitsubscribe($postStr,$Content);
          break;
          case "SCAN";
              $scnce_id=$postStr->EventKey;
              $Content = "关注二维码场景 ".$scnce_id;
             //更新用户参加的活动id
              db('buyuserinfo')->where('openid',$postStr->FromUserName)->update(['activity_id'=>$scnce_id]);
              $result= $this->transmitsubscribe($postStr,$Content);
             break;
          case  "unsubscribe":
            $result= $this->transmitunsubscribe($postStr,$Content);
          break;
          case 'CLICK':
                $content=$postStr->EventKey;
              //  file_put_contents('./clidk.txt',$content.PHP_EOL,FILE_APPEND);
              if($content=='CONNECT_US'){
                 $Content='4000992015';
                 $result=$this->transmitText($postStr,$Content);
               }
           break;
        }
       return $result;
     }
   //接收文本消息
    public function receiveText($postStr){
        //存储留言
        $this->save_receive_txt($postStr);
        $Content='已收到您的留言';
        $result=$this->transmitText($postStr,$Content);
        return $result;       
    }
   //存储公众号粉丝留言
    public  function   save_receive_txt($obj){
       $content=$obj->Content;
       $content=$this->parseXml($content);//xml 转 数组
       $openid=$obj->FromUserName;
       //查找公众号粉丝id
       $user_check=db('wx_number')->where('openid',$openid)->field('id')->find();
       //把留言添加数据库
    
         $arr['wx_openid']=$openid;
         $arr['msg']=$content['Content'];
         $arr['ctime']=time();
         $arr['orgin_id']='1';
        db('wx_send_msg')->insert($arr);
    }
 
  //回复普通文本消息
    public function transmitText($obj,$Content){
        $str='
        <xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[%s]]></Content>
         <FuncFlag>0</FuncFlag>
        </xml>';
       $result= sprintf($str,$this->FromUserName,$this->ToUserName,time(),$Content);
        return $result;  
 
    } 
 
    //回复新闻消息
    public function  transmitnews($obj,$Content){
         if (!is_array($Content)) {
            return;
         }
         $item='
          <item>
              <Title><![CDATA[%s]]></Title>
              <Description><![CDATA[%s]]></Description>
              <PicUrl><![CDATA[%s]]></PicUrl>
              <Url><![CDATA[%s]]></Url>
          </item>';   
         $item_str='';
         foreach ($Content as  $v) {
           $item_str.=sprintf($item,$v['Title'],$v['Description'],$v['PicUrl'],$v['Url']);
         }
         $xml='<xml>
                  <ToUserName><![CDATA[%s]]></ToUserName>
                  <FromUserName><![CDATA[%s]]></FromUserName>
                  <CreateTime>%s</CreateTime>
                  <MsgType><![CDATA[news]]></MsgType>
                  <ArticleCount><![CDATA[%s]]></ArticleCount>
                  <Articles>%s</Articles>
              </xml>';
       $result = sprintf($xml, $this->FromUserName, $this->ToUserName, time(),count($Content),$item_str);
        return $result;
    }
  //处理关注事件
    public  function  transmitsubscribe($obj,$Content){
        $openid = $obj->FromUserName;
   //     $this->createuserinfo($openid);
      
         
         //查看是否有图文链接
       // $list=db('subscribe_response')->where('status','1')->where('orgin_id','1')->select();
     // file_put_contents('./dd.txt',json_encode($list).PHP_EOL,FILE_APPEND);
       // if($list){
        //     $Content=array();
       //      foreach($list as $v){
       //        $Content[]=["Title"=>$v['title'],"Description"=>$v['desc'],"PicUrl"=>$v['img_url'], "Url"=>$v['url']];
        //     }
       //   file_put_contents('./dd.txt',json_encode($Content).PHP_EOL,FILE_APPEND);
        //     $result=$this->transmitnews($obj,$Content);
        //     return $result;
       //  }else{
              $str='
              <xml>
              <ToUserName><![CDATA[%s]]></ToUserName>
              <FromUserName><![CDATA[%s]]></FromUserName>
              <CreateTime>%s</CreateTime>
              <MsgType><![CDATA[text]]></MsgType>
              <Content><![CDATA[%s]]></Content>
               <FuncFlag>0</FuncFlag>
              </xml>';
              $result= sprintf($str,$this->FromUserName,$this->ToUserName,time(),$Content);
             return $result;
     //   }
     }
 
   //处理取消关注事件
     public  function  transmitunsubscribe($obj,$Content){
             $openid = $obj->FromUserName;
            // db('wx_number')->where('openid',$openid)->update(['is_subscribe'=>'0']);
     }
 
 
 //用户关注后获取用户信息
    public function createuserinfo($openid)
    {
       //查看openid是否存在
      $user_check=db('wx_number')->where('openid',$openid)->find();
      if($user_check){
          
        db('wx_number')->where('openid',$openid)->update(['is_subscribe'=>'1','subscribetime'=>time()]);
       
       }else{
              $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->accessToken . "&openid=" . $openid;
              $user= $this->request_get($url);
              $user = json_decode($user,true);
              $nickname=urlencode($user['nickname']);
              $users = array(
                  'openid' =>$openid,
                  'nickname' =>$nickname,
                 'faceimgurl' =>$user['headimgurl'],
                 'sex' =>$user['sex'],
                 'status' => 1,
                 'is_subscribe'=>'1',
                 'orgin_id'=>'1',
                 'ctime'=>$user['subscribe_time'],
                 'subscribetime' =>$user['subscribe_time']//关注公众号的时间
              );
              db('wx_number')->insert($users);
       }
    }
    //获取access_token
     protected function getToken($appid, $appsecret)
    {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            $token = $this->request_get($url);
            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];
 
        return $access_token;
    }
 
    //批量获取粉丝列表
    public  function  piliang_x(){
         $access_token=$this->getToken();
         $url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->accessToken ;
         $openid_list=$this->request_get($url);
         $json_info=json_decode($openid_list,true);
         $user_list=$json_info['data']['openid'];
         $user_list[]=$json_info['next_openid'];
         foreach($user_list as $v){
             $user_check=db('wx_number')->where('openid',$v)->field('id')->find();
             if($user_check){
               continue;
             }
              $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->accessToken . "&openid=" . $v;
               $user= $this->request_get($url);
               $user = json_decode($user,true);
               $nickname=urlencode($user['nickname']);
               $users = array(
                  'openid' =>$v,
                  'nickname' =>$nickname,
                 'faceimgurl' =>$user['headimgurl'],
                 'sex' =>$user['sex'],
                 'status' => 1,
                 'is_subscribe'=>'1',
                 'ctime'=>$user['subscribe_time'],
                 'subscribetime' =>$user['subscribe_time']//关注公众号的时间
              );
              db('wx_number')->insert($users);
         }
    }
  
  // 菜单生成
   public  function  menuset(){
           $menu_son[0]['type']='view';
           $menu_son[0]['name']='兑奖中心';
           $menu_son[0]['url']="****************";
           $menu_send['button']=$menu_son;   
        //  var_dump(json_encode($menu_send));exit;
       //  $access_token=$this->getToken();
            $post_url= 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->accessToken;
            $result=$this->request_post($post_url,json_encode($menu_send,JSON_UNESCAPED_UNICODE));
     
            $result=json_decode($result,true);
   
         var_dump($result);
 
    }
 
 //模拟post
     function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }
    /**
     * 发送get请求
     * @param string $url
     * @return bool|mixed
     */
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
  
    //xml转为array
      function parseXml($xmls)
      {
        $array = [];
 
        foreach ($xmls as $key => $xml) {
            /** @var SimpleXMLElement $xml */
            $count = $xml->count();
 
            if ($count == 0) {
                $res = (string) $xml;
            } else {
                $res = parseXml($xml);
            }
 
            $array[$key] = $res;
        }
 
        return $array;
      }

}

代码演示:http://github.crmeb.net/u/LXT

最后一次编辑于  08-15  (未经腾讯允许,不得转载)
复制链接赞 1收藏投诉评论