How can I get Device token to send notification? - php

I have built web version in Codeigniter and have been working in mobile version with react Native.
To make new order notification, I am going to use firebase clouding message.
how , where can I get this device token ?
public function sendFCMNotification($registration_ids, $message){
$SERVER_API_KEY ='my server api key';
// payload data, it will vary according to requirement
$data = [
"registration_ids" => $registration_ids,
"data" => $message
];
$dataString = json_encode($data);
$headers = [
'Authorization: key=' . $SERVER_API_KEY,
'Content-Type: application/json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}

In your React-Native app, you can get the token like this:
messaging().getToken().then(token => { saveTokenToDatabase(token);});
then listen for any token change
messaging().onTokenRefresh(token => {saveTokenToDatabase(token);});
The method saveTokenToDatabase is used to save the token to your backend so that you can access it later to send messages

In android you need to use this class to get device token
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.e("newToken", token);
//Add your token in your sharefpreferences.
SharedPreferenceManager app_sp = new SharedPreferenceManager(this);
app_sp.putString(Constants.FIREBASE_TOKEN, token);
this service request which update device token on to your server
// updatetokenAPI.updateToken(token);

Related

Xamarin Forms does not recieve firebase notification send from php

I am Working on Xamarin Forms Platform to Implement the Firebase Notification. I have add google-services.json and GoogleService-Info.plist in android and IOS applicaition respectively by setting appropriate property.I have generated token code natively and using dependency service I am getting the generated token for sending notification on same or different device. For sending the Notification I am using php since my application use php as mediator for communicating with database and xamarin forms.
class MyFirebaseIIDService : FirebaseInstanceIdService, IPushHelper
{
public string GetPushToken()
{
return FirebaseInstanceId.Instance.Token;
}
}
public interface IPushHelper
{
string GetPushToken();
}
This is how I am Accessing Token in Xamarin Forms
string token = DependencyService.Get<IPushHelper>().GetPushToken();
PHP Code For Sending Notification
$fields = array(
'to' => $token // Token Generated By Xamarin Forms
'data'=> array("message"=>$message) // Message For Notification
);
//Header Including API Key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);
$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('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
Also, I have tried shell_exec() for running curl
$result =shell_exec('curl -X POST --header "Authorization: key='.$api_key.'" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"'.$token.'\",\"priority\":\"high\",\"notification\":{\"body\": \"'.stripslashes($message).'\"}}"');
Output for result:
"{"multicast_id":8563984716459935776,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1585669578263131%631c6722f9fd7ecd"}]}"
But My Application does not recieve push Notification and I could see the send notication in firebase console.
Please Help me for sending and getting Notification using Firebase

How to get Firebase target by PHP?

I'm building an PHP website. I want to push notification to client(who login to my website) so I use Firebase Cloud Messaging.
I already registered Firebase app and write a function to send message
public function sendMessage($data, $target)
{
//FCM api URL
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'MY SERVER KEY';
$fields = array();
$fields['data'] = $data;
if (is_array($target)) {
$fields['registration_ids'] = $target;
} else {
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $server_key
);
$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('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
But I don't know how to get $target to let Firebase send message to.
Now I want when user register/login on my website, I will request token from Firebase and save it to my DB.
Because when I want send message to that user, I need provide target(token) for Firebase. Anyone please help me?
At first, client should have application that uses your firebase project.
Then you can sand message to it application, and you have 2 ways to do it:
You have to acquire his registration token
His app on smartphone should be registered in some topic, ex. "general".

Handshake error in PHP call to SurveyMonkey API V3

I am new to REST and have been tasked with retrieving SurveyMonkey survey data using the V3 API. I am using PHP. My code is as follows:
$fields = array(
'title'=>'New Admission Survey',
'object_ids' => array($surveyID));
$fieldsString = json_encode($fields);
$curl = curl_init();
$requestHeaders = array(
"Authorization" => 'bearer abc123',
"Content-Type" => 'application/json',
'Content-Length: ' . strlen($fieldsString));
$baseUrl = 'https://api.surveymonkey.net/v3';
$endpoint = '/surveys/';
curl_setopt($curl, CURLOPT_URL, $baseUrl . $endpoint);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $requestHeaders);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $fieldsString);
$curl_response = curl_exec($curl);
if($curl_response == false){
echo('Well, crap');
$info = curl_getinfo($curl);
echo('<pre>');print_r($info);echo('</pre>');
echo('<pre>');print_r(curl_error($curl));echo('</pre>');}
else {
echo('Test: ' . $curl_response);}
curl_close($curl);
I am getting the following error:
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
I have verified the Auth Token I am using is the one issued to me when I registered my app (done today).
Am I missing something? Most of the questions and answers deal with V2 of the SurveyMonkey API. I am using V3.
Thanks for your help!
I'm not sure if this will help the specific error you're encountering, but have you tried using this API wrapper? https://github.com/ghassani/surveymonkey-v3-api-php
This API wrapper simplified my tasks considerably:
<?php
// Init the client.
$client = Spliced\SurveyMonkey\Client(MY_CLIENT_ID, MY_ACCESS_TOKEN);
// Get a specific survey.
$survey = $client->getSurvey(MY_SURVEY_ID);
// Get all responses for this survey.
/** #var Spliced\SurveyMonkey\Response $responses */
$responses = $client->getSurveyResponses(MY_SURVEY_ID);
// Get a specific response.
/** #var Spliced\SurveyMonkey\Response $response */
$response = $client->getSurveyResponse(MY_SURVEY_ID, RESPONSE_ID, TRUE);
/* etc... */

