--
前言
最近 (2024/8) 客戶反應有掉推播問題,直到去查看推播結果看到 {"error":"Deprecated endpoint, see https://firebase.google.com/docs/cloud-messaging/migrate-v1"} ,才發現舊版 FCM API 已經在 2024/7/24 停止服務,必須要更新到 HTTP v1 API
--
參考資源
- PHP Firebase HTTP v1 API 新版推送 - 爱嘤斯坦i - 博客园 (cnblogs.com)
- php - 通过 FCM google-php-api HTTPv1 API 发送推送消息_fcm apis-CSDN博客
--
下載 Google API
因為 PHP 版本太舊,所以無法使用 composer 來取得 Google API,只能從 GitHub 來下載。
這裡下載的版本是 v2.8.0,v2.9.0 以上就不支援 5.4 & 5.5 了
--
完整程式碼
環境:PHP 5.4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?php require_once __DIR__ .'/../vendor/google-api-php-client-v2.8.0-PHP5.4/vendor/autoload.php'; use Google\Client; $client = new Google\Client(); $client->useApplicationDefaultCredentials(); $client->setAuthConfig( __DIR__ .'/../vendor/google-api-php-client-v2.8.0-PHP5.4/upad12-xxxxxx.json');//引入json秘钥 $client->setScopes('https://www.googleapis.com/auth/firebase.messaging'); // 授予访问 FCM 的权限 $send_url = "https://fcm.googleapis.com/v1/projects/upad12-4c8c9/messages:send"; $access_token = $client->fetchAccessTokenWithAssertion();//获取秘钥 if (!isset($access_token['access_token'])) { return json_encode(['err_no' => 1, 'msg' => '推送失败,未获取到秘钥'],JSON_UNESCAPED_UNICODE); } $accessToken = $access_token['access_token'];//秘钥 $params = [ "message" => [ "token" =>'設備 token', "notification" => [ "title" => 'title', "body" => 'body' ] ] ]; //header请求头,$accessToken 就是你上面获取的令牌 $header = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $accessToken, ]; $params = json_encode($params); $response = http_post($send_url, $params, $header); $response = json_decode($response,true); if(isset($response['name'])){ echo json_encode(['err_no' => 0, 'msg' => '推送成功',['data'=>$response]],JSON_UNESCAPED_UNICODE); exit(); }elseif(isset($response['error'])){ echo json_encode(['err_no' => 1, 'msg' => '消息未送达',['data'=>$response]],JSON_UNESCAPED_UNICODE); exit(); } function http_post($send_url,$params,$headers){ $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $send_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $params, CURLOPT_HTTPHEADER => $headers )); $response = curl_exec($curl); curl_close($curl); return $response; } |
--
其他參考資源
- GitHub - kedniko/firebase-cloud-messaging-http-v1-php
- firebase - How to use the FCM HTTP v1 API with php - Stack Overflow
--
615 total views, 5 views today