注意事项:
1.小程序路径前面不需要 /
2.scene 最大32个可见字符
3.width 是生成的二维码大小
官方文档:
public function get_qrcode(){
$appid = '微信小程序appid';
$secret = '微信小程序secret';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$result = $this->httpRequest($url,'GET');
$user = json_decode($result,true);
$access_token = $user['access_token'];
// 调用示例
$page = 'pages/index/index'; // 填入你的小程序页面路径
$scene = 'type=0'; // 填入你要传递的参数
$this->generateMiniProgramQRCode($access_token, $page, $scene, $dzy_user['id']);
}
// 调用微信官方接口生成二维码
function generateMiniProgramQRCode($access_token, $page, $scene, $id, $width = 200){
$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
$data = array(
'page' => $page,
'scene' => $scene,
'width' => $width
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
// 处理返回的二维码图片数据
$filename = "存储地址,绝对路径/{$id}.png";
file_put_contents($filename, $response);
}
// 发送get请求
function httpRequest($url, $method = 'GET'){
$method = strtoupper($method);
$ci = curl_init();
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "POST":
curl_setopt($ci, CURLOPT_POST, true);
if (!empty($postfields)) {
$tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
}
break;
default:
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
break;
}
$ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
curl_setopt($ci, CURLOPT_URL, $url);
if ($ssl) {
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
}
curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
curl_setopt($ci, CURLOPT_HTTPHEADER, array());
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ci);
$requestinfo = curl_getinfo($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
curl_close($ci);
return $response;
}