网站地图    收藏   

主页 > 后端 > 微信开发 >

微信公众平台开发尝试 - 微信公众平台开发:微

来源:自学PHP网    时间:2015-04-14 12:58 作者: 阅读:

[导读] 最近看了一篇博文是说微信公众平台搭建,于是心血来潮自己也尝试了一下。1 不用多讲了,申请微信公众号,对于个人来说,只能申请订阅号。2 采用的是Sina App Engine来脱管服务,就要...

最近看了一篇博文是说微信公众平台搭建,于是心血来潮自己也尝试了一下。

1.不用多讲了,申请微信公众号,对于个人来说,只能申请订阅号。

2.采用的是Sina App Engine来脱管服务,就要申请sae开发者权限。

3.在sae上新建一个应用

\

\

我选择的PHP,PHP几乎免费。Java应用的话,有点小贵了。

虽然没有学过PHP,摸着石头过河吧。

将php代码上传后,就有一个可调试的url了,PHP代码后面上。

\

4.再在微信公众平台中的开发者中心(这个要经过一段时间的审核),填入一下内容即可

\

5.然后就是对接数据了,为了测试,我对接的是图灵机器人的数据、12306和百度地图API

12306是为了查余票和车次,百度地图API是为了查天气预报、图灵机器人见链接:http://www.tuling123.com/openapi/

php代码如下,本人不是搞PHP的,因此只能在网上拷贝了,如有复制,纯属巧合。

