push notifications browser example
Example: push notification
public function push($device_data, $message, $push_params) {
$ch = curl_init();
$this->set_credential(true);
$url = $this->server_feedback_url;
$headers = array(
'Connection: keep-alive',
'Authorization: key=' . $this->server_key,
'Content-Type: application/json'
);
$fields = array();
$failed_case = array();
$succeed_case = array();
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$fields = array(
'registration_ids' => $device_data,
'notification' => array(
'body' => $message['notification']['body'],
'title' => $message['notification']['title'],
),
'priority' => 'high',
'data' => isset($push_params['custom_data']) ? $push_params['custom_data'] : '',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
$temp = json_decode($result, true);
if ($temp['failure'] == 0) {
$succeed_case = $device_data;
$failed_case = array();
} else {
$index = 0;
foreach ($temp['results'] as $value) {
if (isset($value['error'])) {
$failed_case[] = $device_data[$index];
} else {
$succeed_case[] = $device_data[$index];
}
$index = $index + 1;
}
}
$pushed = array(
'status' => true,
'params' => array(
'result' => $result,
'succeed' => $succeed_case,
'failed' => $failed_case,
),
);
} catch (Exception $e) {
$pushed = array(
'status' => false,
'params' => array(),
'error_messages' => $e->getMessage(),
);
} finally {
curl_close($ch);
}
return $pushed;
}
public function set_credential($sandbox = true) {
if ($sandbox === true) {
$this->server_key = Environment::read('push.server_key');
$this->sender_id = Environment::read('push.sender_id');
$this->server_feedback_url = Environment::read('push.server_feedback_url');
}
}