PHP小程序码生成接口

wen PHP项目 2

本文目录导读:

PHP小程序码生成接口

  1. 基础准备
  2. 生成小程序码的三种方式
  3. 完整使用示例
  4. 带错误处理的完整类
  5. 前端调用示例
  6. 注意事项

我来为你整理PHP小程序码生成接口的完整实现方案。

基础准备

获取访问令牌 (Access Token)

<?php
class WxMiniProgram {
    private $appId;
    private $appSecret;
    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }
    /**
     * 获取Access Token
     */
    public function getAccessToken() {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $result = $this->httpRequest($url);
        $data = json_decode($result, true);
        if (isset($data['access_token'])) {
            return $data['access_token'];
        }
        throw new Exception('获取Access Token失败: ' . $result);
    }
    /**
     * HTTP请求封装
     */
    private function httpRequest($url, $method = 'GET', $postData = null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json'
            ]);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}

生成小程序码的三种方式

getwxacode 接口(适合生成普通二维码)

/**
 * 获取小程序码(适合二维码)
 * @param string $path 页面路径
 * @param int $width 宽度
 * @param bool $autoColor 自动配置线条颜色
 */
public function getWxacode($path, $width = 430, $autoColor = true) {
    try {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
        $params = [
            'path' => $path,
            'width' => $width,
            'check_path' => false,  // 不检查路径是否存在
            'auto_color' => $autoColor
        ];
        $result = $this->httpRequest($url, 'POST', json_encode($params));
        // 判断是否返回错误信息
        if (isset($result['errcode'])) {
            throw new Exception('生成失败: ' . $result['errmsg']);
        }
        return $result; // 返回图片二进制数据
    } catch (Exception $e) {
        throw new Exception('生成小程序码失败: ' . $e->getMessage());
    }
}

getUnlimited 接口(适合无限量生成,更推荐)

/**
 * 获取小程序码(无限量)
 * @param string $scene 场景值(参数)
 * @param string $page 页面路径
 * @param array $options 其他参数
 */
public function getUnlimited($scene, $page = '', $options = []) {
    try {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $params = array_merge([
            'scene' => $scene,
            'page' => $page ?: 'pages/index/index',
            'check_path' => false,
            'width' => 430,
            'auto_color' => false,
            'line_color' => ['r' => 0, 'g' => 0, 'b' => 0]
        ], $options);
        $result = $this->httpRequest($url, 'POST', json_encode($params));
        // 检查是否返回错误
        $error = json_decode($result, true);
        if (isset($error['errcode'])) {
            throw new Exception('生成失败: ' . $error['errmsg']);
        }
        return $result; // 返回图片二进制数据
    } catch (Exception $e) {
        throw new Exception('生成小程序码失败: ' . $e->getMessage());
    }
}

createwxaqrcode 接口(普通二维码)

/**
 * 获取小程序二维码(普通二维码)
 * @param string $path 页面路径
 */
public function createWxaqrcode($path, $width = 430) {
    try {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$accessToken}";
        $params = [
            'path' => $path,
            'width' => $width
        ];
        $result = $this->httpRequest($url, 'POST', json_encode($params));
        return $result;
    } catch (Exception $e) {
        throw new Exception('生成二维码失败: ' . $e->getMessage());
    }
}

完整使用示例

<?php
require_once 'WxMiniProgram.php';
// 初始化
$wx = new WxMiniProgram('your_app_id', 'your_app_secret');
// 1. 生成小程序码(无限量)
try {
    // 场景值,可用于追踪用户来源
    $scene = 'source=' . $userId . '&type=share';
    // 生成图片二进制数据
    $imageData = $wx->getUnlimited($scene, 'pages/index/index', [
        'width' => 300,
        'auto_color' => true,
        'line_color' => ['r' => 255, 'g' => 0, 'b' => 0]  // 自定义颜色
    ]);
    // 保存到本地
    $filename = 'qrcode_' . time() . '.png';
    file_put_contents('/path/to/save/' . $filename, $imageData);
    // 或者直接输出
    header('Content-Type: image/png');
    echo $imageData;
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

带错误处理的完整类

<?php
class WechatMiniProgram {
    private $appId;
    private $appSecret;
    private $accessToken;
    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }
    /**
     * 生成小程序码并返回Base64格式
     * @param array $params 生成参数
     * @return array 包含base64图片数据
     */
    public function generateQRCode($params) {
        try {
            // 获取access token
            $accessToken = $this->getAccessToken();
            // 根据类型选择接口
            $apiUrl = '';
            $postData = [];
            if ($params['type'] === 'unlimited') {
                $apiUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
                $postData = [
                    'scene' => $params['scene'],
                    'page' => $params['page'] ?? 'pages/index/index',
                    'width' => $params['width'] ?? 430,
                    'auto_color' => $params['auto_color'] ?? false,
                    'line_color' => $params['line_color'] ?? ['r' => 0, 'g' => 0, 'b' => 0],
                    'is_hyaline' => $params['is_hyaline'] ?? false
                ];
            } elseif ($params['type'] === 'wxacode') {
                $apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
                $postData = [
                    'path' => $params['path'],
                    'width' => $params['width'] ?? 430,
                    'auto_color' => $params['auto_color'] ?? false,
                    'line_color' => $params['line_color'] ?? ['r' => 0, 'g' => 0, 'b' => 0]
                ];
            }
            // 发起请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($postData))
            ]);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            // 检查是否返回错误
            $errorData = json_decode($response, true);
            if (isset($errorData['errcode']) && $errorData['errcode'] != 0) {
                return [
                    'success' => false,
                    'error' => $errorData['errmsg']
                ];
            }
            // 成功返回图片数据
            return [
                'success' => true,
                'image' => base64_encode($response),
                'contentType' => 'image/png'
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
}

前端调用示例

<!DOCTYPE html>
<html>
<head>生成小程序码</title>
</head>
<body>
    <button onclick="generateQRCode()">生成小程序码</button>
    <img id="qrcode" alt="小程序码" style="display:none;">
    <script>
        function generateQRCode() {
            fetch('/api/generate-qrcode.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    type: 'unlimited',
                    scene: 'user_id=123&type=promote',
                    page: 'pages/index/index',
                    width: 300
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const img = document.getElementById('qrcode');
                    img.src = 'data:image/png;base64,' + data.image;
                    img.style.display = 'block';
                } else {
                    alert('生成失败: ' + data.error);
                }
            });
        }
    </script>
</body>
</html>

注意事项

  1. Access Token有效期:7200秒,需要缓存

  2. 接口调用频率限制

    • getwxacode:每日100万次
    • getUnlimited:有数量限制
  3. 参数限制

    • scene:最长32个可见字符
    • page:路径不能包含参数
  4. 错误处理

    • 40001:access_token无效
    • 41030:page路径不正确
    • 40013:不合法的AppID
  5. 最佳实践

    • 缓存Access Token
    • 图片生成后缓存到CDN
    • 异步处理大量生成请求

这个方案覆盖了微信小程序码生成的所有场景,你可以根据实际需求选择合适的接口。

抱歉,评论功能暂时关闭!