比较完整的微信开发php代码

前端之家收集整理的这篇文章主要介绍了比较完整的微信开发php代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例为大家分享了微信开发PHP代码,供大家参考,具体内容如下

PHP;"> class WeixinApi
{
private $appid;
private $appsecret;

//构造方法 初始化赋值
public function __construct($appid="",$appsecret="")
{
  $this->appid = $appid;
  $this->appsecret = $appsecret;
}

//验证服务器地址有效性
public function valid()
{
  if($this->checkSignature())
  {
    $echostr = $_GET['echostr'];//<a href="/tag/suiji/" target="_blank" class="keywords">随机</a>的字符串
    return $echostr;
  }
  else
  {
    return "Error";
  }
}

//检查签名
private function checkSignature()
{
  //一、接收微信服务器GET方式提交过来的4个参数数据

  $signature = $_GET['signature'];//微信加密签名

  $timestamp = $_GET['timestamp'];//时间戳

  $nonce = $_GET['nonce'];//<a href="/tag/suiji/" target="_blank" class="keywords">随机</a>数

  //二、加密/校验过程
  // 1. 将token、timestamp、nonce三个参数进行字典序排序;
  // bool sort ( array &$array [,int $sort_flags = SORT_REGULAR ] ) 对数组排序 

  $tmpArr = array(TOKEN,$timestamp,$nonce);//将上面三个参数放到一个数组里面
  sort($tmpArr,SORT_STRING);

  // 2. 将三个参数字符串拼接成一个字符串进行sha1加密;
  $tmpStr = implode($tmpArr); //将数组转化成字符串

  $signatureStr = sha1($tmpStr);

  // 3. 开发者获得加密后的字符串与signature对比。
  if($signatureStr == $signature)
  {
    return true;
  }
  else
  {
    return false;
  }
}

//响应消息
public function responseMsg()
{
  //接收微信服务器发送POST请求到开发者服务器,携带的XML数据包
  $postData = $GLOBALS['HTTP_RAW_POST_DATA'];

  //处理xml数据包
  $xmlObj = simplexml_load_string($postData,"SimpleXMLElement",LIBXML_NOCDATA);

  if(!$xmlObj)
  {
    echo "";
    exit;
  }

  //<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>接收消息中的参数<a href="/tag/neirong/" target="_blank" class="keywords">内容</a>
  $toUserName = $xmlObj->ToUserName;//开发者微信号
  $fromUserName = $xmlObj->FromUserName;//发送方的微信号(openid)
  $msgType = $xmlObj->MsgType;//消息类型
  switch ($msgType) {
    //接收文本消息
    case 'text':
      //<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>文本消息的关键字
      $keyword = $this->receiveText($xmlObj); 
      //进行关键字<a href="/tag/huifu/" target="_blank" class="keywords">回复</a>
      switch($keyword)
      {
        case "w001":
        case "W001":
          return $this->replyText($xmlObj,"Hi~你好");
          break;
        case "w002":
        case "W002":
          return $this->replyText($xmlObj,"Hi~尴尬了");
          break;
        case "笑话":
          $key = "dee9ebc68fd5a61f67286063932afe56";
          return $this->replyNews($xmlObj,$this->joke_text($key));
          break;
        default:
          $key = "dee9ebc68fd5a61f67286063932afe56";
          return $this->replyNews($xmlObj,$this->joke_text($key));
          break;
      }    
      break;
    //接收<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>消息
    case 'image':
      return $this->receiveImage($xmlObj);
      break;
    //接收事件推送
    case 'event':
      return $this->receiveEvent($xmlObj);
      break;
  }      
}

//接收事件推送
public function receiveEvent($obj)
{
  //接收事件类型
  $event = $obj->Event;
  switch ($event)
  {
    //关注事件
    case 'subscribe':
      //下发欢迎消息
      $newsArr = array(
              array(
                "Title"=>"做有价值的头条资讯!","Description"=>"把握价值头条资讯,日常更加有谈资呢!","PicUrl"=>"http://jober.applinzi.com/news/img/news.png","Url"=>"http://jober.applinzi.com/news/index.<a href="/tag/PHP/" target="_blank" class="keywords">PHP</a>"
              )                
            );
      //<a href="/tag/huifu/" target="_blank" class="keywords">回复</a>图文消息
      return $this->replyNews($obj,$newsArr); 
      break;
    //取消关注事件
    case 'unsubscribe':
      //账号的解绑操作等等
      break;
    //<a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a><a href="/tag/caidan/" target="_blank" class="keywords">菜单</a>推送CLICK事件
    case 'CLICK':
      $eventKey = $obj->EventKey;//<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>事件KEY值,与<a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a><a href="/tag/caidan/" target="_blank" class="keywords">菜单</a>接口中KEY值对应
      switch ($eventKey) 
      {
        case 'old':

          $weixinArr = $this->history("da675ebc6a0d72920dca3f676122a693");
          $weixinArr = array_slice($weixinArr,5);
          $newsArr = array();

          foreach ($weixinArr as $item) 
          {
            $newsArr = array(array(
                      "Title" => $item['Description'],"Description" => $item['Title'],"PicUrl" => "http://1.jober.applinzi.com/news/img/2.jpg","Url" => "http://www.todayonhistory.com/"                          
                    ));
          }
          return $this->replyNews($obj,$newsArr);
          break;
      }
    break;
  }
}

//接收文本消息
public function receiveText($obj)
{
  $content = trim($obj->Content);//文本消息的<a href="/tag/neirong/" target="_blank" class="keywords">内容</a>
  return $content;
}

//接收<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>消息
public function receiveImage($obj)
{
  $picUrl = $obj->PicUrl;//<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>的<a href="/tag/lianjie/" target="_blank" class="keywords">链接</a>
  $mediaId = $obj->MediaId;//<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>消息媒体id
  return $this->replyImage($obj,$mediaId);
}

//<a href="/tag/huifu/" target="_blank" class="keywords">回复</a><a href="/tag/tupian/" target="_blank" class="keywords">图片</a>消息
public function replyImage($obj,$mediaId)
{
  $replyXml = "<xml>
          <ToUserName><![CDATA[%s]]></ToUserName>
          <FromUserName><![CDATA[%s]]></FromUserName>
          <CreateTime>%s</CreateTime>
          <MsgType><![CDATA[image]]></MsgType>
          <Image>
            <MediaId><![CDATA[%s]]></MediaId>
          </Image>
        </xml>";
  return sprintf($replyXml,$obj->FromUserName,$obj->ToUserName,time(),$mediaId);

}

//<a href="/tag/huifu/" target="_blank" class="keywords">回复</a>文本消息
public function replyText($obj,$content)
{
  $replyXml = "<xml>
          <ToUserName><![CDATA[%s]]></ToUserName>
          <FromUserName><![CDATA[%s]]></FromUserName>
          <CreateTime>%s</CreateTime>
          <MsgType><![CDATA[text]]></MsgType>
          <Content><![CDATA[%s]]></Content>
        </xml>";
  return sprintf($replyXml,$content);
}

//<a href="/tag/huifu/" target="_blank" class="keywords">回复</a>图文消息
public function replyNews($obj,$newsArr)
{
  //判断是否为数组类型
  if(!is_array($newsArr))
  {
    return;
  }
  // 判断数组是否为空数组
  if(!$newsArr)
  {
    return;
  }
  $itemStr = "";
  //定义item模板
  $itemXml = "<item>
          <Title><![CDATA[%s]]></Title> 
          <Description><![CDATA[%s]]></Description>
          <PicUrl><![CDATA[%s]]></PicUrl>
          <Url><![CDATA[%s]]></Url>
        </item>";
  foreach($newsArr as $item)
  {
    $itemStr .= sprintf($itemXml,$item['Title'],$item['Description'],$item['PicUrl'],$item['Url']);
  }
  $replyXml = "<xml>
          <ToUserName><![CDATA[%s]]></ToUserName>
          <FromUserName><![CDATA[%s]]></FromUserName>
          <CreateTime>%s</CreateTime>
          <MsgType><![CDATA[news]]></MsgType>
          <ArticleCount>".count($newsArr)."</ArticleCount>
          <Articles>".$itemStr."</Articles>
        </xml>"; 
  return sprintf($replyXml,time());     
}

//封装https请求(GET和POST)

protected function https_request($url,$data=null)
{
  //1、初始化curl
  $ch = curl_init();

  //2、设置传输选项
  curl_setopt($ch,CURLOPT_URL,$url);//请求的<a href="/tag/URLdizhi/" target="_blank" class="keywords">URL地址</a>
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//将请求的结果以<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>流的形式返回

  if(!empty($data))
  {
    curl_setopt($ch,CURLOPT_POST,1);//请求POST方式
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//POST提交的<a href="/tag/neirong/" target="_blank" class="keywords">内容</a>
  }

  //3、执行请求并处理结果
  $outopt = curl_exec($ch);

  //把json数据转化成数组
  $outoptArr = json_decode($outopt,TRUE);

  //4、<a href="/tag/guanbi/" target="_blank" class="keywords">关闭</a>curl
  curl_close($ch);

  //如果返回的结果$outopt是json数据,则需要判断一下
  if(is_array($outoptArr))
  {  
    return $outoptArr;
  }
  else
  {
    return $outopt;
  }      
}

public function juhe_weixin($key,$type)
{
  $url ="http://v.juhe.cn/toutiao/index?type={$type}&key={$key}";
  $result = $this->https_request($url);
  if($result['error_code'] == 0)
  {
    return $result['result']['data'];
  }
  else
  {
    return array();
  }
}

//聚合数据-<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>最新趣图
public function joke_text($key,$pagesize=10)
{
  $url = "http://japi.juhe.cn/joke/img/text.from?key={$key}&pagesize={$pagesize}";
  $jokeArr = $this->https_request($url);
  $resultArr = $jokeArr['result']['data'];
  // $content = $resultArr[0]['content'];
  // return $this->replyText($xmlObj,$content);

  $newsArr = array();
  //判断笑话接口是否<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>数据
  if($jokeArr['error_code'] == 0)
  {
    foreach($resultArr as $item)
    {
      $newsArr[] = array(
            "Title"=>$item['content'],"Description"=>$item['updatetime'],"PicUrl"=>$item['url'],"Url"=>$item['url']
          );
    }        
  }
  return $newsArr;
}


//聚合数据-<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>历史上的今天

public function history($key)
{
  $m = idate('m');
  $d = idate('d');
  $day = "{$m}/{$d}";

  $url = "http://v.juhe.cn/todayOnhistory/queryEvent.<a href="/tag/PHP/" target="_blank" class="keywords">PHP</a>?key={$key}&date={$day}";
  $historyArr = $this->https_request($url);
  $resultArr = $historyArr['result'];
  // $content = $resultArr['title'];
  // return $this->replyText($xmlObj,$content);

  $newsArr = array();
  //判断接口是否<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>数据
  if($jokeArr['error_code'] == 0)
  {
    foreach($resultArr as $item)
    {
      $newsArr[] = array(
            "Title"=>$item['title'],"Description"=>$item['date'],"PicUrl"=>"","Url"=>""
          );
    }        
  }
  return $newsArr;
}

public function fund($key)
{

  $url = "http://japi.juhe.cn/jingzhi/query.from?key={$key}";
  $fundArr = $this->https_request($url);
  $resultArr = $fundArr['result'];
  // $content = $resultArr['title'];
  // return $this->replyText($xmlObj,$content);

  $newsArr = array();
  //判断接口是否<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>数据
  if($jokeArr['error_code'] == 0)
  {
    foreach($resultArr as $item)
    {
      $newsArr[] = array(
            "Title"=>$item['day'],"Description"=>$item['title'],"Url"=>"http://www.baidu.com"
          );
    }        
  }
  return $newsArr;
}

/**
  *<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>基础<a href="/tag/zhichi/" target="_blank" class="keywords">支持</a>里面的接口<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>凭证access_token并缓存access_token
  *@return access_token string 接口凭证
**/
public function getAccessToken()
{
  //<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>memcache缓存的access_token
  $access_token = $this->_memcache_get("access_token");
  //如果缓存的access_token失效
  if(!$access_token)
  {  
    //如果失效<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a><a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>接口凭证来<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>access_token
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
    $outoptArr = $this->https_request($url);
    if(!isset($outoptArr['errcode']))
    {
      //memcache缓存access_token
      $this->_memcache_set("access_token",$outoptArr['access_token'],7000);
      return $outoptArr['access_token'];
    }
  }  
  return $access_token;
}

//初始化memcache
private function _memcache_init()
{
  $mmc = new Memcache;
  $ret = $mmc -> connect();
  if ($ret == false) 
  {
    return;
  } 
  return $mmc;
}

//设置memcache
private function _memcache_set($key,$value,$time=0)
{
  $mmc = $this->_memcache_init();
  $mmc -> set($key,$time);
}

//<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>memcahce
private function _memcache_get($key)
{
  $mmc = $this->_memcache_init(); 
  return $mmc -> get($key);  
}

//<a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a><a href="/tag/caidan/" target="_blank" class="keywords">菜单</a>创建

public function menu_create($data)
{
  $access_token = $this->getAccessToken();
  //<a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a><a href="/tag/caidan/" target="_blank" class="keywords">菜单</a>创建接口地址
  $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
  return $this->https_request($url,$data);
}

//<a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a><a href="/tag/caidan/" target="_blank" class="keywords">菜单</a><a href="/tag/shanchu/" target="_blank" class="keywords">删除</a>
public function menu_delete()
{
  $access_token = $this->getAccessToken();
  $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$access_token}";
  return $this->https_request($url);
}

}
?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

猜你在找的PHP相关文章