前言
最近在开发个微信小程序用到生成二维码的接口,curl执行生成二维码后,返回了一堆乱码,很是无奈,查遍资料最终得以解决。由于网上的资料过于散乱,不易查看,容易误导人等等原因,使我萌生了写下这篇文章的动机。
文章主要分两部分讲解,接口和后端。
接口
curl执行的时候加上这么个header:$header=header("Content-Type:image/jpg;charset=utf-8");(注:这里是单个header值的写法。如果是多个header值的话就要改成$header=array("Authorization:Basic","Content-Type:application/json");这种写法。注意单个header值不能用多个header值的写法。)
加好之后接口就可以正常返回二维码图片了。
后端
后端执行curl生成二维码的时候可不是像接口那样加个header就能正常返回二维码的图片了,需要用file_put_contents保存到文件夹,返回路径放到img才能正常展示。
示例代码:
<?php $url=$_W['siteroot']."app/index.php?i=".$_W['uniacid']."&t=0&v=1.1.1&from=wxapp&c=entry&a=wxapp&do=CreateTicket&m=hotmallstore";
$scene_id=123;
$_data=array('data'=>json_encode(array(
'action_name'=>'QR_LIMIT_SCENE',
'action_info'=>array(
'scene'=>array(
'scene_id'=>$scene_id
)
)
)));
$response = json_decode(ihttp_request($url,$_data)['content'],true);
$ticket=!empty($response['ticket'])?$response['ticket']:"";
$_url=$_W['siteroot']."app/index.php?i=".$_W['uniacid']."&t=0&v=1.1.1&from=wxapp&c=entry&a=wxapp&do=Showqrcode&m=hotmallstore&ticket=".$ticket;
$code = ihttp_get($_url);
$file_path = ATTACHMENT_ROOT.'images/qrcode/';
if(!is_dir($file_path)) {
$result = mkdir($file_path, 0777, true);
if($result) {
$path_arr = explode('/',$path);
$path_str = '';
foreach($path_arr as $val){
$path_str .= $val.'/';
$a = chmod($path_str,0777);
}
}
$file_path=$result;
}
$name=$scene_id.'.png';
$img_path='images/qrcode/'.$name;
$filename = $file_path.$name;
if(!file_exists($filename)){
file_put_contents($filename, !empty($code['content'])?$code['content']:"");
}
?>
<img height="60px" width="60px" src="{media $img_path}"/>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。