Push Notification in android c2dm - php

I'am developing a sample push notification app in android using c2dm. Here is my PHP code to send the message from server to device.
function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) {
$headers = array('Authorization: GoogleLogin auth=' . $authCode);
$data = array(
'registration_id' => $deviceRegistrationId,
'collapse_key' => $msgType,
'data.message' => $messageText //TODO Add more params with just simple data instead
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
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, $data);
$response = curl_exec($ch);
curl_close($ch);
}
sendMessageToPhone("my application server auth token ","my device id","UTF-8","hello");
But i'am getting "No info." notification on my emulator. Where i'am going wrong ? Please help me.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: GoogleLogin auth=$token", "Content-Length: $len", "Content-Type: application/x-www-form-urlencoded"));
echo curl_exec($ch);
curl_close($ch);
This is the php code that my app uses to send C2DM messages where $data is your data array. Please note that the Content-Length is necessary and is is the length of your data.
EDIT: Something you may also find useful a class for php that makes sending messages a little nicer.

Related

PHP CURL - Apple push notification servers

I am writing code to send notifications to the Apple push notification servers (APNs) using PHP Laravel. It says in the documents that it requires HTTP/ HPACK header compression.
I've tried using cURL
$cURLConnection = curl_init();
if(strcmp(env('APP_ENV'), 'production') == 0) {
curl_setopt($cURLConnection, CURLOPT_URL, 'api.push.apple.com:443');
} else {
curl_setopt($cURLConnection, CURLOPT_URL, 'api.development.push.apple.com:443');
}
curl_setopt_array($cURLConnection, [
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_HTTP_VERSION =>CURL_HTTP_VERSION_2_0,
]);
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array(
'path: /3/device/<devicetoken>',
'authorization: bearer ' . $token,
'Content-Type: application/json'
));
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $postRequest);
curl_setopt ($cURLConnection, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
$apiResponse = curl_exec($cURLConnection);
but the APNS server always returning 'Empty reply from server'
I see a few things that could be problematic.
Try adding the following to actually turn your request into a POST request.
curl_setopt($c, CURLOPT_POST, 1);
Your 'path' should also be part of the main URL instead of being added as a header.
curl_setopt($c, CURLOPT_URL, "https://api.push.apple.com:443/3/device/<devicetoken>");
In addition to the previous suggestion, we should also be able to use certificate bases auth system.
Example snippet below:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://path-to-auth-example.com/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_cert");
curl_setopt($ch, CURLOPT_SSLCERT, "path/to/your/pem-file.pem");
curl_setopt($ch, CURLOPT_SSLCERTTYPE, "PEM");
$headers = [];
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
//catch your error wisely
}
curl_close($ch);
$result = json_decode($result);
print_r($result);
?>

PHP cURL how to send a JSON POST request and also include a URL querystring?

I'm trying to submit a POST request with JSON data to an api endpoint. The endpoint requires a querystring passing the api credentials, but also requires the JSON data to be POSTed.
When I try to do this with PHP cURL as shown below, the querystring is apparently removed - thus the api is rejecting the request due to missing api key.
I can do this easily with Postman when testing access to the api endpoint.
How can I make the cURL request include both the querystring AND the JSON POST body?
Example code:
// $data is previously defined as an array of parameters and values.
$url = "https://api.endpoint.url?api_key=1234567890";
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
You are doing almost right.
Sometimes you need to relax SSL verification.
Otherwise, update php ca bundle:
https://docs.bolt.cm/3.7/howto/curl-ca-certificates
Add the following:
$headers = array(
"Content-type: application/json;charset=UTF-8",
"Accept-Encoding: gzip,deflate",
"Content-length: ".strlen($json),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_ENCODING, "identity, deflate, gzip");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Sometimes you need to change encoding too:
$result = utf8_decode($result);
And check the returning data.

Zoho API V2 Update Record

