php - 通过 FCM google-php-api HTTPv1 API 发送推送消息

1 篇文章 0 订阅
1 篇文章 0 订阅

测可用,目前已经用于项目中

官方文档https://firebase.google.com/docs/cloud-messaging/migrate-v1

切记一定要开vpn 不然请求不了

我正在尝试使用 Google PHP API 客户端 GitHub - googleapis/google-api-php-client: A PHP client library for accessing Google APIs通过 Google HTTPv1 API 发送 FCM 推送通知。

    

  1. 第一步 下载composer包引入google扩展包 composer require google/apiclient
  2. 获取token
public function getAccessToken()
    {
        try {
            $cache_key = 'push:access_token:key';
            $accessToken = $this->reids->get($cache_key);
            if (empty($token)) {
                //国内服务器需要使用代理,不然请求不了google接口
                $proxy = 'http://XXXXX';
                $httpClient = new Client([
                    'defaults' => [
                        'proxy' => $proxy,
                        'verify' => false,
                        'timeout' => 10,
                    ]
                ]);
                $client = new Google_Client();
                $client->setHttpClient($httpClient);
                //引入配置文件
                $client->setAuthConfig($this->config['auth_key_file_path']);
                //设置权限范围
                $scope = 'https://www.googleapis.com/auth/firebase.messaging';
                $client->setScopes([$scope]);
                $client->fetchAccessTokenWithAssertion($client->getHttpClient());
                $token = $client->getAccessToken();
                if (empty($token) || empty($token['access_token']) || empty($token['expires_in'])) {
                    throw new \Exception('access_token is empty!');
                }
                //设置缓存
                $this->reids->set($cache_key, $token['access_token'], $token['expires_in'] - 20);
                return $token['access_token'];
            }
            return $accessToken;
        } catch (\Exception $e) {
            return false;
        }
    }

3.开始推送 

public function buildTask($token)
    {
        //发送push接口,project_id需要替换成自己项目的id
        $send_url = 'https://fcm.googleapis.com/v1/projects/{project_id}/messages:send';
 
        //推送参数
        $params = [
            "message" => [
                "token" => 'XXXX', //需要发送的设备号
                "notification" => [
                    "title" => '通知的标题',
                    "body" => '通知的正文'
                ],
                "data" => ''
            ]
        ];
 
        //获取令牌
        $accessToken = $this->getAccessToken();
        if (empty($accessToken)) {
            return false;
        }
 
        //header请求头,$accessToken 就是你上面获取的令牌
        $header = [
            'Content-Type' => 'application/json; UTF-8',
            'Authorization' => 'Bearer ' . $accessToken
        ];
 
        $response = Request::post($send_url, $header, $params);
 
        return $response;
    }

4.请求结果

{
   "name":"projects/project_id/messages/0:1500415314455276%31bd1c9631bd1c96"      
}

运行完整代码

<?php
require_once 'vendor/autoload.php';
use Google\Client;

$client = new Google\Client();

$client->useApplicationDefaultCredentials();

$client->setAuthConfig( 'xxxxx.json');//引入json秘钥
$client->setScopes('https://www.googleapis.com/auth/firebase.messaging');     # 授予访问 FCM 的权限
// 你的 Firebase 项目 ID
$project      = "xxx";//包名
$send_url     = "https://fcm.googleapis.com/v1/projects/{$project}/messages:send";
$access_token = $client->fetchAccessTokenWithAssertion();//获取秘钥

if (!isset($access_token['access_token'])) {

    return json_encode(['err_no' => 1, 'msg' => '推送失败,未获取到秘钥'],JSON_UNESCAPED_UNICODE);
}
error_log("access_token".$access_token['access_token'].PHP_EOL, 3, "/data/huoyu_push/huoyu_push.log",FILE_APPEND);
$accessToken = $access_token['access_token'];//秘钥

$param = file_get_contents("php://input");
$param = json_decode($param, true);
if(!isset($param['firebase_push_token']) || !isset($param['title']) || !isset($param['body'])){
    echo json_encode(['err_no' => 1, 'msg' => '参数错误'],JSON_UNESCAPED_UNICODE);
    exit();
}
error_log("参数".date("Y-m-d H:i:s").$param['firebase_push_token'].$param['title'].$param['body']. PHP_EOL, 3, "/data/huoyu_push/huoyu_push.log",FILE_APPEND);
$deviceToken   = $param['firebase_push_token'];
$title = $param['title'];
$body = $param['body'];
if(empty($deviceToken) || empty($title) || empty($body)){
    echo json_encode(['err_no' => 1, 'msg' => '参数不能为空'],JSON_UNESCAPED_UNICODE);
    exit();
}
//推送参数
$params = [
    "message" => [
        "token"        =>$deviceToken, //需要发送的设备号
        "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'])){
   error_log("响应结果".$response['name']. PHP_EOL, 3, "/data/huoyu_push/huoyu_push.log",FILE_APPEND);
    echo  json_encode(['err_no' => 0, 'msg' => '推送成功',['data'=>$response]],JSON_UNESCAPED_UNICODE);
    exit();
}elseif(isset($response['error'])){
    error_log("请求报错".$response['error']['code']. PHP_EOL, 3, "/data/huoyu_push/huoyu_push.log",FILE_APPEND);
    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;
}

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值