您现在的位置是:首页 >其他 >php生成微信小程序页面二维码网站首页其他

php生成微信小程序页面二维码

salestina 2025-11-14 12:01:03
简介php生成微信小程序页面二维码

微信小程序官方文档地址:获取不限制的小程序码 | 微信开放文档

public function getShopQrcode(){
        // 获取 access_token
        $accessToken = file_get_contents($filePath = ROOT_PATH . 'public/wechat_mini/access_token.txt');
        if(!$accessToken){
            $this->error('接口信息异常');
        }
        
        $shopId = input('shopId/d','');
        if(!$shopId){
            $this->error('接口信息异常');
        }
        // 设置请求参数
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $data = [
            'scene' => 'shop_id='.$shopId,
            'page' => 'service/shopdetail/shopdetail', // 小程序页面路径
            'width' => 430, // 可选参数,二维码的宽度
            'auto_color' => false, // 可选参数,自动配置线条颜色
            'is_hyaline' => true // 可选参数,是否需要透明底色
        ];
    
        // 初始化 cURL 会话
        $ch = curl_init();
    
        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    
        // 执行 cURL 请求
        $response = curl_exec($ch);

        // 检查是否有错误发生
        if (curl_errno($ch)) {
            //echo 'cURL error: ' . curl_error($ch);
            // 关闭 cURL 会话
            curl_close($ch);
            $this->error("获取二维码失败");
        } else {
            // 处理响应数据
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($httpCode == 200) {
                $path = '/uploads/qrcode/';
                // 保存二维码图片到文件
                $qrcodePath = ROOT_PATH . 'public'.$path;
                if (!is_dir($qrcodePath)) {
                    @mkdir($qrcodePath);
                }
                file_put_contents($qrcodePath.'shopQrcode_'.$shopId.'.png', $response);
                // 关闭 cURL 会话
                curl_close($ch);
                $this->success('信息返回成功',$path.'shopQrcode_'.$shopId.'.png');
            } else {
                // echo '请求失败,HTTP 状态码: ' . $httpCode . "
";
                // echo '响应内容: ' . $response;
                // 关闭 cURL 会话
                curl_close($ch);
                $this->error("获取二维码失败");
            }
        }
    
        
    }

注意:此代码中用到的accessToken获取方法请参考:php获取微信小程序全局唯一后台接口调用凭证-CSDN博客

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。