Onesignal REST API Request from php Please include a case-sensitive header of Authorization: Basic

Viewed 738

I am trying to send notifications using Onesignal rest API, I've already setup a new application in my onesignal account. I've made sure the REST API key and app_id is correct but still I get the following error

 {"errors":["Please include a case-sensitive header of Authorization: Basic \u003cYOUR-REST-API-KEY-HERE\u003e or Bearer token=\"\u003cYOUR-REST-API-KEY-HERE\u003e\" with a valid REST API key."],"reference":["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]}

I have only one application in onesignal account I have tested the rest api with POSTMAN and changed the request type to POST works like a charm but using PHP gets me the error.

here is the example code That sends the request

$ch = curl_init();
$header = array();
$header[] = "Content-type: application/json;";
$header[] = "authorization: Basic <MY-REST-API-KEY>";
$fields = array(
          'app_id' => '<MY-APP-ID>',
          'filters' => array(array("field" => "tag", "key" => "player_id", "relation" => "=", "value" => "48223a70-6fb0-11ec-a059-d208b7d4ecd7")),
                    'contents' => array("en"=> "Test From front end"),
      );
print_r($header);
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$res = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($res);

1 Answers

I finally managed to solve the problem using the following code

I guess the issue was I was missing some parameters such as

  1. CURLOPT_CUSTOMREQUEST
  2. CURLOPT_HTTP_VERSION
  3. CURLOPT_MAXREDIRS
$curl = curl_init();
       
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://onesignal.com/api/v1/notifications',
          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 =>'{
          "app_id": "<My-App-ID",
          "data": {"foo": "bar"},
          "include_player_ids":["<player_id>"],
          "contents": {"en": "'.$message.'"},
          "headings":{"en":"'.$header.'"}
        }',

          CURLOPT_HTTPHEADER => array(
            'Authorization: Basic <My-REST_API-Key',
            'Content-Type: application/json'
          ),
        ));

        $response = curl_exec($curl);
Related