good evening,
I'm already breaking my head for 3 days I'm trying to send a message with the button from a page with a bot made in CURL PHP
I'm trying with CURL and PHP POST GRAPH
without success both of us can help me?
function SendRawResponse($Rawresponse){
$userPageConversation = 't_100005050355547';
$Access_token = "XXXX";
$url = "https://graph.facebook.com/v2.6/".$userPageConversation."/messages?access_token=".$Access_token;
//$url = "https://graph.facebook.com/v2.6/me/messages?access_token=".$Access_token;
$ch = curl_init($url);
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'charset=utf-8',
);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $Rawresponse);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Rawresponse));
//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse));
curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
$erros = curl_errno($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($erros);
var_dump($response);
curl_close($ch);
}
Mensage:
$teste = '{
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Try the postback button!",
"buttons":[
{
"type":"web_url",
"title":"GOOGLE",
"url":"https://www.google.com.br"
}
]
}
}
}}';
SendRawResponse($teste);
erros:
Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse)); = Missing message body
According to the docs
you must add domain to the whitelist in FB page settings.
Domains must meet the following requirements to be whitelisted:
Served over HTTPS
Use a fully qualified domain name, such as
https://www.messenger.com/. IP addresses and localhost are not
supported for whitelisting.
Related
I have the same problem as here How to get results from Udemy Api with search? which unfortunately doesn't have an answer.
I'm able to retrieved the title etc, from this URL for example, https://www.udemy.com/api-2.0/courses/238934/?fields[course]=#all (you'll see the results in your browser) this URL works as well https://www.udemy.com/api-2.0/search-suggestions?q=java but not this one https://www.udemy.com/api-2.0/courses/?search=java
As mentioned here https://www.udemy.com/developers/affiliate/methods/get-courses-list/
get /api-2.0/courses/?search=java should work?
Here is my code:
$url = "https://www.udemy.com/api-2.0/courses/?search=java";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$c_id = base64_encode('XXX');
$c_sid = base64_encode('XXX');
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: '.$c_id.'','X-Udemy-Client-Secret: '.$c_sid.'',"Authorization: base64 encoded value of client-id:client-secret","Accept: application/json, text/plain, */*"));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
$title = $result->title;
If someone could please shed some light on this.
Based on ADyson comments, here is the answer (just update the code with your own clientID and clientSecret ID from Udemy):
I've basically updated the CURLOPT_HTTPHEADER:
Code:
$url = "https://www.udemy.com/api-2.0/courses/?search=java";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
//HTTP username.
$clientID = 'XXX';
//HTTP password.
$clientSecret = 'XXX';
//Create the headers array.
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode("$clientID:$clientSecret")
);
//Set the headers that we want our cURL client to use.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
// echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
// echo curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
$json = json_decode($result, true);
// return $result;
foreach($json['results'] as $results) {
$title = $results['title'];
echo $title.'<br>';
}
Results: (Course titles based on this search: https://www.udemy.com/api-2.0/courses/?search=java)
Java Programming Masterclass for Software Developers
Java Programming for Complete Beginners
Java In-Depth: Become a Complete Java Engineer!
The Complete Java Certification Course
Etc.
I just got API access for one of the website on the internet, and as a new api developer i got into troubles understanding how should i start and with what, So hope you guys guide me . They don't have Documents or tutorials Yet.
If anyone can give me a small example on how to send Http post request that includes Header and body? As what they are mentioning in the API page:
All requests must include an Authorization header with siteid and
apikey (with a colon in between) and it must match with the siteid and
apikey in the request body
In the body the Parameter content type will be application/json. They have also provided a Base URL.
The response will be as application/json.
What should i do? is the request can be sent using AJAX? or there is PHP code for this? i have been reading a lot about this subject but none enter my head. Really hope you guys help me out .
Please let me know if you need more information so i can provide it to you.
EDIT : Problem solved and just posting the small editing that i did to the code that was provided in the correct answer that i marked .
Thanks to Mr. Anonymous for the big help that he gave me . His answer was so so close, all what i had to do is just edit his code a little bit and everything went good .
I will list the finial code down bellow in case any other developer had this issue or wanted to do an HTTP request .
First what i did is that i stored the data that i wanted to send over the HTTP in a file with a JSON type :
{
"criteria": {
"landmarkId": 181,
"checkInDate": "2018-02-25",
"checkOutDate": "2018-02-30"
}
}
Second thing as what guys can see what Mr. Anonymous posted .
<?php
header('Access-Control-Allow-Origin: *');
$SiteID= 'My Site Id';
$ApiId= 'My Api Id';
$url = 'Base URL';
// Here i will get the data that i created in Json data type
$data = file_get_contents("data.json");
// I guess this step in not required cause the data are already in JSON but i had to do it for myself
$arrayData = json_decode($data, true);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$SiteID:$ApiID");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Connection: Keep-Alive',
'Authorization: $SiteID:$ApiId'
));
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($arrayData));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
?>
Try this
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
############ Only one of the statement as per condition ###########
//if they have asked for post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id=$api_key" );
//or if they have asked for raw post
curl_setopt($ch, CURLOPT_POSTFIELDS, "$site_id:$api_key" );
####################################################################
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key"] );
$api_response = curl_exec ($ch);
curl_close ($ch);
As asker need to send JSON Payload to API
$site_id = 'your_site_id';
$api_key = 'your_api_key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api-connect-url');
curl_setopt($ch, CURLOPT_POST, 1);
//send json payload
curl_setopt($ch, CURLOPT_POSTFIELDS, "{
"criteria":{
"cityId":9395,
"area":{
"id":0,
"cityId":0
},
"landmarkId":0,
"checkInDate":"2017-09-02",
"checkOutDate":"2017-09-03",
"additional":{
"language":"en-us",
"sortBy":"PriceAsc",
"maxResult":10,
"discountOnly":false,
"minimumStarRating":0,
"minimumReviewScore":0,
"dailyRate":{
"minimum":1,
"maximum":10000
},
"occupancy":{
"numberOfAdult":2,
"numberOfChildren":1
},
"currency":"USD"
}
}
}"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["$site_id:$api_key", 'Content-Type:application/json'] );
$api_response = curl_exec ($ch);
curl_close ($ch);
I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
I need a lot of help with curl and sendgrid integration and I wanted to start with the curl statement shown below:
curl -X "GET" "https://api.sendgrid.com/v3/contactdb/recipients" -H "Authorization: basic key" -H "Content-Type: application/json"
Below script gives me an error "message":"request body is invalid"
<?php
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists';
// Generate curl request
$userid = 'useid';
$userkey= '12345';
$headers = array(
'Authorization' => 'Basic xxxxxxx',
);
$session = curl_init($request);
// Tell curl to use HTTP get
curl_setopt ($session, CURLOPT_POST, FALSE);
// Tell curl that this is the body of the GET
curl_setopt ($session, CURLOPT_POSTFIELDS, $headers);
curl_setopt($session, CURLOPT_USERPWD, $userid.':'.$userkey);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, False);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
var_dump($response);
curl_close($session);
?>
Eventually, I want to integrate the subscription system from my website to seamlessly update Sendgrid contact lists. If you think there are better ways to achieve this, please feel free to point it out to me as well. Thanks!
Based on your code, try this:
<?php
$url = 'https://api.sendgrid.com/v3/templates';
$request = $url.'/user/profile';
$params = array(
'name' => 'test'
);
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init($request);
$headers = array("Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
?>
Also when trying to debug these kind of API integrations I find it very useful to bind cURL to a local proxy that way I can monitor the HTTP communication between cURL and the API, e.g.,
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
If your using Windows and testing locally Fiddler works great for that.
Here's my solution. It is based off too many sources to list.
define("SENDGRID_API_KEY","SG.xxxxxxxxxxxxxxxxxxxxxxxx");
//the 'to' parameter can be either be a single email as a string or an array of emails
function email($to,$subject,$message) {
if (!$to) return;
//start the params
$params=[
'from'=> "yourEmail#address.com",
'fromname'=> "Your From Name",
'subject'=> $subject,
'text'=> preg_replace("/\n\s+/","\n",rtrim(html_entity_decode(strip_tags($message)))),
'html'=> $message,
];
//if we have an array of email addresses, add a to[i] param for each
if (is_array($to)) {
$i=0;
foreach($to as $t) $params['to['.$i++.']']=$t;
//just one email, can add simply like this
} else {
$params['to']=$to;
}
// Generate curl request
$session = curl_init('https://api.sendgrid.com/api/mail.send.json');
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.SENDGRID_API_KEY));
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//execute and obtain response
$response = curl_exec($session);
curl_close($session);
//no response at all. that's bad!
if (!$response) {
$errorMessage="SENDGRID SENT NO RESPONSE<br>";
} else {
$response=json_decode($response,true);
//wasn't a success
if ($response['message']!='success') {
$errorMessage="SENDGRID SENDING ERROR<br>Error(s): ".implode("<br>",$response['errors']);
}
}
//finish forming error message and save to log
if ($errorMessage) {
$errorMessage.="Subject: ".$subject."<br>To: ";
if (is_array($to)) {
$errorMessage.=implode(",",$to);
//just one email, can add simply like this
} else {
$errorMessage.=$to;
}
yourOwnLoggingFunction($errorMessage);
}
//show full response if needed
// print_r($response);
}
//send to one person
email("test#email.com","The Subject","<h1>The Body</h1><p>Goes here</p>");
//send to multiple people
email(["test1#email.com","test2#email.com"],"The Subject","<h1>The Body</h1><p>Goes here</p>");
<?php
$url = 'https://api.sendgrid.com/v3';
$request = $url.'/contactdb/lists';
// Generate curl request
$userid = 'useid';
$userkey= '12345';
$session = curl_init($request);
// Tell curl to use HTTP get
curl_setopt ($session, CURLOPT_POST, FALSE);
// Tell curl that this is the body of the GET
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($session, CURLOPT_USERPWD, $userid.':'.$userkey);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, False);
curl_setopt($session, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
var_dump($response);
curl_close($session);
?>
Solved & working version here
This question already has answers here:
How to properly send and receive XML using curl?
(2 answers)
Closed 9 years ago.
I have fetched data from server using this code, `$server = 'LOCALHOST:9000';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
print $data;
curl_close($ch);
}`
Now I have to do reverse, how to send the data into server using php? curl method is the only way or is there any other method to do the same. Give me some example.
Sending/Receiving using cURL is the exact same thing. cURL is based on sending data to an given URL and possibly receiving a response. Let's take a simple example of getting a user and sending a user.
Getting a user would be
$data = array(
'user_id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/getUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
getUser.php does nothing more than search for a user and return the data found.
$response would possibly contain data of the user, perhaps just a text-response containing the name. A serialized PHP array, an XML response with a full user profile.. etc.
Inserting/Sending data
$data = array(
'user_name' => 'Joshua',
'user_email' => 'my#email.com'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.site.com/addUser.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
addUser.php performs some validation of the fields and if validated inserts a user in the database
$response in this case does not contain the userdata (however: it's a possibility), but more likely the $response contains a result. An ok textresponse, a json/xml response or perhaps a '200 OK' header response
It's all basically the same. There is no difference in getting/sending data using cURL. It's all based on sending a request and in most cases do something with the outcome.