小程序二维码生成接口:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
官方提供了三种接口,我这里使用的是B类接口,遇到的几个坑都是通用的。
1、access_token应放在url中,不在post传递的参数中
在这里,如果你仅把access_token放在post传递的参数中或url和post传参中都放,会报错access_token失效或数据格式错误
2、scene不能为空,随意填写就行,但不能为空
方案一(将二维码存储在本地):
public function getQRcode()
{
$access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret),true)['access_token'];
$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
$ch = curl_init();
$data = json_encode(['scene' => 'test']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过ssl检测
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要将结果直接返回到变量里,那加上这句。
$res = curl_exec($ch);
file_put_contents('test.png',$res);
$this->smarty_lib->tmp("getQRcode.html",'');
}
方案二(直接渲染):
public function getQRcode()
{
$access_token = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret),true)['access_token'];
$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
$ch = curl_init();
$data = json_encode(['scene' => 'test']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 'image/gif');
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //如果需要将结果直接返回到变量里,那加上这句。
$res = curl_exec($ch);
$data = 'data:image/jpeg;base64,'.base64_encode($res);//补全base64加密字符串头
$html = "<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title>二维码</title>
</head>
<body>
<img src='$data'>
</body>
</html>";
echo $html;
exit;
}
- note:微信接口返回的是二进制图片,所以需要先处理一番再渲染