require_once 'phpqrcode.php'; // 引入QRcode类文件
function generateQRCode($page, $width = 150, $margin = 2) {
$appid = 'your_appid'; // 小程序的AppID
$secret = 'your_app_secret'; // 小程序的AppSecret
// 获取小程序access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$result = file_get_contents($url);
$resultObj = json_decode($result);
$access_token = $resultObj->access_token;
// 生成小程序码
$url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$access_token}";
$postData = json_encode([
'path' => $page,
'width' => $width,
'auto_color' => false,
'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
'is_hyaline' => false
]);
$opts = [
'http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $postData
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
// 保存为图片文件
$filename = 'qrcode.png';
file_put_contents($filename, $result);
// 生成带logo的二维码
$logo = 'logo.png'; // logo图片路径
$output = 'output.png'; // 输出图片路径
QRcode::png($filename, $output, QR_ECLEVEL_L, $width, $margin);
$QR = imagecreatefromstring(file_get_contents($output));
$logo = imagecreatefromstring(file_get_contents($logo));
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
$logo_qr_width = $QR_width / 5;
$scale = $logo_width / $logo_qr_width;
$logo_qr_height = $logo_height / $scale;
$from_width = ($QR_width - $logo_qr_width) / 2;
imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
$logo_qr_height, $logo_width, $logo_height);
imagepng($QR, $output);
imagedestroy($QR);
return $output;
}
// 调用方法生成二维码
$page = '/pages/index/index'; // 小程序页面路径
$width = 150; // 二维码宽度
$margin = 2; // 二维码边距
$qrCode = generateQRCode($page, $width, $margin);
echo '<img src="' . $qrCode . '" alt="小程序二维码">';