push notifications IOS using FCM

I am using FCM to send push notification to IOS app, IOS dev provide me device token and SERVER_KEY, I search on google and tried different solutions but nothing worked for me , So let me know what is wrong with my code, Getting error {
"multicast_id": 8569689262516537799,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
Thanks in advance
$ch = curl_init("https://fcm.googleapis.com/fcm/send");
//The device token.
$token = "c2420d68a0838d8fb6b26ef06278e899de73a149e93c9fe13df11f70f3dd5cc1"; //token here
//Title of the Notification.
$title = "Carbon";
//Body of the Notification.
$body = "Bear island knows no king but the king in the north, whose name is stark.";
//Creating the notification array.
$notification = array('title' => $title, 'text' => $body);
//This array contains, the token and the notification. The 'to' attribute stores the token.
$arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
//Generating JSON encoded string form the above array.
$json = json_encode($arrayToSend);
//print_r($json); die();
//Setup headers:
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=AAAAx6P1Nz0:APA91bEqkVCA9YRw9gpUvmF8UOVrYJ5T8672wfS_I7UAT3dA0g1QS7z-Z4fpn8JMiJ5kFRz9ZGc2K64hKZG-4__PAUqm733hqNDuFCDv9'; // key here
//Setup curl, add headers and post parameters.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//Send the request
$response = curl_exec($ch);
//Close request
print_r($response);
curl_close($ch);
//return $response;
token number ur sending is most probably wrong. try "/topics/all" this will send notification to all the users registered.

Executing Curl in PHP to do a Stripe subscription

The Stripe API allows for Curl calls to be made. For example, the command:
curl https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:
returns the subscription of customer cus_5ucsCmNxF3jsSY.
How can I use PHP to call this curl command (I am trying to avoid using the PHP Stripe libraries).
I am trying the following:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com//v1/customers/cus_5ucsCmNxF3jsSY/subscriptions -u sk_test_REDACTED:");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print($output);
// close curl resource to free up system resources
curl_close($ch);
?>
However, it seems that curl does not take the -u parameter of the URL. I get the following error:
{ "error": { "type": "invalid_request_error", "message": "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/." }
How can I pass the -u sk_test_REDACTED: parameter to my curl call?
I ran into the same issue. I wanted to use PHP's CURL functions instead of using the official stripe API because singletons make me nauseous.
I wrote my own very simple Stripe class which utilizes their API via PHP and CURL.
class Stripe {
public $headers;
public $url = 'https://api.stripe.com/v1/';
public $method = null;
public $fields = array();
function __construct () {
$this->headers = array('Authorization: Bearer '.STRIPE_API_KEY); // STRIPE_API_KEY = your stripe api key
}
function call () {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
switch ($this->method){
case "POST":
curl_setopt($ch, CURLOPT_POST, 1);
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
case "PUT":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
if ($this->fields)
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->fields);
break;
default:
if ($this->fields)
$this->url = sprintf("%s?%s", $this->url, http_build_query($this->fields));
}
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true); // return php array with api response
}
}
// create customer and use email to identify them in stripe
$s = new Stripe();
$s->url .= 'customers';
$s->method = "POST";
$s->fields['email'] = $_POST['email'];
$customer = $s->call();
// create customer subscription with credit card and plan
$s = new Stripe();
$s->url .= 'customers/'.$customer['id'].'/subscriptions';
$s->method = "POST";
$s->fields['plan'] = $_POST['plan']; // name of the stripe plan i.e. my_stripe_plan
// credit card details
$s->fields['source'] = array(
'object' => 'card',
'exp_month' => $_POST['card_exp_month'],
'exp_year' => $_POST['card_exp_year'],
'number' => $_POST['card_number'],
'cvc' => $_POST['card_cvc']
);
$subscription = $s->call();
You can dump $customer and $subscription via print_r to see the response arrays if you want to manipulate the data further.

Categories