Firebase Cloud Messaging: Add a device to a topic using curl command - php

For now I can send a notification to a single device using the curl command:
curl --header "Authorization: key=AAAxxxxxE4:xxxxxxxuXog" --header Content-Type:"application/json; application/x-www-form-urlencoded;charset=UTF-8" -d '{"to":"DeviceToken","notification":{"title":"Test","body":"Test Message","icon":"icon-192x192.png"}}' https://fcm.googleapis.com/fcm/send
This works great. Now I try to scale the number of recipients by using the topic functionality.
I tried to add a device to the topic "svp" by using the curl command:
curl --header "Authorization: key=AAAxxxxxE4:xxxxxxxuXog" --header Content-Type:"application/json" https://iid.googleapis.com/iid/v1/DeviceToken/topics/svp
Here I get the error message:
{"error":"InvalidToken"}
But I'm sure, both, the Authorization key and the token are correct. (I still can send notifications with it).
Can anybody help me to find the solution for my problem?

I think you missed the rel in your cURL request, between the token and the topic name. As seen in the Instance ID docs, the format should be:
https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME

For some reason, https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME did not work for me. It seemed to me that I was doing everything correctly but what I decided to do was to try the equivalent of that by using https://iid.googleapis.com/iid/v1:batchAdd and sending only one token:
$curlUrl = "https://iid.googleapis.com/iid/v1:batchAdd";
$mypush = array("to"=>"/topics/toronto", "registration_tokens"=>array("acwAw4F8b0W:AMA91bEAKsN1aGjMm5xsobxBHxbYZLfioTPMEIN90njdiK5C2MnOYF4NcOy6ot6BFanMTBIoKRGcyev2RJuydGWt1XHwsniNZ6h8Pjvn9Fqth-Mqgj_5-YN9pt_nMAtgG8blc5bodWyA"));
$myjson = json_encode($mypush);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, True);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myjson);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization:key=[My authorization key]'));
//getting response from server
$response = curl_exec($ch);
I could add the token to the topic successfully. What was returned was this:
{"results":[{}]}
But then I went to confirm to the topics by using https://iid.googleapis.com/iid/info/IID_TOKEN that the token had been successfully added to the topic the way I wanted it and yes, everything worked correctly for me using https://iid.googleapis.com/iid/info/IID_TOKEN. So if you are having problems with https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME, you can simply use https://iid.googleapis.com/iid/v1:batchAdd the way I did it.

Related

PHP cURL POST Jenkins job with parameters

Triggering Jenkins job via following PHP script:
<?php
$testrun_id = "1744";
$cmd = "curl -X POST http://build:f9280f75396f83a0#mobile-jenkins.domain.com:8080/job/android-test/build --data-urlencode json='{\"parameter\": [{\"name\":\"POST_RESULTS\", \"value\":\"true\"}, {\"name\":\"RUN_ID\", \"value\":\"{$testrun_id}\"}, {\"name\":\"CHECK_NAME\", \"value\":\"SampleAutomatedPlan\"}]}'";
exec($cmd,$result);
?>
This script runs successfully on Mac and the jenkins job does get triggered. How do I make this script to work on Windows? I am getting following error when I run above PHP script on Windows?
curl is already installed on windows machine. Also, is there a better way to do cURL in PHP? Looking at this: http://php.net/manual/en/book.curl.php, can someone point me towards an example based on my curl command in the above PHP script(for Windows)? An example based on the curl command in my script would be ideal.
you should check examples from here http://php.net/manual/en/curl.examples.php
Bellow is the code for you case,
$url = "http://build:f9280f75396f83a0#mobile-jenkins.domain.com:8080/job/android-test/buildWithParameters";
$data = "POST_RESULTS=true&RUN_ID=".$testrun_id."&CHECK_NAME=SampleAutomatedPlan";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
You need to set the content type for JSON
curl -H "Content-Type: application/json" -X POST http://build:f9280f75396f83a0#mobile-jenkins.domain.com:8080/job/android-test/build --data-urlencode json='{\"parameter\": [{\"name\":\"POST_RESULTS\", \"value\":\"true\"}, {\"name\":\"RUN_ID\", \"value\":\"{$testrun_id}\"}, {\"name\":\"CHECK_NAME\", \"value\":\"SampleAutomatedPlan\"}]}'";
Just make sure you don't have any mix matched values.

I need help converting a successful request from Postman into CURL commands using PHP (involves HTTPS and POST)

The endpoint I'm trying to reach requires HTTPS and Basic Authentication. My team was given an API key, and the documentation states to use the key as the username, and to leave the password blank.
Here is the example CURL request from the documentation:
curl -i -k -u '<api_key>': -XPOST --data-urlencode data#/path/to/test/file.json "https://<your_subdomain>.vendor.org/api/v1/assessments/import"; echo ""
When I execute the following using the Postman extension for Chrome, I get a successful response from the server:
I'm trying to execute this locally using PHP (XAMPP install). The following is getting a response from the server saying the username/password is incorrect:
function curlPost($url, $headers, $username, $password, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CAINFO, 'certificate.pem');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
print_r(curl_exec($ch));
// print_r(curl_getinfo($ch));
// print_r(curl_error($ch));
curl_close($ch);
}
$data = '{"key":"value", "key":"value"}';
curlPost('https://domain.com/api/data', ['Content-Type: application/xml'], 'api_key', '', $data);
{"success":false,"errors":["Email\/Username or password incorrect. Please try again."],"warnings":[],"info":[],"meta":[],"results":[]}
The JSON string used in $data was copied and pasted from a successful Postman request.
The certificate.pem is in the same folder as the script, and read/write permissions have been given to everyone. I have tried exporting the specific certificate for our vendor's site from my machine as well as the CA bundle linked in the top response to this post. I was able to use it to successfully hit the vendor's api-key-test endpoint via PHP/CURL.
I'm pretty new to this. Would you mind helping me wrap my head around what I'm missing? While I've copied and pasted a ton, the function is largely my own. The parameter for headers will be used for other things.
Basic Authentication with the HTTP Authorization header uses the Base64 encoded value of "username:password" (without the double quotes)
So I'm assuming in your case you would need to Base64 encode "yourApiKeyValue:" and put that in a Authorization header in your cURL command
MDN reference - HTTP Authentication
Edit: This may also be helpful
How do I make a request using http basic authentication-with-php-curl

