tp5下php微信开发之上传图片素材

时间:2017-07-01 18:24:01   收藏:0   阅读:1310

直接源代码了,比较累不想写了,里面由之前的基本的,本部分功能在最下面的2个函数里。

  1 <?php
  2 
  3 namespace app\index\controller;
  4  
  5 use think\Controller;
  6   
  7 //define your token
  8 define("TOKEN", "weixin");//定义token
  9 
 10 Class Index extends Controller
 11 {
 12     public function index()//接收微信客户端发送的信息并回应! 
 13     {
 14         //get post data, May be due to the different environments
 15         $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];     
 16           //extract post data
 17         if (!empty($postStr)){
 18           /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
 19           the best way is to check the validity of xml by yourself */
 20           libxml_disable_entity_loader(true);
 21           $postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA);
 22           $fromUsername = $postObj->FromUserName;
 23           $toUsername = $postObj->ToUserName;
 24           $keyword = trim($postObj->Content);
 25           $time = time();
 26           $msgType = $postObj->MsgType;//消息类型
 27           $event = $postObj->Event;//时间类型,subscribe(订阅)、unsubscribe(取消订阅)
 28           $textTpl = "<xml>
 29           <ToUserName><![CDATA[%s]]></ToUserName>
 30           <FromUserName><![CDATA[%s]]></FromUserName>
 31           <CreateTime>%s</CreateTime>
 32           <MsgType><![CDATA[%s]]></MsgType>
 33           <Content><![CDATA[%s]]></Content>
 34           <FuncFlag>0</FuncFlag>
 35           </xml>";    
 36           switch($msgType){
 37           case "event":
 38           if($event=="subscribe"){
 39           $contentStr = "Hi,欢迎关注168php微信开发"."\n"."回复数字‘1‘,了解相关基础教程."."\n"."回复数字‘2‘,添加技术交流群.";
 40           } 
 41           break;
 42           case "text":
 43           switch($keyword){
 44           case "1":
 45           $contentStr = "相关教程:"."\n"."<a href=‘http://www.imooc.com/‘>慕课网</a>."; 
 46           break;
 47           case "2":
 48           $contentStr = "技术交流群:"."\n"." QQ群:184037581.";
 49           break;
 50           case "3":
 51           $this->singleGraphic($postObj);
 52           exit;
 53           default:
 54           $contentStr = "对不起,你的内容我会稍后回复";
 55           }
 56           break;
 57           }
 58           $msgType = "text";
 59           $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
 60           echo $resultStr;
 61         }else {
 62            echo "";
 63            exit;
 64         }
 65     }
 66   private  function singleGraphic($postObj) /**多图文回复*/
 67   {
 68     $toUser = $postObj->FromUserName;
 69     $fromUser = $postObj->ToUserName;
 70     $arr = array(
 71         array(
 72           ‘title‘=>‘imooc‘,
 73           ‘description‘=>"imooc is very cool",
 74           ‘picUrl‘=>‘http://www.imooc.com/static/img/common/logo.png‘,
 75           ‘url‘=>‘http://www.imooc.com‘,
 76         ),
 77         array(
 78           ‘title‘=>‘hao123‘,
 79           ‘description‘=>"hao123 is very cool",
 80           ‘picUrl‘=>‘https://www.baidu.com/img/bdlogo.png‘,
 81           ‘url‘=>‘http://www.hao123.com‘,
 82         ),
 83         array(
 84           ‘title‘=>‘qq‘,
 85           ‘description‘=>"qq is very cool",
 86           ‘picUrl‘=>‘http://www.imooc.com/static/img/common/logo.png‘,
 87           ‘url‘=>‘http://www.qq.com‘,
 88          ),
 89       );
 90       $template = "<xml>
 91             <ToUserName><![CDATA[%s]]></ToUserName>
 92             <FromUserName><![CDATA[%s]]></FromUserName>
 93             <CreateTime>%s</CreateTime>
 94             <MsgType><![CDATA[%s]]></MsgType>
 95             <ArticleCount>".count($arr)."</ArticleCount>
 96             <Articles>";
 97       foreach($arr as $k=>$v){
 98         $template .="<item>
 99             <Title><![CDATA[".$v[‘title‘]."]]></Title> 
100             <Description><![CDATA[".$v[‘description‘]."]]></Description>
101             <PicUrl><![CDATA[".$v[‘picUrl‘]."]]></PicUrl>
102             <Url><![CDATA[".$v[‘url‘]."]]></Url>
103             </item>";
104        }
105       $template .="</Articles></xml> ";
106       echo sprintf($template, $toUser, $fromUser, time(), ‘news‘);
107   }
108   private function checkSignature()//验证服务器
109   {
110        // you must define TOKEN by yourself
111       if (!defined("TOKEN")) {
112         throw new Exception(‘TOKEN is not defined!‘);
113       }  
114       $signature = $_GET["signature"];
115       $timestamp = $_GET["timestamp"];
116       $nonce = $_GET["nonce"]; 
117       $token = TOKEN;
118       $tmpArr = array($token, $timestamp, $nonce);
119        // use SORT_STRING rule
120       sort($tmpArr, SORT_STRING);
121       $tmpStr = implode( $tmpArr );
122       $tmpStr = sha1( $tmpStr );  
123       if( $tmpStr == $signature ){
124        return true;
125       }else{
126        return false;
127       }
128   }
129   public function http_curl($url,$type=‘get‘,$res=‘json‘,$arr=‘‘)//接口调用函数
130   {
131       /*
132       *$cur 接口url string
133       *$type 请求类型 string
134       $res   返回数据类型 string
135       $arr  post请求参数 string
136       */
137        //1.初始化curl
138        $ch=curl_init();
139        //2.设置curl的参数
140       // curl_setopt($ch, CURLOPT_URL, $url);
141       // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
142      
143       curl_setopt_array(
144         $ch,
145         array(
146         CURLOPT_URL => $url,
147         CURLOPT_REFERER => $url,
148         CURLOPT_AUTOREFERER => true,
149         CURLOPT_RETURNTRANSFER => true,
150         CURLOPT_SSL_VERIFYPEER => false,
151         CURLOPT_SSL_VERIFYHOST => false,
152         CURLOPT_CONNECTTIMEOUT => 1,
153         CURLOPT_TIMEOUT => 30,
154         )
155       );
156      
157       if($type==‘post‘){
158          curl_setopt($ch, CURLOPT_POST, 1);
159          curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
160     //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//测试
161        // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//测试
162     
163       }
164       //3.采集
165       $output=curl_exec($ch);
166       //4.关闭
167       if($res==‘json‘){
168         if(curl_error($ch)){
169           return curl_error($ch);
170           curl_close($ch);
171         }else{
172             return json_decode($output,true); 
173         }
174       } 
175   }
176   public function getWxAccessToken()//返回access_token *session解决办法 ,存mysql或memcache都可以
177   {
178       //将access_token 存在session/cookie中
179       if(isset($_SESSION[‘access_token‘])&&isset($_SESSION[‘expire_time‘])){
180         if($_SESSION[‘access_token‘]&&$_SESSION[‘expire_time‘]>time()){
181           //如果access_token在session中并没有过期
182           return $_SESSION[‘access_token‘];
183         }
184       }
185       else{
186         //如果access_token不存在或者已经过期,重新取access_token
187         $appid=‘wx4e91a0e959b399a5‘;
188         $appsecret=‘46cf302c8ff3585026682f6ae603da94‘;
189         $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
190         $res=$this->http_curl($url,‘get‘,‘json‘);
191         $access_token=$res[‘access_token‘];
192         $_SESSION[‘access_token‘]=$access_token;
193         var_dump($_SESSION[‘access_token‘]);
194         $_SESSION[‘expire_time‘]=time()+7000;
195         return $access_token;
196       }
197   }
198   public function definedItem()//创建微信公众号底部菜单
199   {
200        //目前微信接口的调用方式都是通过curl post/get
201       header(‘content-type:text/html;charset=utf-8‘);
202       echo $access_token=$this->getWxAccessToken();
203       echo $url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
204       $postArr=array(
205          ‘button‘=>array(
206              array( 
207                 ‘name‘=>urlencode(‘科技力量‘),
208                 ‘type‘=>‘view‘,
209                  ‘url‘=>‘https://m.eqxiu.com/s/4Z7xqPHv‘,
210              ),//第一个一级菜单
211              array(
212                 ‘name‘=>urlencode(‘公司官网‘),
213                 ‘type‘=>‘view‘,
214                 ‘url‘=>‘http://m.yztsaas.com‘,
215              ),//第二个一级菜单
216              array(
217                 ‘name‘=>urlencode(‘下载APP‘),
218                 ‘type‘=>‘view‘,
219                 ‘url‘=>‘http://qrt.huilinchina.com/Home/Index/download‘,
220              ),//第三个一级菜单
221 
222       ));
223       $postJson=urldecode(json_encode($postArr));//数组转换为json
224       //var_dump($postJson);
225       $res=$this->http_curl($url,‘post‘,‘json‘,$postJson);
226       var_dump($res);
227   }
228     // public function add_material($file_info)//上传图片素材方法,还有问题
229     // {
230     //     $access_token=$this->getWxAccessToken();
231     //     $url="https://api.weixin.qq.com/cgi-bin/media/uploding?access_token={$access_token}";
232     //     $ch1 = curl_init();
233     //     $timeout = 5;
234     //     //$real_path="{$_SERVER[‘DOCUMENT_ROOT‘]}{$file_info[‘filename‘]}";
235     // //$real_path=$_SERVER[‘DOCUMENT_ROOT‘].$file_info[‘filename‘];
236     // //$real_path="http://wexin.bsgrj.com".$file_info[‘filename‘];
237     //     //$data= array("media"=>"root",‘form-data‘=>"@{$_SERVER[‘DOCUMENT_ROOT‘]}{$file_info[‘filename‘]}");
238     // //$real_path="{$_SERVER[‘DOCUMENT_ROOT‘]}{$file_info[‘filename‘]}";//
239     //     //$data= array("media"=>"@{$real_path}",‘form-data‘=>$file_info);//
240     // $data = array (
241     //       "buffer" => "@E:/phpStudy/WWW/web1/wexin/pic/Huilin.jpg"
242     //     );
243     //     curl_setopt ( $ch1, CURLOPT_URL, $url );
244     //     curl_setopt ( $ch1, CURLOPT_POST, 1 );
245     //     curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
246     //     curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
247     //     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
248     //     curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
249     //     curl_setopt ( $ch1, CURLOPT_POSTFIELDS, $data );
250 
251     //     $result = curl_exec ( $ch1 );
252     // echo ‘</hr>‘;
253     // var_dump($result);
254     //     //curl_close ( $ch1 );
255     //     if(curl_error($ch1)){
256     //    echo ‘</hr>‘;
257     //    echo curl_error($ch1);
258     //    curl_close ( $ch1 );
259     //    // return $result[‘media_id‘];
260     //     }else {
261     //  echo ‘</hr>‘;
262     //          $result=json_decode($result,true);
263     //    var_dump($result);
264     //     }
265     //  }
266     //  public function use_material()//调用上传素材的方法
267     //  {
268     //     $file_info=array(
269     //                 // ‘filename’=>’/images/1.png’, //国片相对于网站根目录的路径
270     //                 ‘filename‘=>‘/wexin/pic/Huilin.jpg‘, //\wexin\public\static\pic
271     //                 ‘content-type‘=>‘image/jpg‘, //文件类型
272     //                 ‘filelength‘=>‘21011‘ //图文大小
273     //                 );
274     //     $this->add_material($file_info);
275     //  }
276          //test3
277   public function upload()//调用上传素材的方法(可用)
278   {  $access_token=$this->getWxAccessToken();
279      $type="image";
280      $filepath=dirname(__FILE__)."\pic\Huilin.jpg";
281      var_dump($filepath);
282      $filedata=array("media"=>"@".$filepath);
283      var_dump($filedata);
284      $url="http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=$type";
285      $result=$this->https_request($url,$filedata);
286      var_dump($result);
287   }
288 
289   function https_request($url,$data=null)//上传图片素材方法(可用)
290   {
291          $curl=curl_init();
292          curl_setopt($curl,CURLOPT_URL, $url);
293          curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
294          curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
295          if(!empty($data)){
296             curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
297             curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
298          }
299          curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
300          $output=curl_exec($curl);
301          if(curl_error($curl)){
302          curl_error($curl);
303          curl_close($curl);
304          }else{
305             return $output;
306          }
307   }
308 
309 }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!