I am trying to set up a very simple bot. I generated an access token, created a simple index.php file on my web server (SSL certified), set up a webhook that points to my index.php file, subscribed my webhook to my page events (everything on developers.facebook.com), messaged my bot and got no answer. What might be the problem?
(I have checked everything: both tokens, I am admin etc.)
Here is my code:
<?php
$access_token = "i-filled-this-out";
$verify_token = "i-also-filled-this-out";
$hub_verify_token = null;
if(isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token) {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$message_to_reply = '';
$message_to_reply = 'Huh! what do you mean?';
//API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
Make sure your webhook is returning a HTTP 200 response to the POST requests sent by facebook.
What web server are you running? Check the logs to see if your webhook is receiving POST requests from facebook (and returning a 200).
Best way of testing your webhook is using something like postman to imitate the standard POSTs made by facebook and checking the responses you are serving.
Related
i'm trying to update my DNS domain record through cloudflare api using PHP Post, but the cloudflare api send response that POST method is not allowed for the api_token authentication scheme, i already tried the the api using postman and it works, but somehow in PHP the api does not work, is PHP does not support POST using token ?, some variable is stored inside env.php and i hide it because it sensitive information.
PHP code :
include("../../env.php");
//variable input by POST
$domain = $_POST['domain'];
$recordID = $_POST['recordID'];
$content = $_POST['content'];
$zoneID = $_POST['zoneID'];
//for update record
$linkRecord = "https://api.cloudflare.com/client/v4/zones/$zoneID/dns_records/$recordID";
$header = array(
"Content-Type: application/json",
"Authorization: Bearer $authToken"
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $linkRecord);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
$bodyArray = array("type"=>"A","name"=>$domain,"content"=>$content,"proxied"=>true);
$body = json_encode($bodyArray);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
$resp = curl_exec($curl);
print_r($resp);
linkRecord Variable Value:
https://api.cloudflare.com/client/v4/zones/{{my_secret_zone_id}}/dns_records/{{id_of_the_record}}
Cloudflare response of POST :
{
"success": false,
"errors": [
{
"code": 10000,
"message": "POST method not allowed for the api_token authentication scheme"
}
]
}
Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
index.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.
The error I get with this code is: The requested URL returned error: 500 Internal Server Error
I also receive a "Bad request" 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part
Is there anyone who knows what im doing wrong?
PS: It's not really possible to try this code yourself unless you have a 2ba account with working key's etc.
Okey I fixed it already...
I had to add some extra headers and change the $parameters values like this:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
index.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);
I want to send the login credentials and a pin number as a JSON data and the request token as my http header.
initially it's like this,
{
"Username":"admin",
"Password":"root123",
"PinCodeā : "hello321"
}
and I need to post my Request Header token as well.
and if the request is ok, I should get JSON response as follow,
{
"Title": "Mr.",
"Name": "Pushkov",
"Age": "18"
}
I'm trying to do it in cURL PHP. Below is my controller code.
I tried to save my request token to a variable and pass it in header and post username, password and pinnumber as JSON data. if the login success than user info should be displayed. but I'm struggling to move ahead from here. How can I achieve that?
public function send_data() {
$url='http://samplesite.azurewebsites.net/api/member/loginmember';
$ch = curl_init('http://localhost/main');
$data = array("Username" =>$this->input->post('un'), "Password" =>$this->input->post('pw'), "PinCode" =>$this->input->post('PinCode'));
$data_string = json_encode($data);
//echo $data_string;
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
//var_dump(json_decode($result, true));
$data2=json_decode($result, true);
$ref_id = ( ( is_array( $data2["UserCode"] ) ? implode(", ", $data2["PinCode"]) : $data2["RequestToken"] ) ); // array to string
$acc_t = $data2["RequestToken"];
$uun = $data2["UserCode"];
//echo $acc_t;
// Closing
curl_close($ch);
//print $result ;
}
In your code above, you set a URL to curl_init() and you also passed another one in CURLOPT_URL option. You can't do that in one cURL request.
If you are using OAuth 2.0 you can set the access token to CURLOPT_XOAUTH2_BEARER option.
More information, please refer to PHP manual on cURL Functions.
I have two vitual machines installed in a VMWare Workstation and they both have different IP address. I want to send a JSON array from one virtual machine to the other. So I am using the PHP cURL library to send the data, and have followed this tutorial. Below is my code snippet. For the sake of this question, let's suppose that AAA.BBB.CCC.DDD is the IP address of the destination host where I want to send the JSON data.
I have two questions:
All I know is the IP address of the destination host. That destination computer does have an XAMPP local server on it. NOW how do I contruct that URL for the destination? Please see the first line in the snippet below, am I making up the URL correctly?
2.When I execute this script on the localhost and meanwhile run Wireshark, three packets appear to be sent to the particular destination IP address. BUT I don't know how to receive the particular JSON data in the destination machine? It will be great if someone can point me to a tutorial for that or give me a hint?
<?php
$url = "http://AAA.BBB.CCC.DDD"; // AAA.BBB.CCC.DDD is replaced by the IP address of destination host.
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'name' => 'Jeremy',
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
My simple test example:
<?php
$url = 'http://localhost/curl-req.php';
$data = array("name" => "Heniek", "age" => "125", "rozmiar" => "M");
$data = json_encode($data);
// Send post data Json format
echo CurlSendPostJson($url,$data);
// send curl post
function CurlSendPostJson($url='http://localhost/curl-req.php',$datajson){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $datajson);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($datajson)));
//curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers
return $result = curl_exec($ch);
}
?>
<?php
// save belove to: curl-req.php
// GET JSON CONTENT FROM CURL
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
//echo $json = json_decode($jsonStr);
if (!empty($jsonStr)) {
echo $jsonStr;
}
// POST DATA FROM CURL
if (empty($jsonStr)) {
echo serialize($_POST);
}
// GET DATA FROM CURL
if (!empty($_GET)) {
echo serialize($_GET);
}
?>
I have been struggling for days now to find a decent solution for Laravel but to no avail.
There are many libraries out there that at one point may have worked to provide a Laravel - FitBit API OAuth integration however after trying over 15 different ones and none of them working I am stuck.
Reading the FitBit Documentation I see that once you receive a token you must swap the authorization code with an access token. To do this you need to send an authorization header like this:
POST https://api.fitbit.com/oauth2/token
Authorization: Basic Y2xpZW50X2lkOmNsaWVudCBzZWNyZXQ=
Content-Type: application/x-www-form-urlencoded
client_id=22942C&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fexample.com%2Fcallback&code=1234567890
I have tried using guzzle and a few other libraries for sending the requests but none of them support the format that FitBit require.
I've seen sites with FitBit API integrated so there must be a solution for this.
If anyone has managed to integrate the FitBit API please let me know where I am going wrong.
Thanks.
I don't have a fitbit account, so I can't test this and it will probably need some tweaking, but I would start with something like:
class FitbitConnection{
public function getToken($request_url, $client_id, $client_secret, $code, $redirect_uri){
// base64 encode the client_id and client_secret
$auth = base64_encode("{$client_id}:{$client_secret}");
// urlencode the redirect_url
$redirect_uri = urlencode($redirect_uri);
$request_url .= "?client_id={$client_id}&grant_type=authorization_code&redirect_uri={$redirect_uri}&code={$code}";
// Set the headers
$headers = [
"Authorization: Basic {$auth}",
"Content-Type: application/x-www-form-urlencoded",
];
// Initiate curl session
$ch = curl_init();
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Options (see: http://php.net/manual/en/function.curl-setopt.php)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_POST, 1);
// Execute the curl request and get the response
$response = curl_exec($ch);
// Throw an exception if there was an error with curl
if($response === false){
throw new Exception(curl_error($ch), curl_errno($ch));
}
// Get the body of the response
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseBody = substr($response, $header_size);
// Close curl session
curl_close($ch);
// Return response body
return $responseBody;
}
}
You should note that I've commented out
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
You can put this option back in if you get an SSL certificate problem on your localhost, but you shouldn't use it in production .
You can then just do something like:
try{
$fitbitConnection = new FitbitConnection();
$token_response = $fitbitConnection->getToken("https://api.fitbit.com/oauth2/token","22942C","client_secret","1234567890","http://www.example.com");
echo $token_response;
}catch(Exception $e){
// curl error
echo $e->getMessage();
}