Read response from server which downloads as a file

I am trying to read the response (json text) from server. But the server returns the response as a file which gets downloaded in my downloads directory.
url:-https://www.googleapis.com/freebase/v1/mqlread?query=%5B%7B%22id%22%3Anull%2C%22name%22%3Anull%2C%22type%22%3A%22%5C%2Fastronomy%5C%2Fplanet%22%7D%5D
I am using curl in my php code.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Connection: Keep-Alive'
));
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
How can I read the data using php curl?
UPDATE: When I try to run the same code in online editors like http://phpassist.com/ then it reads the data and shows me the required output.
So is there any additional configuration I need to make in XAMPP??
Tks
You need disable ssl certification or get ssl certification, the fastest way is:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Twitter oauth with SSL using cURL in PHP

I'm a bit of a beginner to this. But I am trying to use cURL to perform a GET request to pull back users tweets.
I've been able to authenticate OK. But I cannot work out how to GET the data. I'm working from my localhost.
I've tried adding a basic certificate but it does not work.
Do I have to buy an SSL certificate for my site? I've seen twitter feeds on other sites that haven't purchased SSL certificates so I don't know how they do it?
I've seen this in the Twitter documentation. The file that is mentioned, is that the one I can purchase?
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, True);
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($connection, CURLOPT_CAINFO, "path:/ca-bundle.crt");
This is my cURL code, it worked before I put the CURLOPT_URL section in and got a positive response from the server:
$url = "https://api.twitter.com/oauth2/token";
$headers = array(
"POST /oauth2/token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: my Twitter App v.1",
"Authorization: Basic ".$encoded."",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8"
);
$ch = curl_init();
curl_setopt ($ch, CURLOPT_CAINFO, "cacert.pem");
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/".$username.".json?count=".$num_tweets);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$header = curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
Edit: there are problems with the code above, I'm aware I'm doing something wrong but not sure what. Anyway, here is the original code I had which did work OK and got the expected result back from the server. So the next step is to request the user's tweets from their timeline.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$header = curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
You may use curl_getinfo to know what's going on.
You may also post the url of the Twitter documentation so we can have a look.
$headers indicates a host as api.twitter.com but CURLOPT_URL uses twitter.com, is this a typo ?
Your code is schizophrenic:
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/".$username.".json?count=".$num_tweets);
You're setting the URL twice, to different URLs. Only the LAST url set will have any effect, so you're not posting to the API, you're posting to something else on the main twitter site.
And no, you don't need an SSL cert on your own machine to do any of this. The ca-cert.pem is a list of cert issuer's public certs, which will be used to validate/authenticate Twitter's own certificate. It's basically the same thing built into your browser(s) that allow them to validate any other SSL cert out there. e.g. you don't have to buy a personal SSL cert to go shopping on amazon.com, you just need the CA certs in your browsers to authenticate amazon's servers.

REST-ful connection utilizing cURL header issues

I've spent hours troubleshooting this utilizing PHP documentation, the API documentation, as well as other posts on stackoverflow, and am finally asking for help.
I am attempting to write an interface utilizing the new pbSmartConnections API: API Documentation
I have been having challenges with both fsockopen and cURL, however I seem to be able to get farther in the process utilizing cURL, so that's what I'm presenting here. Here's the challenge:
Per my understanding of the documentation, I should be passing the ApiKey as part of the header. When I do this, regardless of the different ways I've attempted to structure the code, I ALWAYS receive the following response:
{
"ErrorCode": 10,
"Message": "Unauthorized"
}
I'm hoping a fellow SO member can see something in my code below (please offer any criticisms and/or suggestions, too!):
(NOTE: The API key below IS valid. It's connected to an account with nothing of value in it, so feel free to use it in your testing)
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://rest.pbsyscontrol.com/v1/Ping");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type"=>"application/json", "Accept"=>"application/json", "ApiKey"=>"41460b3f-8f35-4878-b78d-49ca7f29c071"));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
?>
In case you are wondering, while I would like this to work as part of the header, I HAVE tried passing it as a part of the URL as well:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://rest.pbsyscontrol.com/v1/Ping?ApiKey=41460b3f-8f35-4878-b78d-49ca7f29c071");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type"=>"application/json", "Accept"=>"application/json", "ApiKey"=>"41460b3f-8f35-4878-b78d-49ca7f29c071"));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
?>
The PHP documentation says:
An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
You thus want to use the following line instead of the original:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Accept: application/json", "ApiKey: 41460b3f-8f35-4878-b78d-49ca7f29c071"));
This does not however, solve the problem that the ApiKey probably isn't valid.
I finally heard back from support, and what they indicated was that I was using the incorrect url (although at this time, it IS the url in their API Documentation)
The URL in the API documentation was their STAGING, not PRODUCTION. Amazing what switching the URL to the correct one that they sent in their reply - rest.api.pbsmartconnections.com does for the connection. That one change and everything began working properly.
THANK YOU all who took a look, and to #mvdnes for the recommendations on how to set headers.

Categories