最近有很多小程序开发,要求有生成的二维码,扫码就能跳转到自己的小程序内,具体代码实现放到下面了
一.首先在小程序后台开通生成二维码功能。
二.用以下代码生成小程序码存到项目指定目录,返回二维码路径。
public function getQrCode($id)
{
// $id = $this->request->param('id', '', 'intval');
// 替换成你的小程序的AppID和AppSecret
$appId = '';
$appSecret = '';
$accessToken = $this->getAccessToken($appId, $appSecret);
$path = 'pages/baoxiu/baoxiu'; // 替换成你想要跳转的小程序页面路径
$sceneParams = "$id";
$code = $this->generateMiniProgramCode($accessToken, $path,$sceneParams);
// 处理接口返回的小程序码数据
if ($code) {
$time = time();
$rand = round('000',999);
$image_name = 'code'.$time.$rand;
$image_path = 'qrCode/'.$image_name.'.png';
// 将小程序码保存到文件
$server = 'https://'.$_SERVER['HTTP_HOST'];
file_put_contents($image_path, $code);
return $server.'/'.$image_path;
} else {
echo "生成小程序码失败";
}
}
//获取token
private function getAccessToken($appId, $appSecret)
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
$res = json_decode(file_get_contents($url), true);
return $res['access_token'];
}
//二维码生成
private function generateMiniProgramCode($accessToken, $path,$sceneParams = '', $width = 430) {
$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
$data = [
'scene' => $sceneParams, // 参数(如:id=123&name=test)
'width' => $width, // 二维码宽度(默认 430px)
'auto_color' => false, // 是否自动配色
'line_color' => ['r' => 0, 'g' => 0, 'b' => 0], // 线条颜色(RGB)
'page' => $path, // 小程序页面路径(如:pages/home/index)
];
$data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
这样就得到了二维码及你所需要存储进二维码的信息,等用户扫这个二维码,就会自动跳转到你的小程序对应页面了。

1137

被折叠的 条评论
为什么被折叠?



