/**
* 微信下载临时素材
*/
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;
}
}
}