I am trying to use the Zoho API Version 2 to do a simple record update in Leads. I am using PHP and CURL and my sample code for this call (to update a single field in the record) is as follows:-
$apiUrl = "https://www.zohoapis.com/crm/v2/Leads/" . {valid record id here};
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', {valid auth token here})
);
$fields = json_encode([["data" => ["City" => "Egham"]]]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
curl_close($ch);
No matter how I format the JSON, I always get the following returned:
{"code":"INVALID_DATA","details": {"expected_data_type":"jsonobject"},"message":"body","status":"error"}
It is not a matter of invalid auth tokens etc because I have successfully used PHP and CURL with the Zoho API to read data and I decode the JSON returned successfully.
Please could somebody help with passing valid JSON data?
The above code constructs input JSON like this
[{"data":{"City":"Egham"}}]. This JSON is not valid as per the ZOHO CRM APIs(API help).
It should be like this {"data":[{"City":"Egham"}]}.
Change the code like this :
$apiUrl = "https://www.zohoapis.com/crm/v2/Leads/" . {valid record id here};
$fields = json_encode(array("data" => array(["City" => "Egham"])));
// *strlen must be called after defining the variable. So moved headers down to $fields*
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', {valid auth token here})
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
curl_close($ch);
You must escape the data into JSON format:
import json
response = requests.post(url, data=json.dumps(data), headers=headers)

Force curl to use preemptive authentication with basic authentication

I'm building a request with PHP using curl, for the basic authentication it is necessary to use the preemptive authentication.
Can I force curl to use the preemptive authentication?
Or is there any other way to build my request with PHP?
#Bas van Stein
I'm not sure if I understand this correctly. I tried it like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// auth header
$headers = array(
sprintf('Authorization: Basic %s',base64_encode(sprintf("%s:%s",$username,$password))),
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
// preemptive authentication (first request)
$result = curl_exec($ch);
// extend header for payload
$boundary = $this->generateRandomString();
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge_values($headers,array(
'Content-Encoding: gzip',
'Content-Type: multipart/mixed;boundary=' . $boundary,
)));
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$multiPart = sprintf("--%s\r\nContent-Disposition: content\r\nContent-Type: application/xx.xx\r\nContent-Version: 1.5\r\n\r\n%s\r\n--%s--",$boundary,$data,$boundary);
curl_setopt($ch, CURLOPT_POSTFIELDS, gzencode($multiPart));
// request with payload (second request)
$result = curl_exec($ch);
curl_close($ch);
but it doesn't worked.
Thanks
katzu

CURL - get Retrieve all email from Google API

I'm using cURL to get all email from user via Google API. Following https://developers.google.com/admin-sdk/email-audit/#retrieving_all_email_monitors_of_a_source_user.
According this tutorial, the server return '201 Created' status code to successful. But, my result return '200 OK' code.
Here is code Authorization
$data = array(
'accountType' => 'HOSTED_OR_GOOGLE',
'Email' => 'myEmail',
'Passwd' => 'myPassword',
'source'=>'PHP-cUrl-Example',
'service'=>'apps');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
And here is code to Retrieving all email monitors of a source user
preg_match("/Auth=([a-z0-9_-]+)/i", $response, $matches);
$auth = $matches[1];
$header = array('Content-Type: application/atom+xml; charset=utf-8',
'Authorization: GoogleLogin auth='.trim($auth),
);
$url_email ="https://apps-apis.google.com/a/feeds/compliance/audit/mail/monitor/mydomain/username";
curl_setopt($ch, CURLOPT_URL, $url_email);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$response = simplexml_load_string($response);
curl_close($ch);
print_r($response);
Help me pls ?
The API allows you to request the status of a single export request with a URL of:
https://apps-apis.google.com/a/feeds/compliance/audit/mail/export/{domain name}/{source user name}/{mailbox requestId}
or of all requests across the domain with a request of:
https://apps-apis.google.com/a/feeds/compliance/audit/mail/export/{domain name}?fromDate={fromDate}
there is no operation to retrieve the status of all requests for a given user like you are trying to do.
I suggest you confirm you've successfully created an audit request by using GAM to create the request. GAM will show you the request ID on success. Then you can try getting the results of the single request with your code.

Categories