Here is my controller
<?php
class Linkedin extends CI_Controller
{
public function __construct ()
{
parent::__construct();
}
public function login ()
{
redirect('https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=client_id&redirect_uri=domain');
}
public function index ()
{
$state = $_GET['state'];
if($state == '987654321')
{
$authorization_code = $_GET['code'];
// Initiating curl
$curl = curl_init();
// Here we exchanging 'authorization code' to access token
// Access token is used to get userdetails
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code='.$authorization_code.'&client_id=client_id&client_secret=app_secret&redirect_uri=domain',
CURLOPT_USERAGENT => 'To get access token',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array()
));
// Send the request & save response to $resp
$response = curl_exec($curl);
$response = json_decode($response);
curl_close($curl);
}
$curl_req = curl_init();
curl_setopt_array($curl_req, array(
CURLOPT_HTTPHEADER => array('Connection : Keep-Alive','Authorization: Bearer '.$response->access_token.''),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://api.linkedin.com/v1/people/~',
CURLOPT_USERAGENT => 'user details',
));
$resp = curl_exec($curl_req);
echo $resp;
curl_close($curl_req);
}
}
I did this from source linkedin docs . Well all seems working fine except the get_details function.I cannot get the user profile details,it returns error whenever I try after login
{
"errorCode": 0,
"message": "ssl required",
"requestId": "HLDS2BCBW4",
"status": 401,
"timestamp": 1479715273015
}
Just changed the line CURLOPT_URL => 'http://api.linkedin.com/v1/people/~' to CURLOPT_URL => 'https://api.linkedin.com/v1/people/~?format=json' and it works
Related
I want to get an access token to call to Google Directory API. I have seen several posts with PHP Curl code, but everytime there has to be a human action to permit access before you get the access token. Is there a way to make a CURL request and get the access token directly?
This is my code so far:
define("CALLBACK_URL", "http://localhost/los/index");
define("AUTH_URL", "https://accounts.google.com/o/oauth2/auth");
define("ACCESS_TOKEN_URL", "https://oauth2.googleapis.com/token");
define("CLIENT_ID", "**.apps.googleusercontent.com");
define("CLIENT_SECRET", "**");
define("SCOPE", "https://www.googleapis.com/auth/admin.directory.device.chromeos");
function getToken(){
$curl = curl_init();
$params = array(
CURLOPT_URL =>
ACCESS_TOKEN_URL."?"."&grant_type=authorization_code"."&client_id=".
CLIENT_ID."&client_secret=". CLIENT_SECRET."&redirect_uri=". CALLBACK_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_ENCODING => '',
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_NOBODY => false,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Content-Length: 0",
"content-type: application/x-www-form-urlencoded",
"accept: *",
"accept-encoding: gzip, deflate",
),
);
curl_setopt_array($curl, $params);
$response = curl_exec($curl);
$err = curl_error($curl);
echo $response;
curl_close($curl);
if ($err) {
echo "cURL Error #01: " . $err;
} else {
$response = json_decode($response, true);
if(array_key_exists("access_token", $response)) return $response;
if(array_key_exists("error", $response)) echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
}
}
When I run it I get this error message:
{ "error": "invalid_request", "error_description": "Missing required parameter: code" }Missing required parameter: codec
I've just been through a similar problem with using PHP cURL to get an access token from the http code returned by the Google API after the user authorizes the consent screen. Here's my long-winded answer:
From least to most important: you should start by fixing the brackets after your if conditions:
if (array_key_exists("access_token", $response)) {
return $response
} elseif (array_key_exists("error", $response)) {
echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
}
The error message "Missing required parameter: code" appears because you need to post the code that was returned in the url after the client authorizes your app. You'd do that by doing something like:
CURLOPT_URL => ACCESS_TOKEN_URL."?"."&code=".$_GET['code']."&grant_type=authorization_code"."&client_id=".CLIENT_ID."&client_secret=". CLIENT_SECRET."&redirect_uri=".CALLBACK_URL,
To make it more semantic you'd define the $authorization code variable before that:
$authorizationCode = $_GET['code'];
Lastly, the most important part is that to get an Access Token from Google you need to used the cURL post method as shown in the documentation:
https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code
You can do that with PHP cURL with this command:
curl_setopt( $ch, CURLOPT_POST, 1);
But then you need to break your URL into two parts: the host and the fields to be posted. To make it easier to read, you can setup your endpoint and the fields into variables:
$endpoint = 'https://oauth2.googleapis.com/token';
$fieldsToPost = array(
// params for the endpoint
'code' => $authorizationCode, //being that $authorizationCode = $_GET['code'];
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'redirect_uri' => CALLBACK_URL,
'grant_type' => 'authorization_code',
);
Then you can use the $enpoint to set the url and http_build_query() to set up your fields. In the end, adapting your code to the code that worked for me would look something like this:
function getToken() {
$endpoint = 'https://oauth2.googleapis.com/token';
$fieldsToPost = array(
// params for the endpoint
'code' => $authorizationCode, //being that $authorizationCode = $_GET['code'];
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'redirect_uri' => CALLBACK_URL,
'grant_type' => 'authorization_code',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $endpoint);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fieldsToPost));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
// get curl response, json decode it, and close curl
$googleResponse = curl_exec($curl);
$curl_error = curl_errno($curl);
$googleResponse = json_decode( $googleResponse, TRUE );
curl_close( $curl );
return array( // return response data
'url' => $endpoint . '?' . http_build_query( $params ),
'endpoint' => $endpoint,
'params' => $params,
'has_errors' => isset( $googleResponse['error'] ) ? TRUE : FALSE, // b oolean for if an error occured
'error_message' => isset( $googleResponse['error'] ) ? $googleResponse['error']['message'] : '', // error message
'curl_error' => $curl_error, //curl_errno result
'google_response' => $googleResponse // actual response from the call
);
}
To check the response you can use the following print function to see the response:
if (isset($_GET['code'])) {
$response = getToken();
echo '<pre>';
print_r($response);
die();
}
I know it's been a long time and you've probably found a workaround but I hope this is still useful for future projects. Cheers!
I've been trying to send a message to my server for a few hours now and failing to do so.
I can receive certain data but i cannot send any message and I'm wondering if i am doing something wrong.
This is my current attempt:
<?php
class Discord {
public static $instance;
public static $api = 'https://discordapp.com/api/v6/';
public static $auth = 'Authorization: Bot ' . config['bot_token'];
private static function generateInstance($request_url, $fields) {
self::$instance = curl_init();
curl_setopt_array(self::$instance, array(
CURLOPT_URL => $request_url,
CURLOPT_HTTPHEADER => [self::$auth, 'Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POSTFIELDS => $fields
));
$response = curl_exec(self::$instance);
curl_close(self::$instance);
return $response;
}
public static function sendMessage() {
return self::generateInstance(self::$api . '/channels/' . intval(632172270751711247) . '/messages', [
'content' => "Hello"
]);
}
}
The response being:
string(42) "{"message": "Unauthorized", "code": 40001}"
I'm setting new fitur Login API in my website using cUrl.
When I run in Postman, is working (screnshoot 2). but when i run in my website using cUrl is not working and still loading. if i not set timeout, it will continue to load until infinite time like in screnshoot 1.
image 1 : when i run in my website
image 2 : when i run in Postman
This is my code
Login Controller for proses login from API/cUrl Request
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
return response()->json(['result' => true, 'message' => "heyho" ], 200);
// $token = $user->createToken('nApp')->accessToken;
// return response()->json(['result' => true, 'message' => $token ], $this->successStatus);
} else {
return response()->json(['result'=> false, 'message' => 'Unauthorised'], 401);
}
}
This is my code cUrl Process/Request.
public function tes()
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "8001",
CURLOPT_URL => "http://localhost:8001/api/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\email#gmail.com\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\bbbbb\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"postman-token: 3546ebed-2016-df32-6d9d-91cdfd43066a"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
// return url('/')."/api/login";
}
Your request is "POST" then how you can see the result in web page
Only "GET" request only show the results on the web page
"GET" : In this case we can pass the parameter in the url
like : https//:localhost:8000/api/user/1
"POST" : In this case we pass the body in the request body so we need postman to pass the request body"
For more info you can check https://www.w3schools.com/tags/ref_httpmethods.asp
Experimenting with webapp with Spotify API. Satisfied that all data settings on Spotify Developer site OK (client_id, client_secret etc).
When I run the following in the console...
curl -H "Authorization: Bearer <the actual access token>" https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V
... it works perfectly. Even running the following url directly in the browser works:
https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V?access_token=<the actual access token>
I've tried tagging on the access token to the url in the method below, but no luck. If I try to use the access token in the header and the url, I get an error telling me to use one or the other.
<?php
session_start();
class SpotifyClientCredentials
{
public $url = 'https://accounts.spotify.com/api/token';
public $client_id = '<the client id>';
public $client_secret = '<the client secret>';
public $token = false;
public function __construct()
{
if(isset($_SESSION['token'])) $this->token = $_SESSION['token'];
}
public function connect()
{
$enc = base64_encode($this->client_id. ':' . $this->client_secret);
$header = "Authorization: Basic $enc";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $this->url,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header],
CURLOPT_POSTFIELDS => 'grant_type=client_credentials'
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result,true);
$this->token = $data['access_token'];
$_SESSION['token'] = $this->token;
}
curl_close($ch);
}
public function request($requestUrl)
{
if(!$this->token) $this->connect();
$header = "Authorization: Bearer {$this->token}";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $requestUrl,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header]
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result, true);
print_r($data);
}
curl_close($ch);
}
}
$spfy = new SpotifyClientCredentials;
$spfy->request('https://api.spotify.com/v1/albums/4aawyAB9vmqN3uQ7FjRGTy');
Getting rid of CURLOPT_POST => true, gives an 502 Bad Gateway.
I get no response / output whatsoever with the code, as is, above.
As mentioned, tagging on the access token to the requestUrl:
CURLOPT_URL => $requestUrl . '?access_token=' . $this->token,
gives the following curl response:
Array ( [error] => Array ( [status] => 400 [message] => Must not use more than one method for including an access token ) )
If I then comment out the CURLOPT_HTTPHEADER, I once again get no response.
The access token seeems valid, as when I don't include it, I get an error message. Truly at a loss - any help gratefully appreciated.
I'm trying to obtain my "long lived access token" using CURL/PHP but I'm receiving the error "Missing parameters for client_id, client_secret, code, grant_type, redirect_uri".
The URL I'm calling is where you can clearly see the parameters I'm trying to pass in!
https://api.surveymonkey.net/oauth/token?client_secret='.urlencode($client_secret).'&code='.urlencode($short_token).'&redirect_uri='.urlencode($redirect_url).'&client_id='.urlencode($client_id).'&grant_type=authorization_code
I'm also using the content-type of "application/x-www-form-urlencoded" as per the docs (see below).
My CURL request:
function survey_monkey_curl_request($url, $params=[], $request_type = 'get', $access_token) {
print_r($url);
$ch = curl_init();
$headers = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: bearer " .$access_token
];
$opts = [
CURLOPT_URL => $url,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => 0,
];
if ($request_type == 'post') {
$opts[CURLOPT_POST] = 1;
//$opts[CURLOPT_POSTFIELDS] = json_encode($params);
}
if ($request_type == 'patch') {
$opts[CURLOPT_CUSTOMREQUEST] = "PATCH";
$opts[CURLOPT_POSTFIELDS] = json_encode($params);
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
curl_close($ch);
throw new Exception(curl_error($ch));
}
curl_close($ch);
return $result;
}
Where am I going wrong?
Straight from the documentation it looks like to get the long-lived token you need to post your fields:
//Exchange for long-lived token
curl -i -X POST https://api.surveymonkey.net/oauth/token -d \
"client_secret=YOUR_CLIENT_SECRET \
&code=AUTH_CODE \
&redirect_uri=YOUR_REDIRECT_URI \
&client_id=YOUR_CLIENT_ID \
&grant_type=authorization_code"
https://developer.surveymonkey.com/api/v3/?shell#new-authentication
When you append your parameters onto your url you are sending then as GET request paramters
You need to put your data string into CURL POSTFIELDS and do not json encode
The PHP Answer
<?php
$ch = curl_init();
$data = [
'client_secret' => $YOUR_CLIENT_SECRET,
'code' => $AUTH_CODE,
'redirect_url' => $YOUR_REDIRECT_URI,
'client_id' => $YOUR_CLIENT_ID,
'grant_type' => 'authorization_code'
];//set your data as an array
$headers = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: bearer " . $access_token
];
$opts = [
CURLOPT_URL => $url,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => 0,
];
if ($request_type == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = http_build_query($data);// this will build your data string from the array
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
curl_close($ch);
return $result;