I am trying to connect to an API which is based on JSON-RPC 2.0. As i am new to this im not sure if im coding this correctly because all I am recieving is an error.
Can anyone give me a brief explanation on how to connect to API in PHP?
<?php
header('Content-Type: application/json');
//check if you have curl loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");
$url = 'xxxxxxxxx';
$data = array(
"operator_id" => "xxxx",
"login" => "xxxx",
"password" => "xxxx",
);
$curl_options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_NOBODY => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_ENCODING => 'gzip,deflate',
CURLINFO_HEADER_OUT => true,
);
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
$output = curl_exec($ch);
curl_close($ch);
$arr = json_decode($output,true);
echo ($output);
?>
The response i am recieving is this: {"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":null}
The response i should be recieving if successful login is: {"jsonrpc":"2.0","result":true,"error":null,"id":1,"ts":1368533487}
You're not sending a JSON-RPC request at all.
The request must be a JSON body, so you must json_encode the data before passing it to CURLOPT_POSTFIELDS.
The posted json must have the keys method, params, id, and jsonrpc (the last should be set to "2.0"). Your data would go into params. The id can be set to whatever, but without it you shouldn't get a response at all.
It is a quite simple format. See the specification at http://www.jsonrpc.org/specification
Related
So I have the following CURL command in PHP, if I send it https://webhook.site I can extract all the required data in JSON format.
Instead of using webhook.site, I would like to create my own PHP webhook client.
The code below is the CURL command that works 100% when using webhook.site:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://webhook.site/832090f1-f54f-4847-8c0d-5ec9208541a1',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('SmsSid' => 'SMe8723661742d423fbf3fa9f7bbede050','SmsStatus' => 'sent','MessageStatus' => 'sent','ChannelToAddress' => '+1788123XXXX','To' => 'whatsapp:+15196978899','ChannelPrefix' => 'whatsapp','MessageSid' => 'SMe8723661742d423fbf3fa9f7bbede050','AccountSid' => 'AC306a09582e77715b0eb72df90de4c590','StructuredMessage' => 'false','From' => 'whatsapp:+154xxxxxx','MediaUrl0' => 'https://api.twilio.com/2010-04-01/Accounts/werwersdsdg72df90de4c590/Messages/wweugryuwyr7762b11ea/Media/wjeruwiy6243742
'),
CURLOPT_HTTPHEADER => array(
'user-agent: TwilioProxy/1.1',
'host: Postman'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I then tried to use PHP to create a basic webhook just to pull the data:
<?php
if($json = json_decode(file_get_contents("php://input"), true)){
$data = $json;
$fp = file_put_contents( 'request.log', $data );
}
print_r($data);
?>
But I keep coming with a blank request.log file - what am I doing wrong??? Thanks in advance
Twilio developer evangelist here.
By default, curl will make a POST request with the Content-Type header application/x-www-form-urlencoded. This is actually the same content type that Twilio uses when it sends a webhook request.
Your PHP to receive the request is trying to json_decode the data, which won't work with form encoded data. Instead, you can access $_POST to get an associative array of the parameters sent to your script. You can then write them to a log file however you like.
I'm very new to PHP and API, and my company was asked for a job of incorporating API calls on a PHP website.
This is the info about the API that the client gave to us:
API Manual
General Notes:
API URL: https://www.somedomain.com/api/
apiKey: 123qwe456rty678yui
HTTP Verb: POST
Content-Type: application/x-www-form-urlencoded
1. {EMPLOYEES category}
POST /en/1001/cat/10
POST /en/1001/cat/10/page/[999]
Observations:
• the list returns 20 records
• to get the reamining records: /en/1001/cat/10/page/2; /en/1001/cat/10/page/3; ...
• the information is returned in JSON format
• all the requests should be made by the POST method and the api key should be sent on the request body
Input variables:
• apiKey => App key
Return parameters:
retCode = “error”
retCode = “ok”
(...)
2. {NEWS category}
POST /en/2002/cat/20
POST /en/2002/cat/20/page/[999]
Observations:
• the list returns 20 records
• to get the reamining records: /en/2002/cat/20/page/2; /en/2002/cat/20/page/3; ...
• the information is returned in JSON format
Input variables:
• apiKey => App key
Return parameters:
retCode = “error”
retCode = “ok”
(...)
And I've made a simple PHP script but I'm getting an empty return value:
<?php
//API URL: https://www.somedomain.com/api/
//This is to test the Employees category - /en/1001/cat/10
$curl = curl_init();
$apiKey = urlencode("123qwe456rty678yui");
//$apiKey = "123qwe456rty678yui";
//it doesn't matter if this variable is urlencoded or not, as the result is always empty...
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.somedomain.com/api/en/1001/cat/10",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_SSL_VERIFYPEER => "false",
CURLOPT_POSTFIELDS => "apiKey=$apiKey",
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "Response: " . $response;
}
?>
Like I said, I'm very new to this, PHP and API's, and the client isn't very helpful.
Based on the Manual API I have, what I'm doing wrong? $response is always empty, it gives no error even if I enter a wrong API Key, and I don't even know if I'm calling this the correct way...
Thanks in advance!
Here is a function that should work from the manual: https://www.php.net/manual/en/function.curl-setopt-array.php#89850
<?php
function get_web_page($url, $curl_data )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_POST => 1, // i am sending post data
CURLOPT_POSTFIELDS => $curl_data, // this are my post vars
CURLOPT_SSL_VERIFYHOST => 0, // don't verify ssl
CURLOPT_SSL_VERIFYPEER => false, //
CURLOPT_VERBOSE => 1 //
);
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$content = curl_exec($ch);
$err = curl_errno($ch);
$errmsg = curl_error($ch) ;
$header = curl_getinfo($ch);
curl_close($ch);
// $header['errno'] = $err;
// $header['errmsg'] = $errmsg;
// $header['content'] = $content;
return $header;
}
$curl_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);
print '<pre>';
print_r($response);
?>
You can also try the file_get_contents function to get this JSON data.
Something like this could do the job:
// API URL
$apiUrl = 'https://www.somedomain.com/api/en/2002/cat/20';
// Request options
$opts = [
"http" => [
'method' => 'POST',
'header' => [
'Content-Type: application/x-www-form-urlencoded',
'apiKey: 123qwe456rty678yui'
]
]
];
// Request context
$context = stream_context_create($opts);
// Get JSON
$json = file_get_contents($apiUrl, false, $context);
Try and see if you can adapt it.
How could I send a Discord DM with cURL? I've got it working w/ channel messages but a Discord DM is quite important to my Website to keep users updated. Below is what I've got so far, with the ID being a Discord User ID.
$url = 'https://discordapp.com/api/channels/591765736003731487/messages';
$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Authorization : Bot <TOKEN>'),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_STDERR => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);
Using your current code, I've made a small snippet. You might need to change a few things according to your needs, but for this matter it works as intended. To make a good use of the CURL request and not make and use repetitive code, I would put it in a function, in this case MakeRequest($endpoint, $data)
Where $endpoint is a String and $data should be an Array
In order to open and send a direct message to a user, you need these endpoints.
For creating a new direct message
POST /users/#me/channels
For sending messages:
POST /channels/{channel.id}/messages
<?php
function MakeRequest($endpoint, $data) {
# Set endpoint
$url = "https://discord.com/api/".$endpoint."";
# Encode data, as Discord requires you to send json data.
$data = json_encode($data);
# Initialize new curl request
$ch = curl_init();
$f = fopen('request.txt', 'w');
# Set headers, data etc..
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array(
'Authorization: Bot token',
"Content-Type: application/json",
"Accept: application/json"
),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POSTFIELDS => $data
CURLOPT_STDERR => $f,
));
$request = curl_exec($ch);
curl_close($ch);
return json_decode($request, true);
}
# Open the DM first
$newDM = MakeRequest('/users/#me/channels', array("recipient_id" => "ID From the user"));
# Check if DM is created, if yes, let's send a message to this channel.
if(isset($newDM["id"])) {
$newMessage = MakeRequest("/channels/".$newDM["id"]."/messages", array("content" => "Hello World."));
}
?>
Heads up: Due security and privacy matters, a direct message might not open if:
The user doesn't share the same server as your bot.
The user has turned off DMs from server members.
The user has blocked your bot.
I read some Q&As but still struggling with this one. I need to post a specific array to an API and get another array as an answer.
UPDATE
I used :
<?php
echo 'Testing cURL<br>';
// Get cURL resource
$curl = curl_init();
$data=array(array("UserId"=>"xxxx-10100","Password"=>"pass"));
$sendpostdata = json_encode( array( "postdata"=> $data ) );
echo $sendpostdata;
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
This results in
Testing cURL
{"postdata":[{"UserId":"xxxxx-10100","Password":"pass"}]}
{ "Data": null, "Success": false, "Error": { "Message": "Invalid UserId: ", "Value": "InvalidUserId", "Code": 9001 } }
No console logs, no other messages or clues
I am trying to implement this API https://cloud.servicebridge.com/developer/index#/
to Worpdress.
The API requires a
{
"UserId": "string",
"Password": "string"
}
Can you help me out? What am I doing wrong
Really appreciate this,
Giannis
I have checked the given API and it's REQUEST Parameters to access them and I think your initial data (username and password) is not going correctly. Please use this code:-
<?php
error_reporting(E_ALL); // check all type of errors
ini_set('display_errors',1); // display those errors
// Get cURL resource
$curl = curl_init();
$sendpostdata = json_encode(array("UserId"=>"xxxx-10100","Password"=>"pass"));
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
Note:- change UserId & Passwordvalues to your real values.Thanks
This might help you in generating proper json. Hope this will work.
use this
$data=array(array("UserId"=>"xxxxx-10100","Password"=>"pass"));
instead of
$data ='[{"UserId":"xxxxx-10100","Password": "pass"}]';
I have been able to use the Advanced Rest Client Extension for chrome to send POST queries to an specific HTTPS server and I get Status Code: 200 - OK with the same body fields as the ones I used in this code, but when I run the following code I get this response: 403 - Access Denied.
<?php
$postData = array(
'type' => 'credentials',
'id' => 'exampleid',
'secret_key' => 'gsdDe32dKa'
);
// Setup cURL
$ch = curl_init('https://www.mywebsite.com/oauth/token');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
var_dump($response);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
?>
I've noticed as well that when I use Advanced Rest Client Extension for chrome and if I set the Content-Type to application/json I have to enter a login and a password that I don't know what are those because even if I enter the id and secret key that I have in the code it returns 401 Unauthorized. So I'm guessing this code that I wrote is not forcing it to the content-type: application/x-www-form-urlencoded, but I'm not sure. Thank you for any help on this issue!
Can you try like that and see if it helps:
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_COOKIEFILE => 'cookie.txt',
CURLOPT_COOKIEJAR => 'cookie.txt',
CURLOPT_USERPWD => 'username:password', //Your credentials goes here
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
CURLOPT_POSTFIELDS => http_build_query($postData),
));
I guess the site expect simple authentication on top of the secret_key that you already provided.
Also it is possible to send a Cookie, so just in case it is good idea to store it and use it again in the next Curl calls.