I am trying to send push notification to a mobile device using the following function but it can not send. I am checking through firebase, it works but it can not send through my coding.
This is my function & give result as follows,
Result=
"{"multicast_id":7523757847702384710,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1558857210405129%6298e0406298e040"}]}"
public function sendNotification(Request $req)
{
$fcm_token=$req->input('fcm_token');
$json_data=[
"to" => $fcm_token,
"notification" => [
"body" => "hello",
"title" => "hello"
]
];
$data = json_encode($json_data);
//FCM API end-point
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'AIzaSyDF4_rqij_Bt4zC3GNEVbNFvwX1HHxy5Mo';
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
//CURL request to route notification to FCM connection server (provided by Google)
$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_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result === FALSE) {
die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
dd($result);
}
When I send a notification, mobile gets the push notification.
In laravel we usually use brozot package to send push notification through laravel instead of using the core php.
https://packagist.org/packages/brozot/laravel-fcm
Related
I want to send notification to android and IOS devices using laravel 5.8. Please help me on recommending the best package for sending push notification.
when using this funcation This error appears "{"multicast_id":6507423456439771247,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}"
public function sendPushNotification($fcm_token, $title, $message, $id = null) {
$url = "https://fcm.googleapis.com/fcm/send";
$header = [
'authorization:key=key',
'content-type: application/json'
];
$postdata = '{
"to" : "' . $fcm_token . '",
"notification" : {
"title":"' . $title . '",
"text" : "' . $message . '"
},
"data" : {
"id" : "'.$id.'",
"title":"' . $title . '",
"description" : "' . $message . '",
"text" : "' . $message . '",
"is_read": 0
}
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I´ve been searching a lot to find a solution but my problem as to do with some understanding of the mechanism, so i was wondering if someone could help me:
At this moment i´m sending push notifications using the REST api from OneSignal and it´s working...but i don´t know how to reach the data sent in order to tell the app to go to a specific place:
My server side:
public function sendMessage(){
$content = array(
"en" => 'Nova Angariação'
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "like-button",
"text" => "Ver",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "https://yoursite.com"
));
$fields = array(
'app_id' => "myAppId",
'included_segments' => array(
'All'
),
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'buttons' => $hashes_array
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic my rest key'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$resp = curl_exec($ch);
curl_close($ch);
return $resp;
}
Now in my app(i´m using nativescript with OneSignal SDK):
if (application.ios) {
const MyDelegate = /** #class */ (function (_super) {
__extends(MyDelegate, _super);
function MyDelegate() {
return _super !== null && _super.apply(this, arguments) || this;
}
MyDelegate.prototype.applicationDidFinishLaunchingWithOptions = function (app, launchOptions) {
try {
**//i think it´s here where i have to handle the handleNotificationOpened but i don´t know how**
TnsOneSignal.initWithLaunchOptionsAppId(launchOptions, 'my onesignal app key');
}
catch (error) {
console.error('error', error);
}
return true;
};
MyDelegate.ObjCProtocols = [UIApplicationDelegate];
return MyDelegate;
}(UIResponder));
application.ios.delegate = MyDelegate;
}
How do i do this?
Thanks for your time
Regards.
If you want to access the notification data upon app launch, then try this inside applicationDidFinishLaunchingWithOptions
if (launchOptions) {
const userInfo = launchOptions.objectForKey(UIApplicationLaunchOptionsRemoteNotificationKey);
if (userInfo) {
const aps = userInfo.objectForKey("aps");
if (aps !== null) {
// aps will be again a dictionary will have all data for the notification
}
}
}
Between didReceiveRemoteNotification also works, but when application is already in foreground.
I'm going to develop a react-native app which uses Firebase Push Notification , when I send push notification from Firebase Console it's working on both background and foreground of the app , but when I send notification from my server using PHP(WordPress) it just sends notification while the app is in foreground and not in background, but the notification message result show success.
Here I'm gonna provide some of codes
Mobile side:
import React, { Component } from "react";
import { Platform, AsyncStorage } from 'react-native';
import FCM, { FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType } from "react-native-fcm";
export default class PushNotificationController extends
Component {
constructor(props) {
super(props);
console.ignoredYellowBox = ['Setting a timer'];
this.state = {
firebase_token :'',
}
}
saveFirebaseToken() {
console.log("------------- as "+this.state.firebase_token+" ---------- ");
AsyncStorage.setItem('firebase_token', this.state.firebase_token);
}
componentDidMount() {
FCM.requestPermissions();
FCM.getFCMToken().then(token => {
console.log(token+' on getFCMToken');
this.setState({
firebase_token: token,
})
this.saveFirebaseToken()
});
FCM.getInitialNotification().then(notif => {
console.log("INITIAL NOTIFICATION", notif)
});
this.notificationListner = FCM.on (FCMEvent.Notification, notif => {
console.log("Notification", notif);
if (notif.local_notification) {
return;
}
if (notif.opened_from_tray) {
return;
}
if (Platform.OS === 'ios') {
//optional
//iOS requires developers to call completionHandler to end notification process. If you do not call it your background remote notifications could be throttled, to read more about it see the above documentation link.
//This library handles it for you automatically with default behavior (for remote notification, finish with NoData; for WillPresent, finish depend on "show_in_foreground"). However if you want to return different result, follow the following code to override
//notif._notificationType is available for iOS platfrom
switch (notif._notificationType) {
case NotificationType.Remote:
notif.finish(RemoteNotificationResult.NewData) //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
break;
case NotificationType.NotificationResponse:
notif.finish();
break;
case NotificationType.WillPresent:
notif.finish(WillPresentNotificationResult.All) //other types available: WillPresentNotificationResult.None
break;
}
}
this.showLocalNotification(notif);
});
this.refreshTokenListener = FCM.on(FCMEvent.RefreshToken, token => {
console.log("TOKEN (refreshUnsubscribe)", token);
});
}
showLocalNotification(notif) {
FCM.presentLocalNotification({
title: notif.title,
body: notif.body,
priority: "high",
click_action: notif.click_action,
show_in_foreground: true,
local: true
});
}
componentWillUnmount() {
this.notificationListner.remove();
this.refreshTokenListener.remove();
}
render() {
return null;
}
}
Added codes in manifest:
<receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
<receiver android:enabled="true" android:exported="true" android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
And Here is the server codes:
function send_notification($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = My_KEY',
'Content-Type: application/json'
);
$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_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
Hopefully I could figure out to solve this with a friend of mine and the help of the bottom link.
Solution: I need to re-format the data I was sending to Firbase server, the payload issues which are used for custom data sending along with notification was involved here.
function send_notification($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$msg = array
(
'body' => $data,
'title' => "New Job",
'sound' => 'default',
'vibrate' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$dat = array
(
'job_id' => "90",
'emp_id' => "9000",
'cand_id' => "1010001"
);
$fields = array
(
'registration_ids' => array($tokens),
'notification' => $msg,
'data' => $dat
);
$headers = array(
'Authorization:key = My_KEY',
'Content-Type: application/json'
);
$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_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
Also the credit goes to #HarikumarAlangode for his useful answer.
Make a custom data for parameter on firebase to call on push notification
Notification Payload Object
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
},
"data" : {
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
}
For more info: https://firebase.google.com/docs/cloud-messaging/concept-options
I want to execute below script while doing checkout in woocommerce.
$args = http_build_query(array(
'token' => '*********',
'from' => '****',
'to' => '*******',
'text' => 'Your Order Id is: 9879987 '));
$url = "http://api.sparrowsms.com/v2/sms/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
I didn't find checkout process page.
You need to add a woocommerce_after_checkout_form hook in function.php like below.
add_action( 'woocommerce_after_checkout_form', 'sms_function', 10 );
function sms_function( ) {
$args = http_build_query(array(
'token' => '*********',
'from' => '****',
'to' => '*******',
'text' => 'Your Order Id is: 9879987 '));
$url = "http://api.sparrowsms.com/v2/sms/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
}
In Wordpress, i want to create New Users from external. I've found this is function in wordpress:
wp_create_user( $username, $password, $email );
So how can i run this function from external call please?
I mean, how to run this function from either:
Via simple URL with GET, like: www.example.com/adduser/?username=james&password=simpletext&email=myemail
Via cURL with POST
.. from external website.
You may try this but also make sure that the listening url has a handler to handle the request in your WordPress end (using GET methof)
function curlAdduser($strUrl)
{
if( empty($strUrl) )
{
return 'Error: invalid Url given';
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $strUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$return = curl_exec($ch);
curl_close($ch);
return $return;
}
Call the function from external site :
curlAdduser("www.example.com/adduser?username=james&password=simpletext&email=myemail");
Update : using POST method
function curlAdduser($strUrl, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
$fields = rtrim($fields, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $strUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$return = curl_exec($ch);
curl_close($ch);
return $return;
}
Call the function with data
$data = array(
"username" => "james",
"password" => "simpletext",
"email" => "myemail"
);
curlAdduser("www.example.com/adduser", $data);