通八洲科技

百度小程序怎么通过PHP接收数据_PHP对接百度接口接收方法【操作】

日期:2025-12-31 00:00 / 作者:雪夜
百度小程序对接PHP需注意三点:JSON请求体需用php://input读取而非$_POST;文件上传须配置合法域名且用swan.uploadFile;swan.login的code换session_key必须HTTPS GET调用百度开放平台接口。

百度小程序的 swan.request 默认发送的是 JSON 数据,PHP 需主动读取原始 body

百度小程序调用 swan.request 时,若未显式设置 header['Content-Type'],默认会以 application/json 发送。此时 PHP 不会自动解析到 $_POST,必须用 file_get_contents('php://input') 手动读取原始请求体。

if ($_SERVER['CONTENT_TYPE'] === 'application/json') {
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON']);
        exit;
    }
} else {
    $data = $_POST;
}

百度小程序调用需携带 swan.getSystemInfo 中的 platformversion 字段做基础校验

虽然百度未强制要求接口鉴权,但生产环境建议对请求来源做轻量识别,避免被恶意模拟。可从 swan.getSystemInfo 获取设备信息,随请求一起传入,PHP 端简单校验是否为合法的小程序平台。

接收文件上传要用 swan.uploadFile,PHP 处理逻辑和普通表单一致,但路径需适配百度域名白名单

百度小程序上传文件必须使用 swan.uploadFile,且目标 URL 必须在百度后台配置的「request 合法域名」和「uploadFile 合法域名」中,否则前端直接报错 fail abortfail url not in domain list

$file = $_FILES['file'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => 'Upload failed']);
    exit;
}
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$target = '/path/to/upload/' . uniqid() . '.' . strtolower($ext);
if (move_uploaded_file($file['tmp_name'], $target)) {
    echo json_encode(['url' => 'https://yourdomain.com/' . basename($target)]);
}

百度小程序的 swan.login code 换取 session_key 需调用百度开放平台接口,PHP 必须用 https + GET 请求

前端调用 swan.login 获取 code 后,需由 PHP 向百度开放平台发起请求换取用户凭证,地址是 https://openapi.baidu.com/rest/2.0/smartapp/user/login,参数必须用 GET 传,不能 POST。

$url = 'https://openapi.baidu.com/rest/2.0/smartapp/user/login?' . http_build_query([
    'code' => $code,
    'grant_type' => 'authorization_code',
    'client_id' => 'your_app_key',
    'client_secret' => 'your_app_secret'
]);
$response = file_get_contents($url);
$result = json_decode($response, true);
百度小程序对接 PHP 的关键不在“怎么写”,而在于清楚每个环节的数据流向和协议约束——尤其是 JSON 请求体不进 $_POST、文件上传域名白名单、登录换 token 必须 GET 这三点,漏掉任一都卡死在第一步。