二维码生成API
接口概述
将 URL 或任意文本生成二维码图片,支持自定义尺寸、纠错级别、前景/背景色。 采用纯本地生成(不依赖外部二维码平台),稳定可控。 支持两种返回模式:JSON(base64 图片)或直接输出 PNG 图片二进制。
接口地址
/api/qrcode_api.php
请求方式
POST GET参数可通过 JSON Body、POST 表单或 GET 查询字符串传递。
请求参数
| 参数名 | 类型 | 必填 | 描述 |
|---|---|---|---|
api_key | string | 是 | API 密钥(用户中心获取) |
content | string | 是 | 二维码内容:URL 或任意文本,最长 500 字符 |
size | int | 否 | 图片边长(像素),100~1000,默认 300 |
error_correction_level | string | 否 | 纠错级别:L / M(默认)/ Q / H,级别越高容错越强、图案越密 |
foreground_color | string | 否 | 前景色,十六进制不含 #,默认 000000(黑) |
background_color | string | 否 | 背景色,十六进制不含 #,默认 ffffff(白) |
format | string | 否 | 返回模式:json(默认,base64 图片)/ image(直接输出 PNG 二进制) |
响应示例
成功响应(format=json)
{
"code": 0,
"message": "生成成功",
"data": {
"content": "https://example.com",
"size": 300,
"error_correction_level": "M",
"foreground_color": "000000",
"background_color": "ffffff",
"mime": "image/png",
"image_base64": "iVBORw0KGgoAAAANSUhEUgAA...(base64 图片数据)",
"remaining_credits": 99
}
}
失败响应(次数不足)
{
"code": 1004,
"message": "二维码API调用次数不足,请先购买"
}
提示:JSON 模式下可将 image_base64 直接用于
<img src="data:image/png;base64,{image_base64}"> 展示。
图片直出模式
传 format=image 时,接口直接返回 PNG 图片二进制(Content-Type: image/png),
可像普通图片 URL 一样嵌入页面或下载:
<img src="https://your-domain/api/qrcode_api.php?api_key=你的key&content=https%3A%2F%2Fexample.com&size=300&format=image">
注意:图片直出模式下每次访问都会生成一次并扣 1 次调用次数;请求出错时返回 JSON 错误(非图片),
调用方需按
Content-Type 区分处理。
扣费规则
- 每次成功生成扣 1 次二维码 API 调用次数(两种返回模式一致)
- 生成失败自动退费:生成过程出错时退回已扣次数,并返回系统错误
- 调用次数不足时直接拒绝请求,返回"次数不足"错误
错误码说明
| 错误码 | 说明 |
|---|---|
0 | 成功 |
1001 | 缺少必要参数(api_key / content) |
1002 | 参数验证失败(content 为空或超长) |
1003 | API 密钥无效 |
1004 | 二维码 API 调用次数不足 |
5000 | 系统内部错误(生成失败,已自动退费) |
调用示例
PHP(JSON 模式)
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://your-domain/api/qrcode_api.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'api_key' => '你的API密钥',
'content' => 'https://example.com',
'size' => 300,
'error_correction_level' => 'M',
'foreground_color' => '000000',
'background_color' => 'ffffff',
]),
]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
if ($res['code'] === 0) {
$img = base64_decode($res['data']['image_base64']);
file_put_contents('qrcode.png', $img);
}
Python(图片直出保存)
import requests
resp = requests.post("https://your-domain/api/qrcode_api.php", data={
"api_key": "你的API密钥",
"content": "https://example.com",
"size": 300,
"format": "image",
})
if resp.headers.get("Content-Type") == "image/png":
with open("qrcode.png", "wb") as f:
f.write(resp.content)
else:
print("生成失败:", resp.json())
HTML(直接嵌入图片)
<img src="https://your-domain/api/qrcode_api.php?api_key=你的key&content=Hello&format=image"
alt="二维码" width="300" height="300">