Hi I'm trying to setup a PHP CURL call using OAuth1 authorization method.
I've tried with POSTMAN 1st, to generate the PHP code. I've completed it with the necessary datas
<?php
$conskey = 'XXXXXXX';
$conssec = 'XXXXXXX';
$nonce = mt_rand();
$timestamp = time();
$url = 'https://some-website/api/project/subproject';
$method = 'POST';
$oauth = new OAuth($conskey, $conssec, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->setNonce($nonce);
$oauth->setTimestamp($timestamp);
$signatureOAuth = $oauth->generateSignature($method, $url);
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_URL => $url.'?oauth_consumer_key='.$conskey.
'&oauth_signature_method=HMAC-SHA1&oauth_timestamp='.$timestamp.
'&oauth_nonce='.$nonce.
'&oauth_version=1.0&oauth_signature='.$signatureOAuth,
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 => $jsonDatas,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
// THE COOKIE I WANNA GET
'Cookie: SSESSd4f3e89d4699e1d1a071aa37eab4fcEd=DWS4UqpaykI2y7q-HJXEzGN82AKHQYnWo5hbsqkAqiQ'
),
));
$result = curl_exec($curl);
curl_close($curl);
But I've noticed that there's the cookie in the CURLOPT_HTTPHEADER entry but I don't have any idea how POSTMAN generate this cookie.
Without this cookie or with a dumb string, the CURL response is always Invalid Signature
Postman is not generating cookies for you, and neither is curl/php. you either did some prior requests (usually GET to get cookies) requests to the website where you received some cookies, or gave the cookies to postman some other way.
since you're not showing us the real url, we can only speculate, but to take an example, here is how to get a session cookie for stackoverflow.com:
<?php
$ch=curl_init();
curl_setopt_array($ch,array(
CURLOPT_COOKIEFILE => "", // setting it to empty activates the curl cookie engine (its disabled by default.),
CURLOPT_URL => "https://stackoverflow.com/",
CURLOPT_RETURNTRANSFER => true,
));
$html=curl_exec($ch);
$cookies = (function($cookielist):array{
$cookies = array();
foreach($cookielist as $cookie_raw) {
$chunks = explode("\t", $cookie_raw);
//var_dump($chunks);
$cookie['domain'] = $chunks[0];
$cookie['secure'] = $chunks[1];
$cookie['path'] = $chunks[2];
$cookie['???todo_wtf_is_this'] = $chunks[3];
$cookie['expiration'] = $chunks[4];
$cookie['name'] = $chunks[5];
$cookie['value'] = $chunks[6];
$cookies[] = $cookie;
}
return $cookies;
})(curl_getinfo($ch, CURLINFO_COOKIELIST));
var_export($cookies);
prints something like
array (
0 =>
array (
'domain' => '#HttpOnly_.stackoverflow.com',
'secure' => 'TRUE',
'path' => '/',
'???todo_wtf_is_this' => 'FALSE',
'expiration' => '2682374400',
'name' => 'prov',
'value' => '9c06f038-9f70-bee8-2a64-b095656175d1',
),
)
which could be used like
// THE COOKIE I WANNA GENERATE
'Cookie: '. $cookies[0]["name"].'='.$cookies[0]["value"]
but this is very rarely done, usually you'd just use curl's built-in cookie engine to handle cookies automatically..
Related
I am testing an api on postman. The request body should be in x-www-form-url-encoded. My requests are being passed successfully, and am able to generate a snippet which I have shared here. However, some of the parameters that am adding to the body (Amount, and phone number) will not be static when the api is employed on my site. These parameters will vary by user. I have tried to define those parameters at the top of the code as you cane see $Airtime_amount and
$Recieving_mobile, but how can I pass them to the x-www-form-url-encoded CURLOPT_POSTFIELDS in the code below? See how am trying to pass them, but without success...
In other words, I have a url encoded string from postman, but the parameters in that string are static. i would like to make them dynamic..Like get user phone number from wordpress, and insert it in the urlencoded string
//Wordpress hook to call the api begins here
add_action('hrw_withdrawal_request_notification','disburse_airtime',7);
function disburse_airtime() {
$Airtime_amount = "KES 230";
$Recieving_mobile = "+254757777777";
//Snippet generated from postman begins here
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.sandbox.africastalking.com/version1/airtime/send',
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 => 'username=sandbox&recipients=%5B%7B%22phoneNumber%22%3D%3E%24Recieving_mobile%2C%22amount%22%3D%3E%24Airtime_amount%7D%5D',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
'apiKey: 61449ca078574078a6d0eaaa01cfb751f803797c99714f74d8541a25e2a612ef',
'Accept: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
You should probably build the POSTFIELDS string using the http_build_query function.
Your existing string has what looks like a JSON string for the value of the recipients parameter, so we can build that up using arrays, then encode it when we set it in the params.
function disburse_airtime()
{
$Airtime_amount = "KES 230";
$Recieving_mobile = "+254757777777";
$recipients = [
[
'phoneNumber' => $Recieving_mobile,
'amount' => $Airtime_amount
]
];
$params = [
'username' => 'sandbox',
'recipients' => json_encode($recipients)
];
$postFields = http_build_query($params);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api.sandbox.africastalking.com/version1/airtime/send',
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 => $postFields,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'apiKey: 61449ca078574078a6d0eaaa01cfb751f803797c99714f74d8541a25e2a612ef',
'Accept: application/json'
],
]);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
Side note, if you want to "reverse engineer" the data that is in the encoded string in order to build it up in your own code, you can do so with using urldecode and parse_str:
$str = 'username=sandbox&recipients=%5B%7B%22phoneNumber%22%3D%3E%24Recieving_mobile%2C%22amount%22%3D%3E%24Airtime_amount%7D%5D';
parse_str(urldecode($str), $params);
print_r($params);
Result:
Array
(
[username] => sandbox
[recipients] => [{"phoneNumber"=>$Recieving_mobile,"amount"=>$Airtime_amount}]
)
I am trying to automate the sign in process with the Zoom API to allow me to use my website to create meetings but I cannot seem to get the sign in to work in order to allow me to get an authentication code to call the API methods. I am doing this in PHP and I am fairly novice so may be making some fundamental errors.
If I make the 2 calls in the code below via postman and copy the code from postman to my PHP then it works for an hour (My guess is that this is because the cookies have an hour expiry?). Given I thought it was down to cookies I have tried a couple of way to copy the cookies returned in the set-cookie header but this still isn't working. Can someone help me with what I am missing? Apologies if the code is messy...
<?php
$curl = curl_init();
$headers = [];
curl_setopt_array($curl, array(
CURLOPT_URL => "https://zoom.us/oauth/v2/signin",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
},
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('email' => 'some#thing.com','password' => 'somePassword','client_id' => 'someClientID','redirect_uri' => 'https://www.some.thing','response_type' => 'code','scope' => '','state' => ''),
));
$response = curl_exec($curl);
$cookie2 = "Cookie: ";
echo "<br>_____<br>";
print_r($headers["set-cookie"]);
echo "<br>_____<br>";
//echo var_dump(curl_getinfo($curl));
foreach ($headers["set-cookie"] as &$value) {
echo "<br>------------<br>";
echo $value;
$cookies = explode(';', $value);
$cookie2 .= $cookies[0] . "; ";
}
unset($value);
echo "<br>_____<br>";
echo $cookie2;
echo "<br>_____<br>";
echo $response;
$nextUrl = json_decode($response, true)["nextUrl"];
// -------------------------------------------
//$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://zoom.us/oauth/authorize?client_id=clientID&response_type=code&redirect_uri=https://www.some.thing",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
$cookie2
),
));
$response = curl_exec($curl);
curl_close($curl);
$pieces = explode("> ", $response);
$authCode = substr($pieces[1], 0, -3);
echo "auth code: " . $authCode;
// ---------------------------------------------------------------
?>
My Solution for this was to use a refresh token call instead to avoid the need for signing in for every call. Now for each call to the Zoom API I refresh the token and then make the API call, storing the tokens on the server for future use.
Besides refreshing your token for each request, you can generate immortal tokens with your own client secret on the jwt token site. For example, I produced a valid token until 2052 and can request as many requests as I want.
Firstly, you should take your token from Zoom and open jwt.io web site and paste it here. You can change the timezone, exp: expiring time, iat: starting time
Finally, you pass your client_secret key
Here is my code:
// Build request URL
$url = 'https://connect.squareup.com/v2/locations/';
// Build and execute CURL request
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $accessToken,
'Accept: application/json',
)
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
var_dump($content);
Here is what I get back:
string(158) "{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"NOT_FOUND","detail":"API endpoint for URL path `/v2/locations/` and HTTP method `GET` is not found."}]}"
I am pounding my head on this one... I tried using the Square SDK but calling from it doesn't return a list of locations either.
I have created an application on the Square Developer Dashboard. $accessToken is set to the sandbox access token listed there.
You have added an extra / at the end of the url. You should instead use:
$url = 'https://connect.squareup.com/v2/locations';
Other than that your code works!
I am trying to remote login using the following code:
$cookiefile = dirname(__FILE__)."/cookie.txt" ;
$postData = array(
'&email' => 'email',
'&pwd' => 'password',
// 'redirect_to' => 'http://example.com',
// 'testing_cookie' => '1'
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://exaple.com/login?cid=6',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIESESSION => true,
CUROPT_COOKIEJAR => $cookiefile,
CURLOPT_COOKIEFILE=> $cookiefile
));
$output = curl_exec($ch);
echo $output;
I am getting the error - No cookies found -
Sorry, but your browser doesn’t seem to accept cookies from our site. A cookie is a small data package stored in your browser that is needed for personal identification
Update:
Besides I am also getting error like:
Notice: Use of undefined constant CUROPT_COOKIEJAR - assumed 'CUROPT_COOKIEJAR' in E:\wamp\www\remote-curl\curl_request.php
I'm using the LinkedIn REST API to post updates to a users timeline.
Since a few days I get an Internal server error response from LinkedIn but the code worked before.
PHP:
$postTitle = "hello";
$postDesc = "world ";
$submitted-url = "http://example.com";
$submitted-image-url = "http://images.example.com/img/hello.jpg";
$comment = "foobar";
$postData = array('visibility' => array('code' => 'connections-only'),
'content' => array('title' => $postTitle,'description' => $postDesc,'submitted-url' => $postURL,'submitted-image-url' => $postImage), 'comment' => $postComment);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='.$oauthToken.'&format=json'
);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
How to fix that error?
Your code is invalid PHP (perhaps because of some edits you made before posting?); modifying it to:
$postTitle = "hello";
$postDesc = "world ";
$postURL = "http://example.com";
$postImage = "http://images.example.com/img/hello.jpg";
$postComment = "foobar";
$oauthToken = "<token>";
$postData = array(
'visibility' => array('code' => 'connections-only'),
'content' => array(
'title' => $postTitle,
'description' => $postDesc,
'submitted-url' => $postURL,
'submitted-image-url' => $postImage
),
'comment' => $postComment
);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='.$oauthToken.'&format=json');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
works if only $oauthToken is set to a valid token. Assuming your real code is correct the only possiblity left is that your OAuth token has expired and you need to obtain a new one first. By adding CURLOPT_VERBOSE => TRUE to the cURL options you would find out more about the error that LinkedIn returns.
You may considering using the LinkedIn PHP SDK (provided by the community) instead: https://github.com/Happyr/LinkedIn-API-client
We faced similar issue with Linkedin API recently. Finally figured out the fix by changing the url.
New URL : "https://api.linkedin.com/v1/people/~/shares"
Instead of specifying 'oauth2_access_token' in the query string,
add it in the header - specify :
"Authorization", "Bearer " + accessToken.
And finally in the request body parameter, add your json/xml data to post
You have to Use your Authentication Token in Request Headers.
This is the working code. Try it.
$postTitle = "hello";
$postDesc = "world ";
$submitted-url = "http://example.com";
$submitted-image-url = "http://images.example.com/img/hello.jpg";
$comment = "foobar";
$oauthToken = "TokenHere";
$postData = array('visibility' => array('code' => 'connections-only'),
'content' => array('title' => $postTitle,'description' => $postDesc,'submitted-url' => $postURL,'submitted-image-url' => $postImage), 'comment' => $postComment);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?format=json');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json", "Bearer: ".$oauthToken.""),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);