php 获取小程序二维码返回的 Buffer二进制数据 保存图片 全套代码

来源:csdn博客 分类: 文章浏览史 发布时间:2020-08-06 15:17:51 最后更新:2020-08-06 浏览:560
转载声明:
本文为摘录自“csdn博客”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2020-08-06 15:17:51

废话不说,直接上代码

    $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=".$access_token; //$access_token为自己获取的token,后面有写
	
	 $codeinfo = $this->http_request($url, $array_json);//图片流 buffer  curl提交数据 获取图片流
	
	//判断是否是 json格式
    if(is_null(json_decode($codeinfo))){
    	//不是json数据   有数据流  json_decode($codeinfo)返回值为 null
        
        $jpg = $codeinfo;//得到post过来的二进制原始数据
         $file = fopen("xcxcode/wxcode1.jpg","w");//创建件准备写入,文件名xcxcode/wxcode1.jpg为自定义
        fwrite($file,$jpg);//写入
        fclose($file);//关闭
    }else{
    	//是json数据
    	$codeinfo_array=json_decode($codeinfo,true);
    	//没有接收到数据流  
        return "no";
    }

完后把自定义的文件名保存即可

获取access_token:
 /**
     * 获取access_token
     * @return [type] [description]
     */
    private function get_access_token(){

    $file = "file/tokenfile.txt";//自定义文件名  但是文件夹需提前创建

    if(!file_exists($file)){

        $get = $this->get_toxcx_access_token();

        return $get;

    }

    $fileinfo = file_get_contents("file/tokenfile.txt");

    $time = time();

    //获取token时间看是否有效
    $info = explode(",", $fileinfo);


    if($info[1]>=$time){

        //token有效
        return $info[0];
    }else{
        //无效的话则调用
        $get = $this->get_toxcx_access_token();

        return $get;
        
    }
    

}

private function get_toxcx_access_token(){


    $xcxInfo = $this->getXcxInfo();//获取小程序 appid,secret

    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$xcxInfo["appid"]."&secret=".$xcxInfo["secret"];
   

    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回,而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //执行命令
    $data = curl_exec($curl);
    echo curl_getinfo($curl,CURLINFO_HTTP_CODE); //输出请求状态码
    //关闭URL请求
    curl_close($curl);
    //显示获得的数据
    $data_array = json_decode($data,true);//转换数组
	
    if(array_key_exists("access_token", $data_array)){

        $text = $data_array["access_token"].",".(time()+7000);

        //写入文件中
        if(!file_exists("file/tokenfile.txt")){

            fopen("file/tokenfile.txt","wb");
        }
        
         //把值存入文件中
        $myfile = fopen("file/tokenfile.txt", "w");

        fwrite($myfile, $text);//写入文件

        fclose($myfile);//关闭文件

        return $data_array["access_token"];

    }else{

        return "no";
    }
   

}
php技术微信