GCM sending with curl (php) - php

I'm trying to send a message to an Android phone but keep getting response code 401 with text: Unauthorized. Also I keep reading different stories on what key to use, I know of 3 keys: the project ID (number), the Key for server apps and the Key for browser apps. So I have tryed them all 3, all with the same result.
My code:
$headers = array("Content-Type" => "application/json", "Authorization" => "key=" . "mykey");
$data = array(
'data' => $messageText,
'registration_ids' => array($deviceRegistrationId)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
error_log(json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
error_log($response);

I changed the header to:
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . "mykey");
And it works. The mykey is Key for browser apps.

You could do your headers like this just to make it a little easier to read and eliminate the concatenation:
$headers = array(
"Authorization:key=mykey",
"Content-Type:application/json",
);

Related

Having troubles for using CURL and API using PHP

Good day family !
Please help me using this API.
This API is user to get a token see the normal answer :
{'status': True, 'message': 'Success', 'code': 50, 'data': {'token': '773b718a53341b57zd511dazd4588fdf2', 'amount': 45.0}}
When i use Python it's working fine ! here is the python working code :
import requests
import json
headers = {"Authorization": "Token 12345678900987654321234567890", "Content-Type":"application/json"}
data = {"vendor": 1265,
"amount": 45,
"note" : "Commande #1324"
}
r = requests.post("https://sandbox.paymee.tn/api/v1/payments/create", data=json.dumps(data), headers=headers)
response = r.json()
# Now you can use
print(response)
But when i use PHP i have as output : NULL
Here is the code
<?php
$headers = array("Authorization: Token 12345678900987654321234567890");
$curl_post_data = array(
'vendor' => 1265,
'amount' => 45,
'note' => "Commande #1324"
);
$curl_handle=curl_init('https://sandbox.paymee.tn/api/v1/payments/create');
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_POST, true);
curl_se
topt($curl_handle, CURLOPT_POSTFIELDS, $curl_post_data);
$query = json_decode(curl_exec($curl_handle),true);
var_dump($query);
curl_close($curl_handle);
?>
Do you have any solution please ? i spent one week stuking there ! and my exam is close... :(
Thanks in advance
$result = curl_exec($curl_handle);
$query = json_decode($result,true);
<?php
$headers = array(
"Authorization: Token 12345678900987654321234567890",
"Content-Type: application/json"
);
$data = array(
"vendor" => 1265,
"amount" => 45,
"note" => "Commande #1324"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://sandbox.paymee.tn/api/v1/payments/create");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
print_r($response);
?>
This gives me the response that I'm using a invalid token which seems about right since you gave a sample token.

Calling Watson API from PHP code

I am trying to call Natural Language Understanding Watson API from my PHP code using curl. I have successfully tried curl from terminal. It gives some result on executing this command:
curl -u "my_username":"my_password" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream.&features=sentiment,keywords"
However when I try to use curl in php using this code:
<?php
$url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream%2C%20a%20dream%20deeply%20rooted%20in%20the%20American%20dream%20%E2%80%93%20one%20day%20this%20nation%20will%20rise%20up%20and%20live%20up%20to%20its%20creed%2C%20%22We%20hold%20these%20truths%20to%20be%20self%20evident%3A%20that%20all%20men%20are%20created%20equal.&features=sentiment,keywords";
$post_args = array(
'version' => '2017-02-27',
'url' => 'https://davidwalsh.name/curl-post',
'features' => 'sentiment,keywords'
);
$headers = array(
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "my_username:my_password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
?>
I get this result:
{
"error": "unsupported media type",
"code": 415
}
What should be done?
I can't believe I was stuck here due to a blank space.
Replacing this:
$headers = array(
'Content-Type:application/json'
);
with
$headers = array(
'Content-Type: application/json'
);
worked. Note the blank space between : and application/json.

Curl POST attachment

I need to attach a pdf file form local drive and post it to the API using PHP CURL.
Here is the RingCentral FaxOut API Documentation
$url = "https://service.ringcentral.com/faxapi.asp";
$data = array(
'Username' => 'XXXXXXXXX',
'Password' => 'XXXXXXXXX',
'Recipient' => 'XXXXXXXXXX|Navneet',
'Coverpage' => 'Default',
'Coverpagetext' => 'Testing Faxout API ',
'Resolution' => 'High',
"Sendtime" => date('d:m:y H:i:s'),
'Attachment' => file_get_contents(PATH_TO_FILE)
);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
API do not return anything in response. I think, I'm not sending the attachment properly. The attachment should be in binary stream. I tried base64_encode but no success.
As given in the Request body example, header for attachment should be like this
Content-Disposition: form-data; name="Attachment"; filename="C:\example.doc"
<Document content is here>
-----------------------------7d54b1fee05aa
You can POST anything to the api with CURL, $doc in my example is anything you want to post , it can be a json_encoded file , a base64_encoded image or pdf or anything else.
$baseUri = https://service.ringcentral.com/faxapi.asp;
$doc = file_get_contents(PATH_TO_FILE);
$ci = curl_init();
curl_setopt($ci, CURLOPT_URL, $baseUri);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ci, CURLOPT_FORBID_REUSE, 0);
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ci, CURLOPT_POSTFIELDS, $doc);
// also you can specify any specific header like this :
$h1['Content-Disposition'] = 'Content-Disposition'. ': ' . 'form-data'; // headers are key-value pairs right ?
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h1)); // you can use this line for each header as a new key-value pair
$h2['name'] = 'name'. ': ' . 'Attachment';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h2));
$h3['filename'] = 'filename'. ': ' . 'C:\example.doc';
curl_setopt($ci, CURLOPT_HTTPHEADER, array_values($h3));
$response = curl_exec($ci);
**NOTE ** : its a good Idea to first of all check to see if your file_get_contents function works :
so in another php file check to see this :
echo file_get_contents(PATH_TO_FILE);
See if it echoes correctly
This is the function and how I generated the info for the request
function send_curl_request_with_attachment($method, $headers, $url, $post_fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
if($headers != "" && count($headers) > 0){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
} curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec($ch);
curl_close($ch);
return $result;}
$token_slams = "Authorization: Bearer " . $access_token;
$authHeader = array(
$token_slams,
'Accept: application/form-data');
$schedule_path ='../../documents/' . $docs_record["document"];
$cFile = curl_file_create($schedule_path);
$post = array(
'old_record' => $old_record,
'employer_number' => $employer_number,
'payment_date' => $payment_date,
'fund_year' => $fund_year,
'fund_month' => $fund_month,
'employer_schedule'=> $cFile
);
send_curl_request_with_attachment("POST", $authHeader, $my_url, $post);

