Search code examples
phpapipostpushbullet

send POST request in PHP to pushbullet API 401 error


I'm trying to send simple push notifications with pushbullet just through using the email and sending those to the linked account to avoid needing account data. (see reference here: https://docs.pushbullet.com/#pushes)

Therefore I'm using a non cURL-method in php that I (not only) found here: How do I send a POST request with PHP?

Unfortunately I get back an error as following:

<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)

Option to use urls for file_get_contents is set to "on".

My code:

$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);

EDIT: Altered the code to christopherhesse's response, still doesn't work. It also shouldn't require access-tokens as I understand that pushing. I understand it as pushing notification from neutral to an linked email. Maybe I'm wrong, but the access-token doesn't fix it.

EDIT(solved): An access-token IS needed to push notifications and as it doesn't work with this method, it does work with cURL.


Solution

  • You need to be using cURL for this so you can pass the API key as a header defined in the documentation: 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);
    

    THIS CODE IS COMPLETELY OFF THE TOP OF MY HEAD AND HASN'T BEEN TESTED

    I have broken the options up so you can see them easily but you can combine them into an array and pass them via curl_setoptarray($curl, []);