[英]send POST request in PHP to pushbullet API 401 error
我正試圖通過使用電子郵件發送帶有pushbullet的簡單推送通知,然后將其發送到鏈接的帳戶,以避免需要帳戶數據。 (請參閱此處的參考: https : //docs.pushbullet.com/#pushes )
因此,我在php中使用了一種非cURL方法,我(不僅如此)在這里找到了該方法: 如何使用PHP發送POST請求?
不幸的是,我得到如下錯誤:
<br />
<b>Warning</b>: file_get_contents(https://api.pushbullet.com/v2/pushes): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
in <b>/path/to/function.php</b> on line <b>42</b><br />
bool(false)
將file_get_contents使用url的選項設置為“ on”。
我的代碼:
$pushdata = array(
"email" => $email,
"type" => "link",
"title" => "Demo Pushbullet Notification",
"body" => "You have new comment(s)!",
"url" => "http://demo.example.com/comments"
);
//Post without cURL
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n"."Authorization: Bearer <xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>\r\n",
'method' => 'POST',
'content' => http_build_query($pushdata),
),
);
$context = stream_context_create($options);
$result = file_get_contents("https://api.pushbullet.com/v2/pushes", false, $context, -1, 40000);
var_dump($result);
編輯:更改了對克里斯多夫的回應的代碼,仍然無法正常工作。 據我所知,它也不應該要求訪問令牌。 我理解這是將通知從中立推送到鏈接的電子郵件。 也許我錯了,但是訪問令牌不能解決它。
編輯(已解決):需要訪問令牌IS來推送通知,並且由於它不適用於此方法,因此它可以與cURL一起使用。
聽起來您缺少用戶帳戶的訪問令牌。 您可以在https://www.pushbullet.com/account上找到它。 您應該將其包含在標題中,例如“ Authorization”:“ Bearer ACCESS_TOKEN_HERE”。
我知道這是一篇過時的文章,但是sendgrid在使用與您的網站相同的Authorization:Bearer APIKEY方法時也遇到了相同的問題。
我終於使用以下代碼使用原始php發布使其工作
$url = "your url";
$post_data = 'yourdata';
// Set the headers
$options = array('http' =>
array(
'method' => 'POST',
'header' => "Authorization: Bearer APIKEY\r\n" . 'Content-Type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
// Send the POST data
$ctx = stream_context_create($options);
$fp = fopen($url, 'rb', false, $ctx);
// Read the POST data
$result = json_decode(stream_get_contents($fp));
echo "done";
似乎切換標題的順序並在末尾省略\\ r \\ n似乎可行。 我花了一個小時嘗試這種不同的組合,所以我想將其發布給其他人。
請注意,如果您使用sendgrid api,請確保設置“ Content-Type:application / json”,並確保$ post_data位於json中
您需要為此使用cURL,以便您可以將API密鑰作為文檔中定義的標頭傳遞: https : //docs.pushbullet.com/#http 。
<?php
$curl = curl_init('https://api.pushbullet.com/v2/pushes');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer <your_access_token_here>']);
curl_setopt($curl, CURLOPT_POSTFIELDS, ["email" => $email, "type" => "link", "title" => "Demo Pushbullet Notification", "body" => "You have new comment(s)!", "url" => "http://demo.example.com/comments"]);
// UN-COMMENT TO BYPASS THE SSL VERIFICATION IF YOU DON'T HAVE THE CERT BUNDLE (NOT RECOMMENDED).
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
print_r($response);
此代碼完全是我的頭頂,尚未經過測試
我已經分解了選項,以便您可以輕松看到它們,但是您可以將它們組合成一個數組,並通過curl_setoptarray($curl, []);
傳遞它們curl_setoptarray($curl, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.