Website inducing alert on mobile phone

I am building a php webpage to be browsed on computers, which is having some email sending and calendar functions.
I would like to try, when sending email messages or creating calendar events from computer browsers, will it be possible to trigger alerts, such as sounds and vibrations in iPhone and Androld systems?
If not, then I may have to do some apps. Thanks!
I would do something like this for android phones:
function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText, $infoType, $messageInfo) {
$headers = array('Authorization: GoogleLogin auth=' . $authCode);
$data = array(
'registration_id' => $deviceRegistrationId,
'collapse_key' => $msgType,
'data.message' => $messageText,
'data.type' => $infoType,
'data.data' => $messageInfo
);
$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);
return $response;
}

Not being able to authenticate Google Visualization Query Language with given Authentication Key

Not being able to authenticate Google Spreadsheet API.
I'm using this code stolen from here,
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "MY_EMAIL#GOOGLE.COM",
"Passwd" => "MY_EMAIL_PASS",
"service" => "writely",
"source" => "MY_APPLICATION_NAME"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute
$response = curl_exec($curl);
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: " . $auth; //this worked!
So this works and now I have a key But actually using it...with the bellow code gives me a user not authenticated error:
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
$key = 'MY_KEY';
// Make the request
curl_setopt($curl, CURLOPT_URL, 'https://spreadsheets.google.com/tq?tqx=version:0.6;out:json&key='.$key);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
$response = curl_exec($curl);
curl_close($curl);
var_dump ($response);
this gives me
string(272) "google.visualization.Query.setResponse({version:'0.6',status:'error',errors:[{reason:'user_not_authenticated',message:'User not signed in',detailed_message:'\u003ca target=\u0022_blank\u0022 href=\u0022http://spreadsheets.google.com/\u0022\u003eSign in\u003c/a\u003e'}]});"
So apparently it is not able to use the authentication key for the Google Visualization Query Language.. what am I doing wrong?
Thank you so much!
I would try the following modifications in the code that uses google authentication string:
add urlencode
$headers = array(
"Authorization: GoogleLogin auth=" . urlencode($auth),
"GData-Version: 3.0",
);
and skip verifying SSL sertificates:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
I've described my experience implementing authentication with CURL in this post. There you'll find some tips on debugging CURL requests.

Categories