Monday, April 8, 2019

How to send push notification message on android/iphone mobile in php


How to send push notification message on android :

define( 'API_ACCESS_KEY', 'AIzaSyCpLu60wrNH5nTbOxnTC89YsLSJV7PwfAY' );
$message_txt =$_REQUEST['msg'];
$msg['message'] = array("other"=> array('title'=>$message_txt));
$registrationIds = array();
$mylink = "SELECT * FROM notification WHERE device_type ='android'";  // Ids whre send notifications


foreach($mylink as $val){
$registrationIds[]=$val->device_id;
}
//print_r($msg);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
/*print_r($fields);
exit;*/
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
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 );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
print_r($result);

How to send push notification message on iphone :

$message_txt =$_REQUEST['msg'];
$registrationIds = array();
$mylink =  "SELECT * FROM notification WHERE device_type ='iphone'" ;
// Ids whre send notifications
foreach($mylink as $val){
$registrationIds[]=$val->device_id;
}
$arr_cnt = count($registrationIds);
$tHost = 'gateway.push.apple.com';
$tPort = 2195;
$tCert = 'iphone_config/apns-dis-cert.pem';
$tPassphrase = 'choc3747*';
//$tToken = $registrationIds;
$tAlert = $data->post_title;
$tBadge = 0;
$tSound = 'default';
$tPayload = 'APNS Message Handled by LiveCode';
$tBody['aps'] = array (
'alert' => $message_txt,
'type' => "other",
'badge' => $tBadge,
'sound' => $tSound,
);
//print_r($tBody);
$tBody ['payload'] = $tPayload;
$tBody = json_encode ($tBody);
$tContext = stream_context_create ();
stream_context_set_option ($tContext, 'ssl', 'local_cert', $tCert);
stream_context_set_option ($tContext, 'ssl', 'passphrase', $tPassphrase);
$tSocket = stream_socket_client ('ssl://'.$tHost.':'.$tPort, $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $tContext);
if (!$tSocket)
exit ("APNS Connection Failed: $error $errstr" . PHP_EOL);
for($i=0;$i<$arr_cnt;$i++)
{
$tMsg = chr (0) . chr (0) . chr (32) . pack ('H*',str_replace(' ','',$registrationIds[$i])) . pack ('n', strlen ($tBody)) . $tBody;
$tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg));
//sleep(3);
}
/*if ($tResult)
echo 'Delivered Message to APNS' . PHP_EOL;
else
echo 'Could not Deliver Message to APNS' . PHP_EOL;*/
fclose ($tSocket);
print_r($tResult);

No comments:

Post a Comment