Nativescript with OneSignal push notifications - GET the data on the app - push-notification

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.

Related

Push notification can not get on mobile using laravel

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

Firebase push notification doesn't send notification on background using react-native

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

Wp Rest Api Custom End point POST request

Im trying to post some data to custom api endpoint that i created,
This is what my wordpress custom endpoint code.
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
And for testing I am trying to return the request like this
function create_city_from_data($req) {
return ['req' => $req];
}
but always i receive empty object as response, whatever i send in payload i didn't receive anything.
My payload is something like this
{ name: 'Hello', population: 565656 }
This is what is received from the request
{"req":{}}
By using below code you can view your payload.
add_action('rest_api_init', function () {
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
});
function create_city_from_data($req) {
$response['name'] = $req['name'];
$response['population'] = $req['population'];
$res = new WP_REST_Response($response);
$res->set_status(200);
return ['req' => $res];
}
I have used postman to view the POST parameter
By using this function you can see all post of your custom post type in API...
Get All Post in your API Viewer.
Writer URL on your API viewer (e.g. I used Postman json api view, google chrome adon)
Domain-name/wp-json/showFavorites/v2?post_type=hotel
Here 'hotel' is the custom posttype.
Add this function in your functions.php
add_action( 'rest_api_init', 'wp_api_show_favorites_endpoints' );
function wp_api_show_favorites_endpoints() {
register_rest_route( 'showFavorites', '/v2', array(
'methods' => 'GET',
'callback' => 'showFavorites_callback',
));
}
function showFavorites_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
$parameters = $request_data->get_params();
$post_type = $parameters['post_type'];
if($post_type!=''){
$re_query = "SELECT * FROM $table where post_type='$post_type'";
$pre_results = $wpdb->get_results($re_query,ARRAY_A);
return $pre_results;
}else{
$data['status']=' false ';
return $data;
}
}
And using this you can post your content from API
// POST All Posts using API
add_action( 'rest_api_init', 'wp_api_add_posts_endpoints' );
function wp_api_add_posts_endpoints() {
register_rest_route( 'addPost', '/v2', array(
'methods' => 'POST',
'callback' => 'addPosts_callback',
));
}
function addPosts_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
// Fetching values from API
$parameters = $request_data->get_params();
$user_id = $parameters['user_id'];
$post_type = $parameters['post_type'];
$post_title = $parameters['post_title'];
$the_content = $parameters['the_content'];
$cats = $parameters['cats'];
$the_excerpt = $parameters['the_excerpt'];
$feature_img = $parameters['featured_image'];
// custom meta values
$contact_no = $parameters['contact_no'];
$email = $parameters['email'];
$hotel_url = $parameters['hotel_url'];
if($post_type!='' && $post_title!=''){
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $post_title),
'post_content' => $the_content,
'post_author' => '',
'post_excerpt' => $the_excerpt,
'post_status' => 'publish',
'post_type' => $post_type,
);
$new_post_id = wp_insert_post( $my_post );
function wp_api_encode_acf($data,$post,$context){
$customMeta = (array) get_fields($post['ID']);
$data['meta'] = array_merge($data['meta'], $customMeta );
return $data;
}
if( function_exists('get_fields') ){
add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
}
// Set post categories
$catss = explode(',', $cats);
if (!empty($catss)) {
if ($post_type == 'post') {
wp_set_object_terms( $new_post_id, $catss, 'category', false );
}
else{
wp_set_object_terms( $new_post_id, $catss, 'Categories', false ); // Executes if posttype is other
}
}
// Set Custom Metabox
if ($post_type != 'post') {
update_post_meta($new_post_id, 'contact-no', $contact_no);
update_post_meta($new_post_id, 'email', $email);
update_post_meta($new_post_id, 'hotel-url', $hotel_url);
}
// Set featured Image
$url = $feature_img;
$path = parse_url($url, PHP_URL_PATH);
$filename = basename($path);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($feature_img);
$savefile = fopen($uploadfile, 'w');
chmod($uploadfile, 0777);
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
if ($attach_id) {
set_post_thumbnail( $new_post_id, $attach_id );
}
if ($new_post_id) {
$data['status']='Post added Successfully.';
}
else{
$data['status']='post failed..';
}
}else{
$data['status']=' Please provide correct post details.';
}
return ($data);
}
The object parameter passed into the callback function is a WP_REST_REQUST object and has a get_body() method on it which returns the payload/post body of the HTTP Post Request.
function create_city_from_data(WP_REST_Request $req) {
$body = $req->get_body()
return ['req' => $body];
}
I learnt about this today whilst reading this article
You can also declare the type of object in the method signature in case you need to search the documentation for it (like i have above).
CURL request :
$url = $your_url; // your url should like: http://host.com/wp-json/v1/'.$key
$post_string = json_encode($post_data);// make json string of post data
$ch = curl_init(); //curl initialisation
curl_setopt($ch, CURLOPT_URL, $url); // add url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get return value
curl_setopt($ch, CURLOPT_POST, true); // false for GET request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // add post data
curl_setopt($crl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post_string))
);// add header
$output = curl_exec($ch);
curl_close($ch); // close curl
$error = curl_error($ch); // get error
if(!$error){
return json_decode($output);
}else{
return $error;
}
For Handle Request in PLUGIN context :
public static function handle_requests(WP_REST_Request $request){
$return_data = [];
//get GET params
$key = $request['key'];
//get POST values
$post_data = json_decode($request->get_body());
//$return_data = $post_data;
if ( empty( $return_data ) ) {
return new WP_Error( 'error', 'Invalid Request', array( 'status' => 404 ) );
}else{
return $return_data;
}
}
Your WP REST API ACTION :
add_action( 'rest_api_init', function () {
register_rest_route( '/v1', '/(?P<key>[\w]+)', array(
'methods' => ['GET', 'POST'],
'callback' => 'YOUR_CLASS::handle_requests',
'permission_callback' => '__return_true'
) );
} );
//permission_callback need to add for wordpress newer versions.

