这些日子一直忙着赶项目,博客又被冷落了。今儿抽个时间来整理下这段时间做的内容, 比较重点的就是微信公众号获取用户信息的接口开发。这里主要说下微信订阅号,服务号如果对这方面有过接触的朋友都知道,服务号可以通过网页授权的方式来进行获取,很方便和简单,订阅号不行,没有这个权限。在网上也找了点资料,零零散散的。所以这次把这些总结一下。方便后面查阅。

微信订阅号获取用户信息,主要是 OpenID  来通过接口的到用户信息,目前做的这种方法是需要通过自定义菜单触发事件的方式来得到。也就是说需要我们分两步来进行,第一步通过代码创建自定义代码,第二步通过点击事件回调来得到我们的需要的信息,下面就分这两部来说明。使用的方法 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013 官方也有说明,大家也可以去了解一下。

我在网上找了一段代码封装好的类和方法,可以很方便的提供给我们使用。创建一个PHP文件比如 index.php 将下面的代码放进去

<?php
header("Content-type:text/html;charset=utf-8");
define("TOKEN", "weblog");  //令牌
$appid = "你得AppID";
$secret = "你得密钥";
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
}else{
$wechatObj->valid();
}

//$jsonmenu = '{
// "button":[
// {
//    "type":"view",
//    "name":"欢迎访问",
//    "url":"http://www.favortt.com"
// },
// {
//    "type":"click",
//    "name":"磊子的博客",
//    "key":"opid"
// }]
//}';
//////第一步:取全局access_token
//$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
//$token = getJson($url);

//echo '<pre>';
//print_r($token);
//echo '</pre>';

//这部分是创建菜单
//$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$token['access_token'];
//$result = https_request($url, $jsonmenu);
//echo '<pre>';
//print_r($result);
//echo '</pre>';

//
////第三步:根据全局access_token和openid查询用户信息
//$access_token = $token["access_token"];
//$openid = $oauth2['openid'];
//$get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
//$userinfo = getJson($get_user_info_url);

function getJson($url){
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $output = curl_exec($ch);
   curl_close($ch);
   return json_decode($output, true);
}



class wechatCallbackapiTest{
   public function valid() { $echoStr = $_GET["echostr"];
      if($this->checkSignature()){ echo $echoStr; exit; }
   }
   private function checkSignature()
   {
      $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 responseMsg()
   {
      //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      $postStr = file_get_contents('php://input');
      if (!empty($postStr)){
         $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
         $RX_TYPE = trim($postObj->MsgType);
         switch ($RX_TYPE)
         {
            case "text":
               $resultStr = $this->receiveText($postObj);
               break;
            case "event":
               $resultStr = $this->receiveEvent($postObj);
               break;
            default:
               $resultStr = "";
               break;
         }
         echo $resultStr;
      }else {
         echo "111";
         exit;
      }
   }
   private function receiveText($object)
   {
      $funcFlag = 0;
      $contentStr = "你发送的内容为:".$object->Content;
      $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
      return $resultStr;
   }
   private function receiveEvent($object)
   {
      $contentStr = "";
      switch ($object->Event)
      {
         case "subscribe":
            $contentStr = "欢迎磊子博客";
         case "unsubscribe":
            break;
         case "CLICK":
            switch ($object->EventKey)
            {
               case "opid":
                  $contentStr[] = array(
                     "Title"=>"OpenID", 
                     "Description"=>"获取到的openID:".$object->FromUserName, 
                     "PicUrl"=>"", "Url" =>"网站地址?openid=".$object->FromUserName);  //通过一个固定好的URL将openid 传过去
                  break;
               default:
                  $contentStr[] = array(
                     "Title" =>"默认菜单回复",
                     "Description" =>"您正在使用的是",
                     "PicUrl" =>"图片地址",
                     "Url" =>"访问链接"
                  );
                  break;
            }
            break;
         default:
            break;
      }
      if (is_array($contentStr)){
         $resultStr = $this->transmitNews($object, $contentStr);
      }else{
         $resultStr = $this->transmitText($object, $contentStr);
      }
      return $resultStr;
   }
   private function transmitText($object, $content, $funcFlag = 0)
   {
      $textTpl = "<xml>
   <ToUserName><![CDATA[%s]]></ToUserName>
   <FromUserName><![CDATA[%s]]></FromUserName>
   <CreateTime>%s</CreateTime>
   <MsgType><![CDATA[text]]></MsgType>
   <Content><![CDATA[%s]]></Content>
   <FuncFlag>%d</FuncFlag>
</xml>";
      $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $funcFlag);
      return $resultStr;
   }
   private function transmitNews($object, $arr_item, $funcFlag = 0)
   {//首条标题28字,其他标题39字
      if(!is_array($arr_item))
               return;
      $itemTpl = "  <item>
       <Title><![CDATA[%s]]></Title>
       <Description><![CDATA[%s]]></Description>
       <PicUrl><![CDATA[%s]]></PicUrl>
       <Url><![CDATA[%s]]></Url>
     </item>";
      $item_str = "";
      foreach ($arr_item as $item)
         $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
      $newsTpl = "<xml>
   <ToUserName><![CDATA[%s]]></ToUserName>
   <FromUserName><![CDATA[%s]]></FromUserName>
   <CreateTime>%s</CreateTime>
   <MsgType><![CDATA[news]]></MsgType>
   <Content><![CDATA[]]></Content>
   <ArticleCount>%s</ArticleCount>
   <Articles>
      $item_str</Articles>
   <FuncFlag>%s</FuncFlag>
</xml>";
      $resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $funcFlag);return $resultStr;
   }
}

function https_request($url,$data = null){
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
   curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
   if (!empty($data)){
      curl_setopt($curl, CURLOPT_POST, 1);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
   }
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);$output = curl_exec($curl);
   curl_close($curl);
   return $output;
}

里面具体的方法就不一一说明了, 有看到的朋友和正好需要的,不清楚的可以找我,大家一起交流学习。