微信开发下载临时素材 PHP

/**
     * 微信下载临时素材
     */
    public function DownImage($serviceid){
        //获取临时素材
        $imageAll = $this->test($serviceid);
        $savename = md5(microtime(true));
        $savename = $savename.mt_rand(1,9999).".jpg";
        //图片保存到服务器
        $imgurl = $this->saveWeixinFile($savename,$imageAll['body']);
        return $imgurl;
    }
    /**
     * 从微信下载图片
     */
    public function test($serviceid){
        $wx = $this->getCacheToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$wx['value']."&media_id=".$serviceid;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package)); 
        return $imageAll;
    }

    //获取access_token
    private function getCacheToken()
    {
        $time = time();
        $where['name'] = ['=','access_token'];
        $where['expire_time'] = ['>',$time];
        $result = model('wx')->WxFind($where);
        return $result;
    }

    /**
     * 保存图片
     * @param  [type] $filename    [description]
     * @param  [type] $filecontent [description]
     * @return [type]              [description]
     */
    private function saveWeixinFile($filename,$filecontent)
    { 
        $path = "uploads/".date('Ymd');//路径
        $a = is_dir($path);
        if (!$a) {
            mkdir($path,0777,true);
        }
        $imageSrc = $path."/".$filename; //图片名字
        $imgpath = ROOT_PATH."public/".$imageSrc;
        $imgpath = str_replace("\\","/",$imgpath);
        $local_file = fopen($imgpath, 'w');
        if (false !== $local_file){
            if (false !== fwrite($local_file, $filecontent)) {
                $imageSrc = config('http_url')."/".$path."/".$filename;
                fclose($local_file);
                return $imageSrc;
            }
        }

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值