I am working with twitter digit. my mobile verification works corrccetly. but with auth header information when I call curl then it not working.my curl code
$request=$_REQUEST['someData'];
function oauth_value($headersIndex = [])
{
if(empty($headersIndex)) return 'Invalid Index Number';
$value = explode('=', $headersIndex);
return str_replace('"', '', $value[1] );
}
$headersData = explode(',',$request['headers']);
$ch = curl_init();
$ch = curl_init($request['apiUrl']);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization' => 'OAuth oauth_consumer_key="'.oauth_value($headersData[0]).'",
oauth_nonce="'.oauth_value($headersData[1]).'",
oauth_signature="'.oauth_value($headersData[2]).'",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="'.oauth_value($headersData[4]).'",
oauth_token="'.oauth_value($headersData[5]).'",
oauth_version="'.oauth_value($headersData[6]).'"'
)
);
$resp = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
example information that come form $_REQUEST['someData'];
Array
(
[apiUrl] => https://api.digits.com/1.1/sdk/account.json
[headers] =>
OAuth oauth_consumer_key="OybCXYoYTuS0Cw0usZYry6Nlj",
oauth_nonce="3942830480-TILitVHHZGmcczuuFj3nbJtnMm00DHvvgduawMHOybCXYoYTuS0Cw0usZYry6Nlj1445246231940",
oauth_signature="dXHcH%2FsLBIlYOVWBIhEBWSCMLJo%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1445246231",
oauth_token="3942830480-TILitVHHZGmcczuuFj3nbJtnMm00DHvvgduawMH",
oauth_version="1.0"
)
What can I do Now?
If you have a URL and header from digits then you can use below code:
$apiUrl = 'https://api.digits.com/1.1/sdk/account.json';
$authHeader = 'OAuth oauth_consumer_key="**********", oauth_nonce="****", oauth_signature="****", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1481554529", oauth_token="*****", oauth_version="1.0"';
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Authorization: {$authHeader}"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($apiUrl, false, $context);
$final_output = array();
if($file)
{
$final_output = json_decode($file,true);
}
print_r($final_output);
It will return id_str, phone number etc. You can store those data in your database.
Related
I am creating a PHP script to access Open Ai's API, to ask a query and get a response.
I am getting the following error:
You didn't provide an API key. You need to provide your API key in an
Authorization header using Bearer auth (i.e. Authorization: Bearer
YOUR_KEY)
...but I thought I was providing the API key in the first variable?
Here is my code:
$api_key = "sk-U3B.........7MiL";
$query = "How are you?";
$url = "https://api.openai.com/v1/engines/davinci/jobs";
// Set up the API request headers
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $api_key
);
// Set up the API request body
$data = array(
"prompt" => $query,
"max_tokens" => 100,
"temperature" => 0.5
);
// Use WordPress's built-in HTTP API to send the API request
$response = wp_remote_post( $url, array(
'headers' => $headers,
'body' => json_encode( $data )
) );
// Check if the API request was successful
if ( is_wp_error( $response ) ) {
// If the API request failed, display an error message
echo "Error communicating with OpenAI API: " . $response->get_error_message();
} else {
// If the API request was successful, extract the response text
$response_body = json_decode( $response['body'] );
//$response_text = $response_body->choices[0]->text;
var_dump($response_body);
// Display the response text on the web page
echo $response_body;
All Engines endpoints are deprecated.
This is the correct Completions endpoint:
https://api.openai.com/v1/completions
Working example
If you run php test.php in CMD, the OpenAI API will return the following completion:
string(23) "
This is indeed a test"
test.php
<?php
$ch = curl_init();
$url = 'https://api.openai.com/v1/completions';
$api_key = '<OPENAI_API_KEY>';
$post_fields = '{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0
}';
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
var_dump($response->choices[0]->text);
?>
public function auth_callback()
{
if ($this->input->get("code") != null)
{
$this->Strava_model->UpdateProfileStravaToken($this->input->get("code"),$this->session->userdata("athlete_id"));
$url = "http://www.strava.com/oauth/token?client_id=[xxxxx]&client_secret=[xxxxxxxxxxx]&code=".$this->input->get("code")."&grant_type=authorization_code";
$post = array();
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($post)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
echo $result;exit;
$cURLConnection = curl_init($url);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $post);
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);
$jsonArrayResponse = json_decode($apiResponse);
redirect($this->config->item("base_url") . "/activity");
}
}
I manage to get the code, and now proceed to get access token.
I'm using php curl to send post as below:
http://www.strava.com/oauth/token?client_id=[xxxx]&client_secret=[xxxxx]&code=[code retrieve from redirection]&grant_type=authorization_code
Once I executed the code above, I got this "You're being redirect..."
Can anyone advice and help?
Generally requests to the OAuth2 token endpoint require parameters to be passed as form-data, in the request body. Based on your current source, you are sending an empty request body.
I need to send data to an API using PHP. The API has a redirect page before showing the final result. The following code shows the content of the redirecting page rather than the final result. How can I wait until the final result?
$url = 'https://example.com/api';
$data = array('text' => "try");
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'GET',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
echo $result;
P.S. I got this code from one of stackoverflow's questions.
You could use cURL to get the final response, using CURLOPT_FOLLOWLOCATION:
From documentation :
CURLOPT_FOLLOWLOCATION: TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
$url = 'https://example.com/api';
$data = array('text' => "try");
$full_url = $url . (strpos($url, '?') === FALSE ? '?' : '')
. http_build_query($data) ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $full_url) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);
var_dump($response) ;
I am trying to create a service on hook.io to load token from another API.
public function loadToken()
{
$computedHash = base64_encode(hash_hmac ( 'md5' , $this->authServiceUrl , $this->password, true ));
$authorization = 'Authorization: Bearer '.$this->username.':'.$computedHash;
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, '');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($curl, CURLOPT_URL, $this->authServiceUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$obj = json_decode($result);
$info = curl_getinfo($curl);
curl_close($curl);
if($info['http_code'] != '200')
{
// print error from the server
echo($obj);
return NULL;
}
return $obj;
}
But it turns out hook.io doesn't support cUrl in PHP . I know it can done directly with php but i don't know how.
edit :
i used file_get_contents now it's give some other error now.
$username = '';
$password = '';
$authServiceUrl = '';
$computedHash = base64_encode(hash_hmac ( 'md5' , $authServiceUrl , $password, true ));
$authorization = 'Authorization: Bearer '.$username.':'.$computedHash;
// Create map with request parameters
// Build Http query using params
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Content-Type: application/json". $authorization ,
);
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
$authServiceUrl, // page url
false,
$context);
I have added the error in comments below
Actually, hook.io has curl support as far as I know. But if you want to try other alternatives, you can use file_get_contents. It has support for custom context and parameters.
$opts = [
'http' => [
'method' => 'POST',
'headers' => ['Authorization' => 'Bearer ' . $this->username . ':' . $computedHash]
]
];
$context = stream_context_create($opts);
$file = file_get_contents('http://www.hook.io/example/', false, $context);
I have to fetch exam results from the page http://cbseresults.nic.in/class1211/cbse122012.htm
Sampleroll number is 4623447.
They are using http post to post the form data.I wrote the following code to post data.But it is not providing the needed results.I am posting the needed cookies and post variables.But still I am not getting the output.What change should I make for send_post function,so that it will be working.Here is my code
echo cbse12_data_extractor(4623447);
function cbse12_data_extractor($regNo) {
$source_url = 'http://cbseresults.nic.in/class1211/cbse122012.asp';
$post_vars = array('regno'=>$regNo);
$cookies = array('_tb_pingSent'=>1);
// $extraHeaders = array('Host'=>'http://cbseresults.nic.in');
return send_post($source_url,$post_vars,$cookies);
}
function send_post( $url, $data ,$cookies='',$extraHeaders = '') //sends data array(param=>val,...) to the page $url in post method and returns the reply string
{
$post = http_build_query( $data );
$header = "Accept-language: en\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen( $post ) .
"\r\nUser-agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n";
if($extraHeaders) {
foreach($extraHeaders as $headerN => $val) {
$header = $header.$headerN.': '.$val."\r\n";
}
}
if($cookies) {
$cookieArr = array();
foreach($cookies as $cookie => $value) {
array_push($cookieArr,$cookie.'='.$value);
}
$cookieStr = "Cookie: ".implode('; ',$cookieArr)."\r\n";
$header = $header.$cookieStr;
}
$context = stream_context_create( array(
"http" => array(
"method" => "POST",
"header" => $header,
"content" => $post
)
) );
//echo $header;
$page = file_get_contents( $url, false, $context );
return $page;
}
You can' send POST data using file_get_contents. Use CURL for this task
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,your_parameters);
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);