Search code examples
phponesignal

How to send "additional data" in push notification with OneSignal API and PHP


When sending Push Notification from OneSignals control panel, I can include "additional data" (key and value) in the push message.

I am trying to create a PHP script that allows me to send push from PHP through OneSignal API, but can't find anything about additional data in OneSignal's API documentation.

URL to OneSignal Documentation: https://documentation.onesignal.com/reference

The script is working as is, but I need to include additional data.

Can someone point me in the right direction?

function sendPush($oneSignalConfig) {
if (sizeof($oneSignalConfig)) {  
  $notifTitle = html_entity_decode($oneSignalConfig['title'],ENT_QUOTES, 'UTF-8');
  $notifContent = html_entity_decode($oneSignalConfig['brief'],ENT_QUOTES, 'UTF-8');
        
  $includedSegments = array('All');      

  $fields = array(
    'app_id' => $oneSignalConfig['app_id'],
    'headings' => array("en" => $notifTitle),
    'included_segments' => $includedSegments,
    'isAnyWeb' => true,
    'url' => $oneSignalConfig['url'],
    'contents' => array("en" => $notifContent)
  );
  
  $thumbnailUrl = $oneSignalConfig['image_url'];

  if (!empty($thumbnailUrl)) {
      $fields['chrome_web_image'] = $thumbnailUrl;
  }

  $logoUrl = $oneSignalConfig['logo_url'];

  if (!empty($logoUrl)) {
      $fields['chrome_web_icon'] = $logoUrl;
  }

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                         'Authorization: Basic ' . $oneSignalConfig['app_rest_api_key']));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_HEADER, FALSE);
  curl_setopt($ch, CURLOPT_POST, TRUE);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

  $response = curl_exec($ch);
  curl_close($ch);
  
  return $response;
}

return null;
} // EO_Fn 


if(isset($_POST['send'])) {

$oneSignalConfig = array(
'app_id' => 'xxxxx', //APP ID (ONESIGNAL)
'app_rest_api_key' => 'xxxxx', //REST API KEY
'title' => $_POST['tittel'], //TITLE
'brief' => $_POST['beskjed'], //BESKJED
'url' => $_POST['side'], //CONTENT URL
'image_url' => 'xxxx', //BILDE URL
'logo_url' => 'xxxx', // LOGO URL
);

$behandle = sendPush($oneSignalConfig);
if($behandle) {
    $array = json_decode($behandle, true);
    $melding = $array['recipients']." personer har mottatt push varslet.";
}

}

Solution

  • Found it. :)

    In $oneSignalConfig array (bottom of the code), i added following:

    'key' => 'some value here',
    'value' => 'something here',
    

    Inside the function at $fields array, i added following:

    'data' => array($oneSignalConfig['key'] => $oneSignalConfig['value'])
    

    This did the trick. Key and Value is now sent with push notification.