请求支付宝二维码图片内容很慢的解决办法
最近开发支付宝小程序项目,通过接口生成的二维码打算下载到服务器,用file_get_contents 获取,结果被限制了很慢7-10秒才获取到
用img 标签访问也是很快,估计是判断了浏览器请求头
后来网上找到解决办法,用curl 模拟浏览器进行访问。秒取
<?php $camera_url = 'https://mdgw.alipay.com/wsdk/img?fileid=A*OG3WRZIq5S0AAAAAAAAAAAAAAQAAAQ&bz=am_afts_openhome&zoom=original'; $camera_base64 = get_head($camera_url); if ($camera_base64!='') { echo json_encode(array('camera_base64' => $camera_base64),JSON_UNESCAPED_UNICODE);; } function get_head($url) { $header = [ 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding: gzip, deflate', ]; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_ENCODING, ‘gzip‘); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); $data = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); file_put_contents('aaa.png',$data); if ($code == 200) {//把URL格式的图片转成base64_encode格式的! $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data); return $imgBase64Code;//图片内容 } else { return '获取头像失败'; } }