Woocommerce CRM connect

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

Wordpress XML-RPC and featured images

I'm currently developing a plugin for a client that takes an xml feed hourly and posts it into wordpress and I'm having trouble sending the featured image to the post.
I can post to wordpress fine but all my attempts to post the featured image have failed.
<?php
class XMLRPClientWordPress
{
var $XMLRPCURL = "";
var $UserName = "";
var $PassWord = "";
// Constructor
public function __construct($xmlrpcurl, $username, $password)
{
$this->XMLRPCURL = $xmlrpcurl;
$this->UserName = $username;
$this->PassWord = $password;
}
function send_request($requestname, $params)
{
$request = xmlrpc_encode_request($requestname, $params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $this->XMLRPCURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
public function create_post( $title, $body )
{
$title = htmlentities( $title, ENT_NOQUOTES, 'UTF-8' );
$content = array(
'post_category' => array( 18 ), // my category id
'post_type' => 'post',
'post_title' => $title,
'post_content' => $body,
'featured_image_url' => 'http://www.geekologie.com/2009/02/18/scary%20clown.jpg',
);
$params = array( 0, $this->UserName, $this->PassWord, $content );
return $this->send_request( 'wp.newPost', $params );
}
}
$objXMLRPClientWordPress = new XMLRPClientWordPress("xxxx/xmlrpc.php" , "xxxxx" , "xxxx");
$objXMLRPClientWordPress->create_post('Hey Chloe','Hope you like the clown');
?>
Is what i currently have, i've been reading the wordpress patch tickets on this issue but can't seem to figure out how to actually use the new features
Thanks
It should be something like this
'wp_post_thumbnail' => $pictureid
You have to get the ID of uploaded picture into variable and then assign it as a value of 'wp_post_thumbnail' parameter for 'metaWeblog.newPost'

Resources