PHP 8.2中Guzzle 7调用FCM接口报错,Curl/Postman请求正常
解决Guzzle 7调用FCM接口的致命错误
错误根源
你的Guzzle客户端headers配置格式错误。Guzzle要求headers是关联数组(键为Header名称,值为对应内容),但你直接将完整的Header字符串放入数组,导致数组变成索引形式(键为整数0、1)。Guzzle处理时会把这些整数当作Header名称传入strtolower()函数,触发类型错误。
修复后的代码
$this->client = new Client([ 'base_uri' => 'https://fcm.googleapis.com/fcm/', 'headers' => [ 'Authorization' => 'key=' . SERVER_KEY, // 改为键值对格式 'Content-Type' => 'application/json' ] ]); $fields = [ 'to' => USER_TOKEN, 'notification' => [ 'title' => 'Title', 'body' => 'Body', ], 'data' => [ 'icon' => LOGO, 'click_action' => LINK_TO_SITE, ], ]; try { $response = $this->client->post('send', ['json' => $fields]); $result = json_decode($response->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR); } catch (Exception $e) { var_dump($e->getMessage()); exit; }
额外检查项
- 确保
SERVER_KEY、USER_TOKEN、LOGO、LINK_TO_SITE均为有效字符串,未被错误解析为整数 - 若问题仍存在,可在Client配置中添加
'debug' => true,查看完整请求详情,与Postman的请求参数对比排查差异
内容的提问来源于stack exchange,提问作者Yevheniy Antikov
相关产品推荐
相关产品推荐