<?php
    
 define("TOKEN", "weixin");

    Session_start();

    Session_Register("kw");


    $wechatObj = new wechatCallbackapiTest();
    require_once("train.php");

    $tqTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <ArticleCount>5</ArticleCount> <Articles> <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> </Articles> </xml> ";
    if (!isset($_GET['echostr'])) {
        $wechatObj->responseMsg();
    }else{
        $wechatObj->valid();
    }

    class wechatCallbackapiTest
    {
        //验证签名
        public function valid()
        {
            $echoStr = $_GET["echostr"];
            $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){
                echo $echoStr;
                exit;
            }
        }

        //响应消息
        public function responseMsg()
        {
            $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
            if (!empty($postStr)){
                $this->logger("R ".$postStr);
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $RX_TYPE = trim($postObj->MsgType);
                 
                //消息类型分离
                switch ($RX_TYPE)
                {
                    case "event":
                        $result = $this->receiveEvent($postObj);
                        break;
                    case "text":
                        $result = $this->receiveTulingText($postObj);
                        break;
                    case "image":
                        $result = $this->receiveImage($postObj);
                        break;
                    case "location":
                        $result = $this->receiveLocation($postObj);
                        break;
                    case "voice":
                        $result = $this->receiveVoice($postObj);
                        break;
                    case "video":
                        $result = $this->receiveVideo($postObj);
                        break;
                    case "link":
                        $result = $this->receiveLink($postObj);
                        break;
                    default:
                        $result = "unknown msg type: ".$RX_TYPE;
                        break;
                }
                $this->logger("T ".$result);
                echo $result;
            }else {
                echo "";
                exit;
            }
        }

        //接收事件消息
        private function receiveEvent($object)
        {
            $content = "";
            switch ($object->Event)
            {
                case "subscribe":
                    $content = "欢迎关注TomSnail ";
                    $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
                    break;
                case "unsubscribe":
                    $content = "取消关注";
                    break;
                case "SCAN":
                    $content = "扫描场景 ".$object->EventKey;
                    break;
                case "CLICK":
                    switch ($object->EventKey)
                    {
                        case "COMPANY":
                            $content = array();
                            $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
                            break;
                        default:
                            $content = "点击菜单:".$object->EventKey;
                            break;
                    }
                    break;
                case "LOCATION":
                    $content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                    break;
                case "VIEW":
                    $content = "跳转链接 ".$object->EventKey;
                    break;
                case "MASSSENDJOBFINISH":
                    $content = "消息ID:".$object->MsgID.",结果:".$object->Status.",粉丝数:".$object->TotalCount.",过滤:".$object->FilterCount.",发送成功:".$object->SentCount.",发送失败:".$object->ErrorCount;
                    break;
                default:
                    $content = "receive a new event: ".$object->Event;
                    break;
            }
            if(is_array($content)){
                if (isset($content[0])){
                    $result = $this->transmitNews($object, $content);
                }else if (isset($content['MusicUrl'])){
                    $result = $this->transmitMusic($object, $content);
                }
            }else{
                $result = $this->transmitText($object, $content);
            }

            return $result;
        }

        private function receiveTulingText($object){
            try{
                $keyword = trim($object->Content);
                $userid = trim($object->FromUserName);

                $apiKey = "*******************************"; 
                $apiURL = "http://www.tuling123.com/openapi/api?key=".$apiKey."&info=".$keyword."&userid=".userid;
                
                
               if((substr_count($keyword,'天气')!=0)||$_SESSION["kw"]=="天气"){  //百度地图API
                    if($keyword=="天气"){
                        $_SESSION["kw"]="天气";
                        $content = "请输入城市".$_SESSION["kw"];
                    }else{
                        $geshu = substr_count($keyword,'天气');    
                        if($geshu==0){
                            $city = $keyword;
                        }else{
                             $t = explode("天气",$keyword);         
                             for($i=0;$i<=$geshu;$i++)    
                                {     
                              if($t[$i]!='')     
                              {     
                            $city = $t[$i];     
                            break;     
                              }         
                             }   
                    }
                
                 $mykey ="*********************";   
                 $url = "http://api.map.baidu.com/telematics/v3/weather?location=".$city."&output=json&ak=".$mykey;    
                 $output = file_get_contents($url);    
                 $contentStr = json_decode($output, true);        
                       
                 if($contentStr['status']=='success')    
                 {           
                    $T[0]['Title']=$contentStr['date']." ".$contentStr['results'][0]['currentCity']."天气"; 
                    $T[0]['PicUrl']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg"; 
                    $T[0]['Url']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg";     
                    if(is_array($contentStr['results'][0]['index']))     
                    {     
                        $T[2]['Title']="【pm2.5】".$contentStr['results'][0]['pm25']."\n"."【".$contentStr['results'][0]['index'][0]['title']."】"."(".$contentStr['results'][0]['index'][0]['zs'].") ".$contentStr['results'][0]['index'][0]['des'];     
                    //下一行是洗车指数,感觉不对主题还是不要的好。。     //$T[2]['Title']=$T[2]['Title']."\n"."【".$contentStr['results'][0]['index'][1]['title']."】(".$contentStr['results'][0]['index'][1]['zs'].")".$contentStr['results'][0]['index'][1]['des'];  
                        $T[2]['Title']=$T[2]['Title']."\n"."【".$contentStr['results'][0]['index'][2]['title']."】(".$contentStr['results'][0]['index'][2]['zs'].")".$contentStr['results'][0]['index'][2]['des'];     
                    }     
                    else    
                        $guowai=1;  
                    for($i=1,$aaa=0;$i<=5;$i++)     
                    {     
                        if($i==2 && $guowai!=1)      
                            continue;     
                        if($guowai==1 && $i==5)      
                            continue;     
                        $T[$i]['Title']=$contentStr['results'][0]['weather_data'][$aaa]['date']."".$contentStr['results'][0]['weather_data'][$aaa]['temperature']."".$contentStr['results'][0]['weather_data'][$aaa]['weather']." ".$contentStr['results'][0]['weather_data'][$aaa]['wind'];             
                        $T[$i]['PicUrl']=$contentStr['results'][0]['weather_data'][$aaa]['dayPictureUrl'];     
                        $T[$i]['Url']=$contentStr['results'][0]['weather_data'][$aaa]['dayPictureUrl'];     
                        $aaa++;     
                     }      
                     $content = $T;
                    
                 }     
                    }
                        
                    
                
               }else if(substr_count($keyword,'火车')!=0 && $keyword!='火车'){//12306
                    $geshu = substr_count($keyword,'火车:'); 
                    $k = str_replace('火车 ', "", $keyword);
                    $t = explode(" ",$k);
                    $startstaion = $t[0];
                    $endstation = $t[1];
                    $date =$t[2];
                    if($date==null){
                        $date = date("Y-m-d",time());
                    }
                    if(substr_count($date,'-')==0){
                       $date = date("Y-m",time())."-".$date;
                    }
                    $time =$t[3];
                    if($time==null){
                        $time = "00:00";
                    }
                    if(substr_count($time,':')==0){
                        $time = $time.":00";
                    }
                    
                    $data = gettrain($startstaion,$endstation,$date,$time);
                    $str="";
                    $T[0]['Title']=$startstaion."到".$endstation." ".$date." ".$time."以后10列火车信息"; 
                    $T[0]['PicUrl']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg"; 
                    $T[0]['Url']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg";     
                    $count = 1;
                    foreach($data as $key =>$value){
                        $str=$count." ";
                        $str.="火车列次:{$data[$key]['station_train_code']}\n";
                        $str.="始发站:{$data[$key]['start_station_name']},终点站:{$data[$key]['end_station_name']}\n";
                        $str.="出发时间:{$data[$key]['start_time']},到站时间:{$data[$key]['arrive_time']},历时:{$data[$key]['lishi']}\n";
                        $str.="一等座:{$data[$key]['zy_num']}\n二等座:{$data[$key]['ze_num']}\n硬座:{$data[$key]['yz_num']}\n硬卧:{$data[$key]['yw_num']}\n";
                         $str.="软卧:{$data[$key]['rw_num']}\n软座:{$data[$key]['rz_num']}\n特等座:{$data[$key]['tz_num']}\n无座:{$data[$key]['wz_num']}";
                        $count = $count+1;
                        $T[$count]['Title'] = $str;
                        // $T[$count]['Url']="http://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=".$data[$key]["train_no"]."&from_station_no=".$data[$key]["from_station_no"]."&to_station_no=".$data[$key]["to_station_no"]."&seat_types=".$data[$key]["seat_types"]."&train_date=$date";
                        $T[$count]['Url'] = "https://kyfw.12306.cn/otn/login/init";
                        if($count==10){
                        break;}
                    }
                    $content =  $T;
               }else{//图灵机器人
                   
                     $file_contents = file_get_contents($apiURL);
                $file_contents = json_decode($file_contents,true);
                $code = $file_contents["code"];
                if($code==100000){
                    $content = $file_contents["text"];
                }else if($code==200000){
                    $T[0]['Title']=$file_contents["text"]; 
                    //$T[0]['PicUrl']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg"; 
                    $T[0]['Url']=$file_contents["url"];  
                     $content = $T;
                }else if($code==302000){
                       $T[0]['Title']=$file_contents["text"]; 
                    $T[0]['PicUrl']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg"; 
                    $T[0]['Url']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg";  
                    $data = $file_contents["list"];
                    $count = 1;
                    foreach($data as $key =>$value){
                            $T[$count]['Title']=$data[$key]["article"]; 
                            $T[$count]['PicUrl']=$data[$key]["icon"]; 
                            $T[$count]['Url']=$data[$key]["detailurl"];  
                            $count++;
                    }
                     $content = $T;
                }else if($code==305000){
                    $T[0]['Title']=$file_contents["text"]; 
                    $T[0]['PicUrl']="http://zhengwairen-try2.stor.sinaapp.com/xytq.jpg"; 
             
                    
                    

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论