I am very suck. I am trying to send to a php array of device id's with urban airship. I am using the first example found here. Everything works, with "audience"=>"all". Every registered device gets hit. I need to make a query of a database, that has a bunch of device id's in it, and send to those device id's. What do I change "audience"=>"all" to so I can do that. I have tried everything!
Here is the code incase the link breaks:
<?php
define('APPKEY','XXXXXXXXXXXXXXX'); // Your App Key
define('PUSHSECRET', 'XXXXXXXXXXXXXXX'); // Your Master Secret
define('PUSHURL', 'https://go.urbanairship.com/api/push/');
$contents = array();
$contents['badge'] = "+1";
$contents['alert'] = "PHP script test";
$contents['sound'] = "cat.caf";
$notification = array();
$notification['ios'] = $contents;
$platform = array();
array_push($platform, "ios");
$push = array("audience"=>"all", "notification"=>$notification, "device_types"=>$platform);
$json = json_encode($push);
$session = curl_init(PUSHURL);
curl_setopt($session, CURLOPT_USERPWD, APPKEY . ':' . PUSHSECRET);
curl_setopt($session, CURLOPT_POST, True);
curl_setopt($session, CURLOPT_POSTFIELDS, $json);
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_RETURNTRANSFER, True);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Accept: application/vnd.urbanairship+json; version=3;'));
$content = curl_exec($session);
echo $content; // just for testing what was sent
// Check if any error occured
$response = curl_getinfo($session);
if($response['http_code'] != 202) {
echo "Got negative response from server, http code: ".
$response['http_code'] . "\n";
} else {
echo "Wow, it worked!\n";
}
curl_close($session);
?>
It depends on what device OS you are trying to send to. Via their documentation here:
http://docs.urbanairship.com/reference/api/v3/push.html#atomic-selectors
you will need to set the correct device type to it's corresponding ID. For example:
android:
"audience" : {
"apid" : "b8f9b663-0a3b-cf45-587a-be880946e880"
}
ios:
"audience" : {
"device_token" : "C9E454F6105B0F442CABD48CB678E9A230C9A141F83CF4CC03665375EB78AD3A"
}
I found a possible solution for this from urban airship help center... They suggest this. And its working for me.
You can send to multiple device tokens or APIDs in a single request. I would suggest using our new API v3 and batching up your requests. There are a couple ways to do this:
1) Send to multiple devices in one payload
curl -v -X POST -u "<AppKey>:<MasterSecret>" -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '{"audience" : {"OR": [{"device_token":"<DeviceToken1>"}, {"device_token":"<DeviceToken2>"}, {"device_token":"<DeviceToken3>"}]}, "notification" : {"alert" : "Hello iOS devices!"}, "device_types" : ["ios"]}' https://go.urbanairship.com/api/push/
OR
2) Put multiple payloads together in one batch
curl -v -X POST -u "<AppKey>:<MasterSecret>" -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '[{"audience": {"device_token": "<DeviceToken1>"}, "notification": {"alert": "Hello, I was sent along with a batch of other pushes!"}, "device_types": ["ios"]}, {"audience": {"device_token": "<DeviceToken2>"}, "notification": {"alert": "I was also sent with a batch of other pushes!"}, "device_types": ["ios"]}, {"audience": {"device_token": "<DeviceToken3>"}, "notification": {"alert": "Me three!"}, "device_types": ["ios"]}]' https://go.urbanairship.com/api/push/
Switched to the PHP 2 library for Urban Airship and I was able to send to individual device tokens. I was also able to read tokens out of an array, and assign the array value as the target. Version 2 found here.
Related
It is my first time trying to connect Sheet from Smartsheet using API with PHP.
I cannot seem to connect and give me this error
Notice: Trying to get property of non-object in C:\xampp\htdocs\smartsheet\test.php on line 22
The variable $sheetObj is empty.
And in Authorization: Bearer, what does Bearer means? Is it a token name or it is always Bearer?
My future plan is to write into the row of smartsheet using PHP. Can anyone give me advice what went wrong with my code?
$baseURL = "https://api.smartsheet.com/1.1";
$sheetsURL = $baseURL . "/sheets/";
$getSheetURL = $baseURL . "/sheet/xxxxxxxxxxx";
$rowsURL = $baseURL . "/sheet/xxxxxxxxxxx/rows";
$accessToken = "xxxxxxxxxxxxxxxxxx";
// Create Headers array for cURL
$headers = array(
"Authorization: Bearer " . $accessToken,
"Content-Type: application/json"
);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";
Both stmcallister and Kim provided good information on how to troubleshoot your issue and some likely causes.
There were actually two issues with the code you provided.
As Scott mentioned you must point to the 2.0 version of the API.
$baseURL = "https://api.smartsheet.com/2.0";
You have a typo in your $getSheetURL. As is documented here the url is /sheets/{sheetId}. So your code should have the following:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
Here is your code in a working state. Make sure to replace YOUR_TOKEN and also take a look at the output from var_dump (which I added to your code) to see what message it gives you.
<?php
$baseURL = "https://api.smartsheet.com/2.0";
$getSheetURL = $baseURL. "/sheets/4925037959505796";
$accessToken = "YOUR_TOKEN";
$headers = array("Authorization: Bearer ". $accessToken);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
// Remove this line when done debugging
var_dump($getSheetResponseData);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";
?>
Search here on SO for the (partial) error message "Trying to get property of non-object" and you'll see lots of related posts. Essentially, this error means that your code is treating something as an object that's not actually an object. This would happen, for instance, when you try to access the name property of $sheetObj if the API request had previously failed for some reason and the contents of $sheetObj is therefore not actually an object.
I'm not very familiar with PHP, but I'd suspect (based on the error message, combined with the fact that you say "var_dump($getSheetResponseData) is Bool(false)) that the "Get Sheet" request may not be returning a successful response. To troubleshoot, I'd suggest that you try running the exact same "Get Sheet" request (i.e., with identical URI, including sheet Id) using a tool like Postman (https://www.getpostman.com/) or via the commandline with cURL, and see if you get a successful response. If you can get your request working via Postman or cURL, it should be straightforward to update your code to send the same request, resulting in a successful response. See this section of the Smartsheet API docs for info about API Troubleshooting techniques using Postman or cURL: http://smartsheet-platform.github.io/api-docs/#api-troubleshooting.
Version 1.1 of the Smartsheet API is no longer supported. You'll want to use version 2.
To do this just change $baseURL to this:
$baseURL = "https://api.smartsheet.com/2.0";
Also, each of the objects in the API will be represented by plural endpoints. So, to get a sheet you'll use:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
To get the rows you'll use:
$rowsURL = $baseURL. "/sheets/xxxxxxxxxxx/rows";
Bearer is the type of Authorization header that you're passing to the API, and the type that is required by the Smartsheet API.
Hello to use the smartsheet API connection to PHP, the API version 2.0 is used, because the older version is obsolete, the code for the connection is as follows:
$baseURL = "https://api.smartsheet.com/2.0/sheets";
// Insertar access token generado en SmartSheet
$accessToken = "YOUR_TOKEN";
// Creación del Headers Array para el Curl
$headers = array(
"Authorization: Bearer $accessToken",
"Content-Type: application/json");
//Conexión de la API de SmartSheet
$curlSession = curl_init($baseURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
//Establece la sesión del Curl
$smartsheetData = curl_exec($curlSession);
// Asignar respuesta a un objeto PHP
$createObj = json_decode($smartsheetData);
I would like to write messenger bot based on this script:
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
// Set this Verify Token Value on your Facebook App
if ($verify_token === 'testtoken') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
// Get the Senders Graph ID
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
// Get the returned message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//API Url and Access Token, generate this token value on your Facebook App Page
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<ACCESS-TOKEN-VALUE>';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"The message you want to return"
}
}';
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request but first check if the message is not empty.
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>
All works correctly but i receive two responses to variable $message, for example:
Send "Hello";
$message = "Hello";
Receive message: "Hi";
$message = "Hi";
I would like to skip 3 and 4 points and receive only "Hello" message because i have to check if $message is my question or answer. Is it possible?
Greetings
You should skip any read and delivery messages, like this:
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
// Skipping delivery messages
if (!empty($message['delivery'])) {
continue;
}
// Skipping read messages
if (!empty($message['read'])) {
continue;
}
}
}
Or, you can deselect message_reads & message_deliveries checkboxes in Page Subscription section of your Facebook Page Settings/Webhooks.
I'm calling a server to deliver a digital product, and I want to let the server check if the payment is completed. I'm using in-app billing and the mobile checkout from PayPal from an Android app.
They get a RESULT_OK, then I'm calling a server, but I want the server to verify if the payment is completed.
I've found some documentation, but it's not really clear what I should use.
For google play in-app I should be able to check this POST:
www.googleapis.com/androidpublisher/v1.1/applications/{packageName}/inapp/{productId}/purchases/{token}
I couldn't find what the productId is, but I'm guessing it's the SKU I'm sending, and where to I get the token?
For PayPal, I found:
GET https://api.paypal.com/v1/payments/sale/{id}
This makes it a little more clear, but I don't know how to convert this into PHP: https://quar.me/paypal/rest/_sales_look-up-a-sale.html
But the id in the documentation looks a lot different than the one I have in the app and is not working. It returns nothing, my ID looks like this AP-8BH89990X7137743X:
{
"name": "INVALID_RESOURCE_ID",
"message": "The requested resource ID was not found",
"information_link": "https://developer.paypal.com/webapps/developer/docs/api/#INVALID_RESOURCE_ID",
"debug_id": "fec9d138aa55d"
}
Getting closer on PayPal, I'm still not sure how to translate this to PHP and how to deal with the certificate when using this form my server. It also seems like depending on the use of a PayPal account or a credit card you should use different verifications, how do I know which method the user used?:
curl -s --insecure
-H "X-PAYPAL-SECURITY-USERID: api_username"
-H "X-PAYPAL-SECURITY-PASSWORD: api_password"
-H "X-PAYPAL-SECURITY-SIGNATURE: api_signature"
-H "X-PAYPAL-REQUEST-DATA-FORMAT: NV"
-H "X-PAYPAL-RESPONSE-DATA-FORMAT: NV"
-H "X-PAYPAL-APPLICATION-ID: app_id"
https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails -d
"payKey=AP-3TY011106S4428730
&requestEnvelope.errorLanguage=en_US"
Some example code would help me a lot, I'm using PHP.
You can use the following functions:
function verify_play($signed_data, $signature)
{
global $public_key_base64;
$pkey = "-----BEGIN PUBLIC KEY-----\n".
chunk_split($public_key_base64, 64,"\n").
'-----END PUBLIC KEY-----';
//using PHP to create an RSA key
$pkey = openssl_get_publickey($pkey);
//$signature should be in binary format, but it comes as BASE64.
//So, I'll convert it.
$signature = base64_decode($signature);
//using PHP's native support to verify the signature
$result = openssl_verify(
$signed_data,
$signature,
$pkey,
OPENSSL_ALGO_SHA1);
if (0 === $result)
{
return false;
}
else if (1 !== $result)
{
return false;
}
else
{
return true;
}
} ;
function verify_paypal($payKey, $appID)
{
global $payPalUser_Id, $payPalPassword, $payPalSig;
$headerArray = array(
'X-PAYPAL-SECURITY-USERID:'.$payPalUser_Id,
'X-PAYPAL-SECURITY-PASSWORD:'.$payPalPassword,
'X-PAYPAL-SECURITY-SIGNATURE:'.$payPalSig,
'X-PAYPAL-REQUEST-DATA-FORMAT:JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT:XML',
'X-PAYPAL-APPLICATION-ID:'.$appID
);
$url="https://svcs.paypal.com/AdaptivePayments/PaymentDetails?payKey={$payKey}&requestEnvelope.errorLanguage=en_US";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$adaptiveResponse = curl_exec($ch);
curl_close($ch);
echo $adaptiveResponse;
//check following and return true or false:
//Is completed ("status": "COMPLETED").
//Is the expected currency ("currencyCode": "USD").
//Has a paymentInfo within paymentInfoList that:
//Has a receiver with amount and email as expected.
//Is complete ("senderTransactionStatus": "COMPLETED").
};
I'm working with the Urban Airship (v3) API to push out messages to Android/iPhone/Blackberry and hopefully soon Windows phones. I'm not responsible for that; instead, I'm setting up the backend to allow users to send out a broadcast.
Another guy built the original backend, but I chose to rebuilt it from the bottom up to add in some additional functionality. Everything works in it, except the whole pushing of the broadcast part. Well, it sort of works; let me explain:
When a form is submitted, the data goes into the database via MYSQL and then with mysql_fetch_id() I get the new id and toss that id into a PHP function called sentBroadcast. It looks like the following:
function sentBroadcast($id){
$alertinfo = getAlertInfo($id);//this just gets all the data matching the id
$alert = mysql_fetch_assoc($alertinfo);
//these just get extra values
$organization = getOrganizationById($alert['broadcast_organization_id']);
$cityinfo = getCityInfo($organization['organization_city_id']);
$city = mysql_fetch_assoc($cityinfo);
// Create Airship object
$airship = new Airship(APP_KEY, APP_MASTER_SECRET);
$apiurl = "https://go.urbanairship.com/api/location/?q=".str_replace(" ","",strtolower($city['city_name']));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_USERPWD, APP_KEY.":".APP_MASTER_SECRET);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close ($ch);
$json = json_decode($output);
$locationid = "all";
if(count($json->features) > 0){
$locationid = $json->features[0]->id;
}
//send the message
$broadcasttype = "";
if($alert['broadcast_broadcasttypeother'] != ""){
$broadcasttype = $alert['broadcast_broadcasttypeother'];
}
else {
//this just gets data, nothing to see here
$broadcasttype = getCategoryInfo($alert['broadcast_broadcasttype_id'],'broadcasttype_name');
}
$message = html_entity_decode($broadcasttype)."\r\n".html_entity_decode($organization['organization_name'])."\r\n". html_entity_decode($alert['broadcast_subject']);
$blackberry_message = html_entity_decode($organization['organization_name'])."\r\n". html_entity_decode($alert['broadcast_subject']);
//calc as UTC
$timestamp = strtotime($alert['broadcast_sentdatetime']) + strtotime("+1 minute"); //add an hour
$offset = new DateTime(date("Y-m-d H:i:s T",$timestamp));
$offset->setTimezone(new DateTimeZone('UTC'));
$minutes_to_add = 10;
$time = new DateTime($alert['broadcast_sentdatetime']);
$time->add(new DateInterval('PT' . $minutes_to_add . 'S'));
$stamp = $time->format('Y-m-d H:i:s');
//echo $stamp;
$broadcast_message = array(
'schedule' => array("scheduled_time" => $stamp),
'push' => array("audience" => "all",
"notification" => array("alert" => $message),
"device_types" => array()
),
);
$device_types = array();
$device_types[] = "ios";
$device_types[] = "android";
$device_types[] = "blackberry";
$broadcast_message["push"]["device_types"] = $device_types;
if(in_array("ios", $device_types)){
$broadcast_message["push"]["notification"]["ios"] = array("sound" => "police.mp3", "extra" => array("id"=>$alert['broadcast_id']), "badge" => "+1");
}
if(in_array("android", $device_types)){
$broadcast_message["push"]["notification"]["android"] = array("extra"=>array("id"=>$alert['broadcast_id']));
}
if(in_array("blackberry", $device_types)){
$broadcast_message["push"]["notification"]["blackberry"] = array("content-type"=>"text/plain","body"=> json_encode(array("id"=>$alert['broadcast_id'], "body"=>$blackberry_message, "type"=>$broadcasttype)));
}
$data_string = json_encode($broadcast_message);
$apiurl = "https://go.urbanairship.com/api/schedules/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_USERPWD, APP_KEY.":".APP_MASTER_SECRET);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/json',
'Accept: application/vnd.urbanairship+json; version=3;',
'Content-Length: ' . strlen($data_string)
));
$json = curl_exec($ch);
$output = json_decode($json, true);
if(!is_array($output) || empty($output["ok"])){
echo "<h1>ERROR: (".(isset($output["error"]) ? $output["error"] : "An unknown error has occurred while trying to send your message.").")</h1>";
echo $data_string;
print_r($output);
$error = true;
}
curl_close ($ch);
$debug = false;
if($debug || $error){
if($error) echo "<!--";
var_dump($broadcast_message);
echo "<hr><br>";
echo $json."<hr><br>";
echo "<pre>";
print_r($output);
echo "</pre>";
if(!empty($output['ok'])){
//maybe we should save the status, or the json in the db.
echo 'yay it sent';
}
if($error) echo "-->";
}
if($error){
exit;
}
}//end sendBroadcast
When I do this query, I get hit by an error "Could not parse body request body". That wasn't very helpful, so I printed the response (look under "if(!is_array($output) || empty($output["ok"])){"). I get the following error message:
Array ( [ok] => [error] => Could not parse request body. [error_code] => 40700 [details] => Array ( [error] => Cannot schedule for the past 2013-10-12T06:46:00.000Z ) [operation_id] => 6fde4fa0-4b64-11e3-8903-90e2ba0253a0 )
The error I'm getting is "Cannot schedule for the past", however at the time of submitting this, it was the future. I began doing some research and read that I had to set it to UTC time. That being said, whatever my time is now, it will always be 6 hours into the past in UTC, so I have to convert it up to UTC.
So, I did that and the message went out and the phones received it and all went well. Except when we went to read the message: we then got an error that said the message was deleted.
We didn't delete it, so I think maybe (it hasn't been 6 hours yet) the users phone will get the new broadcast in the future, but they got informed of the alert now. That alert isn't visible yet, so it throws an error. At least that's what I think; it hasn't been 6 hours yet so I can't prove that.
My problem is this: How do I tell Urban Airship I want an immediate post to go out, without having to add 6 hours to the current time to make it in the "present", as well as actually having the phones get it at the correct time?
I contacted UA but they said to "expect a week delay in responding to you" (No rush, eh?) and I googled the error code (40700) and came up with nothing. I then emailed the guy who built the original and all he said was the "UTC was very important". Thank you for that.
If anybody can help me out I would be very thankful.
Thank you.
Oh, and if anybody is wondering, the json I'm submitting looks like the following:
{"schedule":{"scheduled_time":"2013-10-12 06:46:00"},"push":{"audience":"all","notification":{"alert":"Message\r\nKenton Industries\r\nKenton Test","ios":{"sound":"police.mp3","extra":{"id":"406"},"badge":"+1"},"android":{"extra":{"id":"406"}},"blackberry":{"content-type":"text\/plain","body":"{\"id\":\"406\",\"body\":\"Kenton Industries\\r\\nKenton Test\",\"type\":\"Message\"}"}},"device_types":["ios","android","blackberry"]}}
Thanks :)
I'm not sure I understand the second part of your question of, "having the phones get it at the correct time". In regards to the question of, "How do I tell Urban Airship I want an immediate post to go out, without having to add 6 hours to the current time to make it in the "present"":
If you want your users to receive the message as soon as possible then you shouldn't be scheduling your message. Via their curl examples an immediate push message curl request should look as thus:
curl -v -X POST -u "<AppKey>:<MasterSecret>" -H "Content-type: application/json" -H "Accept: application/vnd.urbanairship+json; version=3;" --data '{"audience" : "all", "device_types" : "all", "notification" : {"alert": "This is a broadcast"} }' https://go.urbanairship.com/api/push/
I am facing the problem with GCM push notification. I am getting the following error.
{
"multicast_id":4630467710672911593,
"success":0,
"failure":1,
"canonical_ids":0,
"results":[{
"error":"MismatchSenderId"
}]
}
Following is the code. Any help would be really appreciated. Thanks in Advance.
public function gcmPush()
{
$regId = "APA91bHFcgOssQZEqtdUk3EC1ojwC5-LVG3NPV2bMqKyC9rPymR6StmAbz-N7Ss8fnvruZhWWNrR3lmBqpjQItlu00AKHPbltBclUJF-EfC5qG4CF2xiuYYC0NCf8u5rbiYFk8ARhIT4lY2AEPWzGpl1OtTvQEC0gA";
$registatoin_ids = array($regId);
$message = array("msg" => 12345);
$this->send_notification($registatoin_ids, $message);
}
public function send_notification($registatoin_ids, $message)
{
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
define('GOOGLE_API_KEY', 'AIzaSyBavsIgQKo1Nf9wKZ5o_fGvE_6MI52LFR0');
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch)
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
"MismatchSenderId" is the obvious problem that we are getting nowadays.
Here are the possible cases that cause this problem.
Case 1: Mismatching Sender ID ->
Please check the Project number which you are using. If it's is correct or not.
Case 2: Wrong API Key ->
Please be sure that you are using the same API_Key or not. And in most of the cases, we need to generate Server_Key instead of Android_Key.
Case 3: Wrong Device's ID ->
Most of the time the problem is due to the wrong Device ID(Registration ID generated by GCM).
Please be ensure that that Whenever you generate new API key, the device id's of your device gets changed. Then it will take almost 5 five minutes to get an effect.
Note : Your device id is bound with the API KEY.
So....
--New Key created.
--GCM for Android Turned "on" in Google Dev. Console.
--Device registered with backend fine (Android Project is doing its job). Device key on the server.
--Send to device. Fail! The same message is returned from GCM everytime.
To Recap. This is NOT an Android Studio, Android OS, or Device issue. The GCM servers are not even trying to send the message to the device. My server sends to GCM, it returns the message...
{"multicast_id":6047824495557336291,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
to the server. As far as I can tell this means the Device's ID (the one returned to the device when it registered for a push, and the one saved on the backend (in the control panel) does not match, or is somehow not associated with the API Key used when sending the message.
Sending, of course, starts on my server, goes to GCM, then goes to the device.
This is what's not happening. The message goes from my server to GCM and back to my server - with the error.
Super frustrating as all of you can imagine - we've all been through this nightmarish stuff before :-)
Reference : https://www.buzztouch.com/forum/thread.php?tid=C3CED924C86828C2172E924
Hope it will solve your problem.