The GCM response is not correct, missing },{ - php

I am sending a GCM push message (less then 1000) with:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
$result_array = array();
while ($row = mysql_fetch_array($Regids)){
$result_array[] = $row['regid'];
}
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $serverApiKey
);
$data = array(
'registration_ids' => $result_array,
'data' => array(
'type' => 'New',
'title' => 'LH',
'msg' => ''.$msj.''
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
When I print the $result to check (and use for updating the database) it shows:
{"multicast_id":000,"success":274,"failure":75,"canonical_ids":13,"results":[{"message_id":"123"},{"message_id":"123"},{"error":"NotRegistered"},{"error":"NotRegistered"},{"message_id":"123"},{"message_id":"123"},{"registration_id":"456","message_id":"123"}]}
There is no },{ between every (canonical) registration_id and the next (success) message_id or error.
(I shortened the response to make it readable)
So my update part fails
$result = json_decode($result);
for ($i = 0; $i < count($result->{'results'}); $i++) {
if ($result->{'results'}[$i]->{'message_id'}) {
...
} elseif($result->{'results'}[$i]->{'error'}) {
...
} elseif ($result->{'results'}[$i]->{'registration_id'}) {
...
}
}
Does someone know what's wrong?

The format of the response you got is correct . A message for which you get a canonical registration id is still accepted by Google and is therefore successful , and that's why you get a message id in addition to the canonical registration id for that message . That's why there are no brackets after the canonical registration id.

Related

Shopify GraphQL Error "Parse error on \":\" (COLON) at [2, 35]" With PHP

Greetings I have a problem with my GraphQL I don't know how to pass data to my GraphQL without getting
Error Message: "Parse error on ":" (COLON) at [2, 35]"
here is what I'm trying to pass product variant id data and get some response here is the example of what I'm trying to do and my function for graphql
$variantId = (isset($data->variantId) && !empty($data->variantId)) ? strip_tags($data->variantId) : "";
if(empty($variantId)){
$result['error'] = "Product id not specified!";
}
$query = array("query" => '{
productVariant(id: '. ($variantId) .') {
availableForSale
}
}');
$variants = shopify_gql_call($_SESSION['access_token'], $_SESSION['shop_name'], $query);
if( isset($variants['response']) && !empty($variants['response']) ){
$result[] = $variants['response'];
}else{
$result['error'] = "Variants not found!";
}
function shopify_gql_call($token, $shop, $query = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . "/admin/api/".getenv('API_DATE')."/graphql.json";
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
// Setup headers
$request_headers[] = "";
$request_headers[] = "Content-Type: application/json";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($curl, CURLOPT_POST, true);
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part, 2);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
I strongly suggest the use of https://packagist.org/packages/shopify/shopify-api instead of implementing your own function/http requests.
Your query should be something like this
query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}
and then you submit the ID as part of another entry of the array, check the example below:
$query = [
"query" =>
'query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}',
"variables" => [
'id' => $variantId
]
];
You should never concatenate the values as part of the query string (unless you want to deal with a lot of injection issues). Check more info about variables here https://graphql.org/learn/queries/

Incorrect player_id format in (not a valid UUID)

I'm trying to add an array of players_id to send to push notification to specific mobiles, but I keep getting the error "Incorrect player_id format in include_player_ids (not a valid UUID)"
if ($cons) {
$dado1 = array();
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado1 = array(
$row['funcionarioId']
);
array_push($dado2, $dado1);
}
//echo json_encode($dado2);
} else {
$dado2 = array();
array_push($dado2, $dado1);
$retornoVazio = array("Retorno" => $dado2);
EnviaEmailComErro($sql, sqlsrv_errors(), "Consulta_NFCe - ConsultaDados");
array_push($dado2, array("Success" => "0", "Error" => "1"));
echo json_encode($retornoVazio);
}
function sendMessage($produto, $mesa, $comanda, $garcom, $dado2)
{
$content = array(
"en" => " Garçom $garcom \n o pedido: $produto está pronto!\n mesa: $mesa \n comanda: $comanda",
);
**That where it should add the IDS**
$fields = array(
'app_id' => "***",
'include_player_ids' => array($dado2),
'channel_for_external_user_ids' => 'push',
'data' => array("foo" => "bar"),
'contents' => $content
);
$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 ***'));
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);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($produto, $mesa, $comanda, $garcom, $dado2);
$return["allresponses"] = $response;
$return = json_encode($return);
the variable $fields print
{"app_id":"***",
"include_player_ids":[
[
["2610ec53-"],
["045eac07-"],
["8fb19bd9-"]
]
]"
And $response:
{"errors":["Incorrect player_id format in include_player_ids (not a valid UUID): [[\"2610ec53-\"], [\"045eac07-\"], [\"8fb19bd9-\"]]"]}
"The players ID are complete in the code, but I deleted it."
In the if ($cons) { you are pushing all sorts of stuff into arrays, simplify it to
if ($cons) {
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado2[] = $row['funcionarioId'];
}
} else {
And in the function make this change
'include_player_ids' => $dado2,

pushcrew - send notification with PHP curl

This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)

InvalidRegistration on sending push to muliple devices

I'm trying to send push notifications to multiple device using Google Firebase and I always received the error : "InvalidRegistration".
This is the tokens that I sent in the "to"
:json_encode($tokensPerEvent):
["eV9g4oTwjZs:APA91bF3YLGtDkCDekvR6eahbVAn-jIY0sVGjxMWyBEyR-
3AB9q6RBhw4fyeqE4ZkZxQs0TsYhUee9Txy_exAGxtrBPV_-
sjKlWcV3z3nDYXOcVSVwlpPyGzUJKxGMU16drMR41bLI4t"]
and this is the response :
{
"multicast_id":***,
"success":0,
"failure":1,
"canonical_ids":0,
"results":[
{
"error":"InvalidRegistration"
}
]
}
another questions: if the one of the tokens not exist anymore, this is effect on all the other tokens , or just the only old one will effected ?
This is my code:
<?php
require_once '../CommonFunctions.php';
ignore_user_abort();
ob_start();
$url = 'https://fcm.googleapis.com/fcm/send';
//GET TOKENS FROM DB
$db = new Database();
$db->query("SELECT push_token FROM User");
$db1 = new Database();
$db1->query("SELECT phone FROM invite_list where event_id = 137");
$response = $db->resultset();
$response1 = $db1->resultset();
$arr2 = array_column($response1, 'phone');
$phones = join("','",$arr2);
$db2 = new Database();
$db2->query("SELECT push_token FROM User WHERE phone IN ('$phones')");
$tokensPerEvent = array();
$tokensrr = $db2->resultset();
$tokensPerEvent = array_column($tokensrr, 'push_token');
echo json_encode($tokensPerEvent);
$fields = array('to' => json_encode($tokensPerEvent),
'notification' => array('body' => 'HI', 'title' => ':)'));
define('GOOGLE_API_KEY', '***********');
$headers = array(
'Authorization:key='.GOOGLE_API_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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
?>
If you want to send push notification to many clients by theirs registration ids, you have to use registration_ids instead of to field. You can find this in docs (second parameter).
You are also encoding tokens two times:
$fields = array('to' => json_encode($tokensPerEvent), ...
and
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
Try by skipping encoding $tokensPerEvent in array:
$fields = array('to' => $tokensPerEvent, ...

Fetch gmail contacts using google API, showing error account disabled

I am using PHP. I want to fetch all gmail contacts of a user, i am using a PHP code that is calling google API through CURL. But, when i am doing this on localhost, it is doing well and giving me all contacts.
But when i am doing this on online server that server in US, it is giving me response "Account Disabled" and also receiving a security mail by same user from google.
i am using below code :
function getGmailContacts($user, $password) {
//========================================== step 1: login ===========================================================
$login_url = "https://www.google.com/accounts/ClientLogin";
$fields = array(
'Email' => $user,
'Passwd' => $password,
'service' => 'cp', // <== contact list service code
'source' => 'test-google-contact-grabber',
'accountType' => 'GOOGLE',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$login_url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,$fields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
$returns = array();
foreach (explode("\n",$result) as $line)
{
$line = trim($line);
if (!$line) continue;
list($k,$v) = explode("=",$line,2);
$returns[$k] = $v;
}
curl_close($curl);
//echo "<pre>";
//print_r($returns);exit;
if(!isset($returns['Error'])) {
//========================== step 2: grab the contact list ===========================================================
$feed_url = "http://www.google.com/m8/feeds/contacts/$user/full?alt=json&max-results=250";
$header = array(
'Authorization: GoogleLogin auth=' . $returns['Auth'],
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $feed_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$data = json_decode($result, true);
//echo "<pre>";
//print_r($data);exit;
$contacts = array();
$i=0;
foreach ($data['feed']['entry'] as $entry)
{
//echo $i." ";
$entryElement = $entry;
if(isset($entryElement['gd$email'])) {
$gdEmailData = $entryElement['gd$email'][0];
//$contact->title = $entryElement['title']['$t'];
//$contact->email = $gdEmailData['address'];
$contacts[$gdEmailData['address']] = $entryElement['title']['$t'];
}
}
//var_dump($contacts);
//print_r($contacts);
return $contacts;
}
else {
if($returns['Error']=='BadAuthentication') {
//echo '<strong>User Name and Password is incorrect.</strong>';
$errorArr = array("Error"=>"User Name and Password is incorrect.");
//print_r($errorArr);
return $errorArr;
}
}
}
That mail contains that
"Someone recently tried to use an application to sign in to your
Google Account....Location: New York NY, New York, United States....."
.
I thing this error is occurring from location change.
can any one help me please? Thanks in advance.

Categories