PHP调用Roblox注册接口用动态x-csrf-token返回400错误如何解决?
问题排查与修复方案
核心问题1:变量名重复导致CSRF值被覆盖
你代码中先将CSRF值存入$data变量,后续又用相同变量名存储请求体JSON,导致拼接到请求头中的x-csrf-token实际值为整段JSON内容,完全不符合接口要求。硬编码时未使用该变量所以请求正常。
核心问题2:请求头格式不符合PHP cURL规范
CURLOPT_HTTPHEADER要求传入的数组中每个请求头为单独的元素,不需要手动添加\r\n换行符,也不允许将多个请求头拼接为同一个字符串。
优化建议
- 从
$_POST获取的CSRF值建议先用trim()清除多余空白字符 - 请求体不要手动拼接JSON,改用
json_encode()处理数组,避免出现语法错误
修复后完整代码
// 单独命名存储CSRF的变量,避免和请求体重名 $csrfToken = trim($_POST['csrf']); // 每个请求头单独作为数组元素,无需加换行符 $headers = [ "x-csrf-token: $csrfToken", "Content-Type: application/json", "Accept: application/json" ]; // 用数组定义请求参数,转JSON更稳妥 $postData = [ "username" => "string", "password" => "string", "gender" => "Unknown", "birthday" => "2021-11-22T23:29:51.656Z", "isTosAgreementBoxChecked" => true, "email" => "string", "locale" => "string", "assetIds" => [0], "bodyColorId" => 0, "bodyTypeScale" => 0, "headScale" => 0, "heightScale" => 0, "widthScale" => 0, "proportionScale" => 0, "referralData" => [ "acquisitionTime" => "2021-11-22T23:29:51.656Z", "acquisitionReferrer" => "string", "medium" => "string", "source" => "string", "campaign" => "string", "adGroup" => "string", "keyword" => "string", "matchType" => "string", "sendInfo" => true, "requestSessionId" => "string", "offerId" => "string" ], "agreementIds" => ["string"], "identityVerificationResultToken" => "string", "captchaId" => "string", "captchaToken" => "string", "captchaProvider" => "string" ]; $postDataJson = json_encode($postData); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://auth.roblox.com/v1/signup'); curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 部分本地环境请求HTTPS出错可以开启以下两行配置 // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($ch); curl_close($ch);
内容的提问来源于stack exchange,提问作者Witz
相关产品推荐
相关产品推荐

