使用 PHP 执行 cURL 发送推送通知
Posted
技术标签:
【中文标题】使用 PHP 执行 cURL 发送推送通知【英文标题】:Using PHP to Execute cURL to send Push Notification 【发布时间】:2017-04-19 17:22:42 【问题描述】:我正在尝试发送 cURL 命令来发送推送通知。我对 cURL 很陌生,似乎无法运行命令。
这里是 cURL 命令行:
curl --header "Authorization: key=AAAAVD27CWY:APA91bE7YdKYiqTmQhErf0E3gm8lbgNt2KP5-xPQf83V7m8eKsa0ljktOLiGyzzrP0uxVNBHC6cyuJAPejkTyNl1DnoxcajesLvGXIzq3YR1l-wiFvoivRmIUkDvThTsKCJkZMomhEPp" --header Content-Type:"application/json" https://android.googleapis.com/gcm/send -d "\"registration_ids\":[\"fr1l051Pczw:APA91bGkyuA6iKMP6oICJ8NweijQpWTWGuo-inqvpF5-Mety0D7oL_ppvevKKdWPxIo7ev_v5sAWbprk7pEg8kz3cNCivipL9RCR3XlA1caBtahsRtnANZpaU-KYnsdjcGY3Q51xN1ny\"]"
这是我正在尝试执行的 php cURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "\"registration_ids\":[\"fr1l051Pczw:APA91bGkyuA6iKMP6oICJ8NweijQpWTWGuo-inqvpF5-Mety0D7oL_ppvevKKdWPxIo7ev_v5sAWbprk7pEg8kz3cNCivipL9RCR3XlA1caBtahsRtnANZpaU-KYnsdjcGY3Q51xN1ny\"]");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Authorization: key=AAAAVD27CWY:APA91bE7YdKYiqTmQhErf0E3gm8lbgNt2KP5-xPQf83V7m8eKsa0ljktOLiGyzzrP0uxVNBHC6cyuJAPejkTyNl1DnoxcajesLvGXIzq3YR1l-wiFvoivRmIUkDvThTsKCJkZMomhEPp";
$headers[] = "Content-Type: \"application/json\"";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch))
echo 'Error:' . curl_error($ch);
curl_close ($ch);
我正在使用 Google 的 Firebase Cloud Messaging 运行它。
我可以在我的服务器上执行命令,所以我知道至少它有效。
运行 UBUNTU 16.04 和 Apache。 我在服务器上运行 SSL 并尝试添加:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
还是没有运气。
【问题讨论】:
【参考方案1】:请使用下面的 PHP 卷曲请求
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://android.googleapis.com/gcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "\"registration_ids\":[\"fr1l051Pczw:APA91bGkyuA6iKMP6oICJ8NweijQpWTWGuo-inqvpF5-Mety0D7oL_ppvevKKdWPxIo7ev_v5sAWbprk7pEg8kz3cNCivipL9RCR3XlA1caBtahsRtnANZpaU-KYnsdjcGY3Q51xN1ny\"]",
CURLOPT_HTTPHEADER => array(
"authorization: key=AAAAVD27CWY:APA91bE7YdKYiqTmQhErf0E3gm8lbgNt2KP5-xPQf83V7m8eKsa0ljktOLiGyzzrP0uxVNBHC6cyuJAPejkTyNl1DnoxcajesLvGXIzq3YR1l-wiFvoivRmIUkDvThTsKCJkZMomhEPp",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
echo "cURL Error #:" . $err;
else
echo $response;
【讨论】:
成功了。非常感谢!以上是关于使用 PHP 执行 cURL 发送推送通知的主要内容,如果未能解决你的问题,请参考以下文章
JSON对象压缩同时使用php发送推送通知ios/android