After many tests, I cannot retrieve the access token. It gives me every time this error:
"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : authorization code not found","error":"invalid_request"
I totally distraught. For a few days I cannot solve my problem.
Here is the code of my application :
Route::get('login/linkedin', function()
{
$lk_credentials = Config::get('linkedin.public0');
$provider = new LinkedIn($lk_credentials);
if(!Input::has('code')){
$provider->authorize();
}else{
$code = Input::get('code');
if(strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with LinkedIn');
try{
$params = array(
'response_type' => 'code',
'client_id' => '*************',
'redirect_uri' => urlencode(url('login/linkedin')),
'state' => $_GET['state'],
);
$postdata = http_build_query($params);
$url = '/uas/oauth2/authorization?'.$postdata;
$context = stream_context_create(array('https' => array('method' => 'GET')));
$t = $provider->getAccessToken('authorization_code', array('code' => $_GET['code']));
Session::put('oauth2_access_token', $t->accessToken);session(['oauth2_access_token' => $t->accessToken]);
try{
if(count($_POST) > 0){
print_r($_POST);
exit('post');
}
$params = array(
'grant_type' => 'authorization_code',
'code' => Session::get('oauth2_access_token'), //$_GET['code'],
'redirect_uri' => urlencode(url('login/linkedin')),
'client_id' => '123456789',
'client_secret' => '123456789',
);
$postdata = http_build_query($params);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'https://www.linkedin.com/uas/oauth2/accessToken');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS,$postdata);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded',));
$output = curl_exec($c);
if($output === false){
trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING);
exit('Erreur');
}else{
var_dump($output);
//exit('Affiche');
}
curl_close($c);
}catch(Exception $e){
return 'Unable to get Request Token';
}
}catch(Exception $e){
return 'Unable to get user authorization_code';
}
try{
$resource = '/v1/people/~:(id,emailAddress,firstName,lastName,pictureUrl,dateOfBirth,location)';
$params = array(
'oauth2_access_token' => Session::get('oauth2_access_token'),
'format' => 'json',
);
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
$context = stream_context_create(array('http' => array('method' => 'GET')));
$response = file_get_contents($url, false, $context);
$data = json_decode($response);
Session::put('data', $data);session(['data' => $data]);
return redirect('/')->with('data',$data);
}catch(Exception $e){
return 'Unable to get user details';
}
}
});
Does anyone could help me?
For information; I use Laravel5 and for the authentication is OAuth2.
Thank you in advance, David.
Related
I am using instagram api to search specific hashtag getting top media and recent media but graphic shows 4 different calls, so the the 200 limit per hour are consumed really fast. I know about ig_hashtag_search , top_media and recent_media but what i dont know what is shadowIGHastag.
Is there a way to avoid overconsumption of my app?
This is how i use the api
function insthashtag()
{
include "../insta/define.php";
function makeApiCall($endpoint, $type, $params)
{
$ch = curl_init();
if ('POST' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_POST, 1);
} elseif ('GET' == $type) {
curl_setopt($ch, CURLOPT_URL, $endpoint . '?' . http_build_query($params));
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
$hashtag = 'sedapal';
$hashtagId = '17843308429009249';
$hashtagSearchEndpoint = ENDPOINT_BASE . 'ig_hashtag_search';
$hashtagSearchParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,name',
'q' => $hashtag,
'access_token' => $accessToken
);
$hashtagSearch = makeApiCall($hashtagSearchEndpoint, 'GET', $hashtagSearchParams);
/* To get hashtagID */
/* echo '<pre>';
print_r($hashtagSearch);
die(); */
$hashtagDataEndpoint = ENDPOINT_BASE . $hashtagId;
$hashtagDataParams = array(
'fields' => 'id,name',
'access_token' => $accessToken
);
$hashtagData = makeApiCall($hashtagDataEndpoint, 'GET', $hashtagDataParams);
$hashtagTopMediaEndpoint = ENDPOINT_BASE . $hashtagId . '/top_media';
$hashtagTopMediaParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagTopMedia = makeApiCall($hashtagTopMediaEndpoint, 'GET', $hashtagTopMediaParams);
$topPost = $hashtagTopMedia['data'][0];
$topPost1 = $hashtagTopMedia['data'][1];
$topPost2 = $hashtagTopMedia['data'][3];
/* To get recent data
$hashtagRecentEndpoint = ENDPOINT_BASE . $hashtagId . '/recent_media';
$hashtagRecentParams = array(
'user_id' => $instagramAccountId,
'fields' => 'id,caption,children,comments_count,like_count,media_type,media_url,permalink',
'access_token' => $accessToken
);
$hashtagRecent = makeApiCall($hashtagRecentEndpoint, 'GET', $hashtagRecentParams);
$recentPost = $hashtagRecent['data'][0];
$recentPost2 = $hashtagRecent['data'][1]; */
/* $recentPost3 = $hashtagRecent['data'][2]; */
$return = [$topPost['media_type'], $topPost['media_url'], $topPost1['media_type'], $topPost1['media_url'], $topPost2['media_type'], $topPost2['media_url']];
$jsondata = json_encode($return, JSON_PRETTY_PRINT);
return $jsondata;
I got method in getting the access token and here it is
public $token; //I declare global var to read in every func
public function getToken(){
$key = 'xxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxx';
$data = array(
'key' => 'xxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxx'
);
$payload = json_encode($data);
$ch = curl_init('https://cgi.singmap.com/token?key='.$key.'&secret='.$secret.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Content-Length: ' . strlen($payload))
);
// Submit the POST request
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
$token = $trimmed['access_token'];
curl_close($ch);
$this->token = $token;
}
The token only lasts for 5 minutes to use. But in my other method like this which uses token
public function propertyUnitDetails(){
$unitId = \DB::table('property_unit_list')
->select('projectId','unitId')
->get();
foreach($unitId as $res){
$this->getToken();
$final_token = $this->token;
// dd($final_token);
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($final_token.$request_time);
$pageNo = 1;
$pageSize = 200;
$url = 'https://cgi.singmap.com/unit/queryUnitDetail?request_time='.$request_time.
'&token='.$final_token.'&sign='.$sign.'&projectId='.$res->projectId.'&unitId='.$res->unitId.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
if(empty($trimmed)){
$this->getToken();
$final_token = $this->token;
}
foreach ($trimmed as $data){
$inserts[] = [
'projectId' => $res->projectId,
'stack' => $data['stack'],
'floorPlanId' => $data['floorPlanId'],
'soldBy' => $data['soldBy'],
'transactionPrice' => $data['transactionPrice'],
'type' => $data['type'],
'unitId' => $data['unitId'],
'floorPlanName' => $data['floorPlanName'],
'price1' => $data['price1'],
'price2' => $data['price2'],
'price3' => $data['price3'],
'price4' => $data['price4'],
'custom1' => $data['custom1'],
'custom2' => $data['custom2'],
'custom3' => $data['custom3'],
'custom4' => $data['custom4'],
'direction' => $data['direction'],
'area' => $data['area'],
'buildName' => $data['buildName'],
'unitName' => $data['unitName'],
'buildId' => $data['buildId'],
'bathrooms' => $data['bathrooms'],
'transactionDate' => $data['transactionDate'],
'bedrooms' => $data['bedrooms'],
'purchaseStatus' => $data['purchaseStatus'],
];
}
}
$chuncked = array_chunk($inserts, 10);
foreach($chuncked as $inserts){
\DB::table('property_project_details')->insert($inserts);
}
dd('record inserted');
}
When the function is not completely excecuted or the data is not fully inserted, maybe because it has a large amount of data. It throws an error of datas index is not found or something from the curl response. It is because I can only get the datas based on the token i get manually or declared manually. What I want is that if the token expires, it will run the function getToken() and pass the token to the running function in order to avoid interrupting it.
EDIT:
I added
$this->getToken();
$final_token = $this->token;
in my foreach statement because #user001232 said that in every unitId result query I got, a new token would be generated. But I still got an error every 5 mins that is because i cant get a new token even if i add that function in there.
Here you go, this will work:
<?php
class NameOfYourClass {
public $token;
public function refreshToken()
{
$key = 'xxxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxxxxxxx';
$data = array(
'key' => 'xxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxx'
);
$payload = json_encode($data);
$ch = curl_init('https://cgi.singmap.com/token?key='.$key.'&secret='.$secret.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Content-Length: ' . strlen($payload))
);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
$this->token = $trimmed['access_token'];
curl_close($ch);
}
private function getUnitDetails($res, $attempts = 1)
{
// We only allow 5 attempts to avoid getting into infinite loops
if ($attempts > 5) {
throw new \Exception('Signmap API Issue');
}
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($this->token.$request_time);
$pageNo = 1;
$pageSize = 200;
$url = 'https://cgi.singmap.com/unit/queryUnitDetail?request_time='.$request_time.
'&token='.$this->token.'&sign='.$sign.'&projectId='.$res->projectId.'&unitId='.$res->unitId.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'] ?? null;
// If the response datas is empty, we're assuming it's because of a token error, so we retry
if(empty($trimmed)){
$attempts++;
$this->refreshToken();
return $this->getUnitDetails($res, $attempts);
}
return $trimmed;
}
public function propertyUnitDetails()
{
// Grab all of the units
$unitItds = \DB::table('property_unit_list')->select('projectId','unitId')->get();
foreach($unitId as $res) {
$trimmed = $this->getUnitDetails($res);
foreach ($trimmed as $data){
$inserts[] = [
'projectId' => $res->projectId,
'stack' => $data['stack'],
'floorPlanId' => $data['floorPlanId'],
'soldBy' => $data['soldBy'],
'transactionPrice' => $data['transactionPrice'],
'type' => $data['type'],
'unitId' => $data['unitId'],
'floorPlanName' => $data['floorPlanName'],
'price1' => $data['price1'],
'price2' => $data['price2'],
'price3' => $data['price3'],
'price4' => $data['price4'],
'custom1' => $data['custom1'],
'custom2' => $data['custom2'],
'custom3' => $data['custom3'],
'custom4' => $data['custom4'],
'direction' => $data['direction'],
'area' => $data['area'],
'buildName' => $data['buildName'],
'unitName' => $data['unitName'],
'buildId' => $data['buildId'],
'bathrooms' => $data['bathrooms'],
'transactionDate' => $data['transactionDate'],
'bedrooms' => $data['bedrooms'],
'purchaseStatus' => $data['purchaseStatus'],
];
}
}
$chuncked = array_chunk($inserts, 10);
foreach($chuncked as $inserts){
\DB::table('property_project_details')->insert($inserts);
}
dd('record inserted');
}
}
What if you call the method getToken() everytime you got a projectId in your loop. Its like this
foreach($project_id as $res){
$this->getToken();
$final_token = $this->token;
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($final_token.$request_time);
//and so on ....
In that way. it will get a new token in every projectId. the only drawbacks is it will execute very slowly.
And if it is still got the error replace your code like this. Add a condition if empty
public function propertyBuildings(){
$project_id = \DB::table('project_list')
->select('projectId')
->get();
foreach($project_id as $res){
$this->getToken();
$final_token = $this->token;
$request_time = Carbon::now()->format('YmdHis');
$sign = md5($final_token.$request_time);
$url = 'https://cgi.singmap.com/project/queryBuilding?request_time='.$request_time.
'&token='.$token.'&sign='.$sign.'&projectId='.$res->projectId.'';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$trimmed = $response['datas'];
if(empty($trimmed)){
$this->getToken();
$final_token = $this->token;
}
// return $trimmed;
foreach($trimmed as $data){
$inserts[] = [
'projectId' => $res->projectId,
'buildId' => $data['buildId'],
'buildName' => $data['buildName'],
];
}
}
\DB::table('property_building')->insert($inserts);
dd('Data Inserted');
}
I am new in CURL I need to authenticate user is logged in or not using access token. But how to send x-access-token with post request into header.
I am using. curl library
require __DIR__ . '/vendor/autoload.php';
use \Curl\Curl;
$curl = new Curl();
$curl->post('http://localhost:3011/user/reset-password',array('x-access-token'=>$user['token']), array(
'newPassword' => $_POST['newPassword'],
'confirmPassword' => $_POST['confirmPassword']
));
if ($curl->error) {
$response = array(
'status' => $curl->errorCode,
'message' => $curl->errorMessage,
'response' => $curl->response
);
echo json_encode($response);
} else {
$response = array(
'status' => $curl->httpStatusCode,
'message' => 'Successfylly Login',
'response' => $curl->response
);
echo json_encode($response);
}
You can do this way also.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.abctest.com/abc.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//********************Check these lines for headers*******************
$headers = [
'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
'x-access-token':'sdsdgdsggrtyrtghf'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//************************ END Headers *********************************
$server_output = curl_exec ($ch);
curl_close ($ch);
print $server_output ;
You can use setHeader method in Curl class.
RTFM plz.
require __DIR__ . '/vendor/autoload.php';
use \Curl\Curl;
$curl = new Curl();
// check the following line
$curl->setHeader('x-access-token', 'YOUR-TOKEN-HERE');
$curl->post('http://localhost:3011/user/reset-password',array('x-access-token'=>$user['token']), array(
'newPassword' => $_POST['newPassword'],
'confirmPassword' => $_POST['confirmPassword']
));
if ($curl->error) {
$response = array(
'status' => $curl->errorCode,
'message' => $curl->errorMessage,
'response' => $curl->response
);
echo json_encode($response);
} else {
$response = array(
'status' => $curl->httpStatusCode,
'message' => 'Successfylly Login',
'response' => $curl->response
);
echo json_encode($response);
}
I am using the following api:http://apidocs.mifinity.com/#/doc/2 but its not working??
My API key
$data = array(
'key' => "1234567777"
);
$url = 'https://demo.mifinitypay.com/';
$ch = curl_init($url);
$postString = http_build_query($data, '', '&');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$request = new HttpRequest();
$request->setUrl('https://demo.mifinitypay.com/api/oauth/token');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'postman-token' => '6396dfb7-540b-0e7d-7333-5d0eeff4d606',
'cache-control' => 'no-cache',
'authorization' => 'Basic username:password encoded using Base64',
'x-api-version' => '1',
'accept' => 'application/json',
'content-type' => 'application/x-www-form-urlencoded'
));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array(
'grant_type' => 'client_credentials'
));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
I have a problem with a request post http. The params are correct but I have an error.
This is my code
Route::get('login/linkedin', function()
{
$lk_credentials = Config::get('linkedin.public0');
$provider = new LinkedIn($lk_credentials);
if(!Input::has('code')){
//exit('debug');
$provider->authorize();
}else{
try{
$code = Input::get('code');
if(strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with LinkedIn');
$t = $provider->getAccessToken('authorization_code', array('code' => $code));
}catch(Exception $e){
return 'Unable to get access token';
}
try{
$userDetails = $provider->getUserDetails($t);
$resource = '/v1/people/~:(id,emailAddress,firstName,lastName,pictureUrl,dateOfBirth,location)';
$params = array(
'oauth2_access_token' => $t->accessToken,
'format' => 'json',
);
Session::put('oauth2_access_token', $t->accessToken);session(['oauth2_access_token' => $t->accessToken]);
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
$context = stream_context_create(array('http' => array('method' => 'GET')));
$response = file_get_contents($url, false, $context);
$data = json_decode($response);
Session::put('data', $data);session(['data' => $data]);
}catch(Exception $e){
return 'Unable to get user details';
}
try{
if(count($_POST) > 0){
print_r($_POST);
exit();
}
$params = array(
'grant_type' => 'authorization_code',
'code' => Session::get('oauth2_access_token'),
'redirect_uri' => url('login/linkedin'),
'client_id' => '************',
'client_secret' => '***************',
);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'http://www.linkedin.com/uas/oauth2/accessToken?');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS,$params);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
)
);
$output = curl_exec($c);
if($output === false){
trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING);
exit('Erreur');
}
else{
var_dump($output);
exit('Affiche');
}
curl_close($c);
return redirect('/')->with('data',$data);
}catch(Exception $e){
return 'Unable to get Request Token';
}
}
});
And this is my error :
{"error_description":"missing required parameters,
includes an invalid parameter value, parameter more than once.
: Unable to retrieve access token : authorization code not found",
"error":"invalid_request"}
While building $params array remember that url must be urlencoded, so if your url function doesn't do that, change this line to:
'redirect_uri' => urlencode(url('login/linkedin'))
Then make post string like this:
$params = http_build_query($params);
And remove ? at the end of CURLOPT_URL.
Also you should include CURLOPT_USERAGENT.