php - 如何从 php 从 android 推送通知

标签 php android google-cloud-messaging

您好,我正在尝试从我的 php 网络服务器向 android 移动设备发送通知...但我收到的响应为

Unauthorized Error 401

下面是我的代码

<?php $url = 'https://android.googleapis.com/gcm/send';
$device_ids = array('devise ID' );
$headers = array('Authorization: key=api key',
'Content-Type: application/json');
$t_data = array();
$t_data['message'] = array('Someone commented on your business.');
$t_json = array( 'registration_ids' => $device_ids , 'data' => $t_data );

$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $t_json ) );
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
if ($result === FALSE)
{
 die('Curl failed: ' . curl_error($ch));
}

curl_close($ch);

echo $result;
?>

我该如何解决这个错误

最佳答案

这是我在自己的 GCM 项目中实现的工作脚本。尝试运行它。 确保更改“api_key”和“registrationids”。

 <?php
        $api_key = "AIzBpx4XbXkhkjwKd8P-v2d1Jk";
        $registrationIDs = array("APA91bjkj3Rjlo8T_URx15NqvxY2mRyQ");
        $message = "congratulations";
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
                    'registration_ids'  => $registrationIDs,
                    'data'              => array( "message" => $message ),
                    );

        $headers = array(
                        'Authorization: key=' . $api_key,
                        'Content-Type: application/json');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch);
        curl_close($ch);

    echo $result;
    ?>

关于php - 如何从 php 从 android 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20372802/

相关文章:

php - CakePHP 没有在查找查询中加入正确的表

php - Paypal 14077410 错误

Android 最低内存量

google-chrome - chrome service worker 推送通知仅在我的网站的标签页 URL 关闭或不活动时显示

android - GCM : Using same account on multiple devices - what happens?

android - 如何从 GCM 获取规范 ID

php - 具有多个 GET 变量的 .htaccess RewriteRule?

php - ipn 中的 PDO 不插入

android - 关于android加速度计的onSensorChanged的信息

android - 编译 VLC Android 失败 "You must define ANDROID_NDK, ANDROID_SDK before starting."