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
Related
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
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 trying to connect my Woocommerce to a CRM. They gave me this example code.
My question:
In what file do i need to add this code in Woocommerce.
class SimplicateApi {
public $authentication_key;
public $authentication_secret;
public $api_url;
public function __construct($domain, $key, $secret){
$this->authentication_key = $key;
$this->authentication_secret = $secret;
$this->api_url = 'https://'.$domain.'/api/v2';
}
public function makeApiCall($method, $url, $payload = NULL) {
// Generate the list of headers to always send.
$headers = array(
"User-Agent: simplicate-koppeling",// Sending a User-Agent header is a best practice.
"Authentication-Key: ".$this->authentication_key,
"Authentication-Secret: ".$this->authentication_secret,
"Accept: application/json", // Always accept JSON response.
);
$endpoint = $this->api_url . $url;
$curl = curl_init($endpoint);
switch(strtoupper($method)) {
case "GET":
// Nothing to do, GET is the default and needs no
// extra headers.
break;
case "POST":
// Add a Content-Type header (IMPORTANT!)
$headers[] = "Content-Type: application/json";
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
break;
case "PATCH":
// Add a Content-Type header (IMPORTANT!)
$headers[] = "Content-Type: application/json";
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
default:
exit;
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (self::isFailure($httpCode)) {
return array('errorNumber' => $httpCode,
'error' => 'Request returned HTTP error '.$httpCode,
'request_url' => $url);
}
$curl_errno = curl_errno($curl);
$curl_err = curl_error($curl);
if ($curl_errno) {
$msg = $curl_errno.": ".$curl_err;
curl_close($curl);
return array('errorNumber' => $curl_errno,
'error' => $msg);
}
else {
error_log("Response: ".$response);
curl_close($curl);
return json_decode($response, true);
}
}
public static function isFailure($httpStatus){
// Simplistic check for failure HTTP status
return ($httpStatus >= 400);
}
}
$SimplicateApi = new SimplicateApi('yourdomain.simplicate.nl','yourapikey','yourapisecret');
// pepare the payload to create an organization
$org_payload = array(
'name' => $variable_with_organization_name,
'phone' => $variable_with_organization_phone,
'email' => $variable_with_organization_email,
'note' => $variable_with_note,
'relation_type' => array(
'id'=>'' //provide the relationtypeid, f.e. relationtype:796ce0d318a2f5db515efc18bba82b90
),
'visiting_address' => array(
'country_code' => 'NL'
), // can be extented with other address data
'postal_address' => array(
'country_code' => 'NL'
) // can be extented with other address data
);
// add the organization to the CRM
$organization = $SimplicateApi->makeApiCall('POST','/crm/organization',json_encode($org_payload));
And nother question.
How about this part:
// pepare the payload to create an organization
$org_payload = array(
'name' => $variable_with_organization_name,
'phone' => $variable_with_organization_phone,
'email' => $variable_with_organization_email,
'note' => $variable_with_note,
Where do i get these variables from woocommerce?
you need Add custom api route
first technique :
inside woocommerce-ac.php add :
add_action('woocommerce_api_loaded', 'wpc_register_wp_api_endpoints');
function wpc_register_wp_api_endpoints() {
include_once( 'woo-includes/api/v2/class-wc-api-carts.php' );
add_filter('woocommerce_api_classes', 'filter_woocommerce_api_classes', 10, 1);
}
function filter_woocommerce_api_classes($array) {
$cart = array(
'WC_API_Carts',
);
return array_merge($array, $cart);
}
and inside woo-includes/api/v2 add class-wc-api-customs.php; that is done
full details
My method of payment with Paypal does not work. After the user arrived on the Paypal page with the description of what he bought, it is directed to my site that says the payment was successful on
http://example.com/Store/ReturnPaypal/?token=EC-8F726826L7777777&PayerID=PEWR9EA
but when I go to my PayPal account, I don't see any extra money
public ActionResult OrderPaypal()
{
string api_paypal = "https://api-3t.paypal.com/nvp?";
string user = "info_api1.example.com";
string pass = "testpass";
string signature = "test.test-test";
string version = "124.0";
string requete = api_paypal + "VERSION=" + version + "&USER=" + user + "&PWD=" + pass + "&SIGNATURE=" + signature;
requete = requete + "&METHOD=SetExpressCheckout" +
"&CANCELURL=" + HttpUtility.UrlEncode("http://example.com/Store/CancelPaypal/") +
"&RETURNURL=" + HttpUtility.UrlEncode("http://example.com/Store/ReturnPaypal/") +
"&AMT=" + SessionData.CurrentOrder.Total.ToString().Replace(',','.') +
"&CURRENCYCODE=EUR" +
"&DESC=" + HttpUtility.UrlEncode("Paiement total:" + SessionData.CurrentOrder.Total+" €") +
"&LOCALECODE=FR" +
"&HDRIMG=" + HttpUtility.UrlEncode("http://example.com/assets/images/home/image_10000.png");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(requete);
WebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string rep = streamReader.ReadToEnd();
if (!string.IsNullOrEmpty(rep))
{
string[] list = rep.Split('&');
Dictionary<string,string> dicParam = new Dictionary<string,string>();
foreach(string str in list)
{
string key = str.Split('=')[0];
string value = str.Split('=')[1];
dicParam.Add(key, value);
}
if (dicParam["ACK"] == "Success")
return Redirect("https://www.paypal.com/webscr&cmd=_express-checkout&token=" + dicParam["TOKEN"]);
else
{
ViewBag.State = "-1";
return View("ReturnSolution",dicParam["L_SHORTMESSAGE0"]);
}
}
else
{
ViewBag.State = "-1";
return View("ReturnSolution", "Error communication PayPal ");
}
}
}
I do not see you completing the transaction with the DoExpressCheckout call.
It looks like you are doing the SetExpressCheckout which will give you the Payer ID and the Express Checkout token. You get this in the URL:
http://example.com/Store/ReturnPaypal/?token=EC-8F726826L7777777&PayerID=PEWR9EA
token=EC-8F726826L7777777
PayerID=PEWR9EA
This is returned in the URL and is used to complete the DoExpressCheckout call (which I do not see in your code).
Here is a sample script of a SetExpressCheckout and DoExpressCheckout in PHP.
<a href='http://marshalcurrier.com/paypal/ExpressCheckout/custom/SetDo.php'>RESET</a><br>
<form method='post'><input type="text" name="CHARGE" value="1"/><input type="submit" value="Pay Now"/><form>
<?php
session_start();
$PPUSER = 'marshal_api1.clubcovert.com';
$PPPWD = 'LL6NV7TDRB9RFXQ5';
$PPSIG = 'ANc3YRaMB1Tgm9TediH0gENHB02JAksSKWD08wVNN3w3pwHqdBW8Im6y';
function url(){ //PayPal Payment URL (TEST or LIVE)
$url = "https://api-3t.sandbox.paypal.com/nvp";
return $url;
}
function curlCall($nvp){ // Function for Curl Call to PayPal.
$url = url();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($nvp) );
//echo http_build_query($nvp); //Print String
curl_setopt($ch, CURLOPT_URL, $url);
$server_output = curl_exec($ch);
mb_parse_str($server_output, $arr);
return $arr;
}
if(isset($_POST['CHARGE'])){ // SetExpressCheckout Call
$_SESSION['AMT'] = $_POST['CHARGE'];
$nvp = array(
'USER' => $PPUSER,
'PWD' => $PPPWD,
'SIGNATURE' => $PPSIG,
'METHOD' => 'SetExpressCheckout',
'VERSION' => '123',
'PAYMENTREQUEST_0_PAYMENTACTION' => 'SALE',
'PAYMENTREQUEST_0_AMT' => $_POST['CHARGE'],
'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
'RETURNURL' => 'http://marshalcurrier.com/paypal/ExpressCheckout/SetDo.php',
'CANCELURL' => 'http://marshalcurrier.com/paypal/ExpressCheckout/SetDo.php',
);
$arr = curlCall($nvp);
echo '<br><br>SetExpressCheckout Call to PayPal:<br><pre>';
print_r ($nvp);
echo '</pre>';
echo 'SetExpressCheckout Server Response:<br><pre>';
print_r ($arr);
echo '</pre>';
echo 'Go To PayPal';
}
if(isset($_GET['PayerID']) && (isset($_POST['CHARGE'])) == false){ // DoExpressCheckoutPayment Call
if (isset($_SESSION['AMT'])){
$AMT = $_SESSION['AMT'];
}else{
$AMT = null;
}
$nvp = array(
'METHOD' => 'DoExpressCheckoutPayment',
'VERSION' => '123',
'USER' => $PPUSER,
'PWD' => $PPPWD,
'SIGNATURE' => $PPSIG,
'PAYERID' => $_GET['PayerID'],
'TOKEN' => $_GET['token'],
'PAYMENTREQUEST_0_PAYMENTACTION' => 'SALE',
'PAYMENTREQUEST_0_AMT' => $AMT,
'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
);
$arr = curlCall($nvp);
echo '<br><br>DoExpressCheckoutPayment Call to PayPal:<br><pre>';
print_r ($nvp);
echo '</pre>';
echo 'DoExpressCheckoutPayment Server Response:<br><pre>';
print_r ($arr);
echo '</pre>';
unset($_SESSION['AMT']);
}
?>
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);