如何使用OneSignal API和PHP在推送通知中发送“其他数据”

时间:2019-09-04 12:33:09

标签: php api documentation onesignal

从OneSignals控制面板发送推送通知时,我可以在推送消息中包括“其他数据”(键和值)。

我正在尝试创建一个PHP脚本,该脚本允许我通过OneSignal API从PHP发送推送,但无法在OneSignal的API文档中找到有关其他数据的任何信息。

OneSignal文档的URL:https://documentation.onesignal.com/reference

脚本按原样工作,但是我需要包括其他数据。

有人可以指出我正确的方向吗?

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.";
}

}

1 个答案:

答案 0 :(得分:0)

找到了。 :)

在$ oneSignalConfig数组(代码的底部)中,我添加了以下内容:

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

在$ fields数组中的函数中,我添加了以下内容:

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

这成功了。现在,键和值随推送通知一起发送。