Github api Login - get user - api

I have a problem with Github api.
I parse the access_token but when i try to get the user I get the following error:
Warning: file_get_contents(https://api.github.com/user?access_token=mplamplampla): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
When I try to get the contents through address bar in my browser is working!
My code:
//Get the access token
$postdata = http_build_query(
array(
'client_id' => 'mplamplaID',
'client_secret' => 'mplamplaSECRET',
'code' => trim($_GET['code']),
'redirect_uri' => 'http://vlingos.com/github.php'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$vip = file_get_contents('https://github.com/login/oauth/access_token',false,$context);
parse_str($vip);
//Get the User
$json = file_get_contents('https://api.github.com/user?access_token='.$access_token);
if(isset($json) and (is_array($json)===true or is_object($json)===true)){
$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($json, TRUE)),RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
$git_user[$key] = $val;
}
print_r($git_user);
}else{
echo "can't get user";
}
Can someone propose something?
kindest regards

Enable your token is correct. generate new token, refer to:https://help.github.com/articles/creating-an-access-token-for-command-line-use/
test it:
curl https://api.github.com/user?access_token=your token

Related

Shopware - How to get products using App Credentials?

I created App in Shopware and able to get apiKey, secretKey, shopUrl and shopId. I want to get all my products using these credentials.
This is my code
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://shopware.example.com/store-api/product",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Content-Type: application/json",
"sw-access-key: SW234C1LVA010CWHDD34WK1TMW"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$data = json_decode($response, true);
print_r($data);
}
and I am getting error like this
Array
(
[errors] => Array
(
[0] => Array
(
[status] => 412
[code] => FRAMEWORK__ROUTING_SALES_CHANNEL_NOT_FOUND
[title] => Precondition Failed
[detail] => No matching sales channel found.
[meta] => Array
(
[parameters] => Array
(
)
)
)
)
)
When I using API key from settings page API I am able to get products.
But how to use App credentials (App key, secret key, shop URL) and get products
You should have gotten the API key during App registration:
https://developer.shopware.com/docs/guides/plugins/apps/app-base-guide#confirmation-request
Did you try that one? If it does not work for the store API you might want to use the admin API.

Ebay Unsupported API call error upon using GuzzleHttp client v6

I am trying to get sessionid by using ebay Trading API . I am able to get session id successfully by using Curl but as soon as i try to fetch session id via Guzzle Http client, get below error in response from ebay
FailureUnsupported API call.The API call "GeteBayOfficialTime" is
invalid or not supported in this release.2ErrorRequestError18131002
I suppose there's some issues with the way i am using GuzzleHttp client . I am currently using GuzzleHttp v6 and new to this . Below is the code i am using to get session id by calling actionTest function
public function actionTest(){
$requestBody1 = '<?xml version="1.0" encoding="utf-8" ?>';
$requestBody1 .= '<GetSessionIDRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestBody1 .= '<Version>989</Version>';
$requestBody1 .= '<RuName>test_user-TestAs-Geforc-ldlnmtua</RuName>';
$requestBody1 .= '</GetSessionIDRequest>';
$headers = $this->getHeader();
$client = new Client();
$request = new Request('POST','https://api.sandbox.ebay.com/ws/api.dll',$headers,$requestBody1);
$response = $client->send($request);
/*$response = $client->post('https://api.sandbox.ebay.com/ws/api.dll', [
'headers' => $headers,
'body' => $requestBody1
]);*/
echo $response->getBody();die;
}
public function getHeader()
{
$header = array(
'Content-Type: text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL: 989',
'X-EBAY-API-DEV-NAME: a4d749e7-9b22-441e-8406-d3b65d95d41a',
'X-EBAY-API-APP-NAME: TestUs-GeforceI-SBX-345ed4578-10122cfa',
'X-EBAY-API-CERT-NAME: PRD-120145f62955-96aa-4d748-b1df-6bf4',
'X-EBAY-API-CALL-NAME: GetSessionID',
'X-EBAY-API-SITEID: 203',
);
return $header;
}
Plz suggest the possible shortcoming in the way i am making request . I already tried/modified the guzzle request call by referring various reference site and guzzle official doc but error remained same .
You need to pass an associative array of headers as explained in the documentation.
public function getHeader()
{
return [
'Content-Type' => 'text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL' => '989',
'X-EBAY-API-DEV-NAME' => '...',
'X-EBAY-API-APP-NAME' => '...',
'X-EBAY-API-CERT-NAME' => '...',
'X-EBAY-API-CALL-NAME' => '...',
'X-EBAY-API-SITEID' => '203',
];
}
In case you are interested there is an SDK available that simplifies the code. An example of how to call GetSessionID is shown below.
<?php
require __DIR__.'/vendor/autoload.php';
use \DTS\eBaySDK\Trading\Services\TradingService;
use \DTS\eBaySDK\Trading\Types\GetSessionIDRequestType;
$service = new TradingService([
'credentials' => [
'appId' => 'your-sandbox-app-id',
'certId' => 'your-sandbox-cert-id',
'devId' => 'your-sandbox-dev-id'
],
'siteId' => '203',
'apiVersion' => '989',
'sandbox' => true
]);
$request = new GetSessionIDRequestType();
$request->RuName = '...';
$response = $service->getSessionID($request);
echo $response->SessionID;

API returning 400 Bad Request response

I have built an API and an application that uses that API. Everything was working but now, for some reason, I get a 400 Bad Request response. I am not sure if I changed something in the code so I wanted to double check it was correct.
So my API call is this
$client = new GuzzleHttp\Client();
$jsonData = json_encode($data);
$req = $client->request('POST', 'https://someurl.com/api/v1/createProject', [
'body' => $jsonData,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($jsonData),
]
]);
$output = $req->getBody()->getContents();
The API has a route set up correctly which uses post. The function it calls is correct, and I have changed it for testing to simply return
return response()->json(["Success", 200]);
When I test the API out within Postman, I can see that Success is returned. When I test the API within the other application I have built, I dont even see a POST request within the console, I am just displayed a Laravel error 400 Bad Request.
What could be the cause of this issue?
Thanks
Update
I have changed the request to this
$data= json_encode($data);
$req = $client->post('https://someurl.com/api/v1/createProject', [
'body' => $data
]);
If I output $data after it has been encoded, I get something like this
{
"projectName":"New Project",
"clientName":"Test Client",
}
Within the controller function of the API that is being called, I simply do
return response()->json(['name' => $request->input('clientName')]);
The 400 error has now gone, but I now get null returned to me
{#326 ▼
+"name": null
}
Request is being injected into the function as it should be. Should I be returning the data in a different way?
Thanks
Probably you did $ composer update and Guzzle updated.
So if you are using newest Guzzle (guzzlehttp/guzzle (6.2.2)) you do POST request:
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data
]);
You do not need to specify headers.
To read response you do following:
$json_response = json_decode($response->getBody());
My full example (in routes file web.php routes.php)
Route::get('smith', function () {
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data,
]);
$code = $response->getStatusCode();
$result = json_decode($response->getBody());
dd($code, $result);
});
Route::post('neo', function (\Illuminate\Http\Request $request) {
return response()->json(['name' => $request->input('name')]);
});
or you could use following (shortened), but code above is "shorter"
$json_data = json_encode(['name' => 'Agent Smith']);
$response = $client->post('http://example.dev/neo', [
'body' => $json_data,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($json_data),
]
]);
note: If you are running PHP5.6, change always_populate_raw_post_data to -1 (or uncomment the line) in php.ini and restart your server. Read more here.
In my case I was using public IP address in BASE_URL while I should have been using the private IP. From mac you can get your IP by going into system preferences -> network.
This is with Android + Laravel (API)

response from google "Oauth 2.0 for login" missing email after authorization

I am attempting implement Oauth 2.0 for login, but the following code isn't producing a consistent response. why? Email is present "sometimes" but I cannot find anything here that would explain the varied response. The goal here is that I could use the email to locate users in my system.
<?php
// http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
require_once 'sites/all/modules/schoology_core/s_support/JWT.php';
// app info (see google api console for creds)
$google_client_id = '';
$google_secret = '';
$google_redirect_uri = '';
$google_is_auth_response = (isset($_GET['code']) || isset($_GET['error']));
// construct auth url used to redirect user to google login form
$auth_url = 'https://accounts.google.com/o/oauth2/auth?';
$auth_url .= 'client_id=' . $google_client_id . '&';
$auth_url .= 'response_type=code&';
$auth_url .= 'scope=openid%20email&';
$auth_url .= 'redirect_uri=' . $google_redirect_uri . '&';
$auth_url .= 'state=' . uniqid();
$auth_link = '<br>'. $auth_url .'';
// send user to google login form
if(!$google_is_auth_response) {
print $auth_link;
exit;
}
// handle response
if($_GET['error']) {
print 'Oauth2 response error=' . $_GET['error'];
}
else {
// exchange one-time authorization code for access token and ID token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://accounts.google.com/o/oauth2/token',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => array(
'code' => $_GET['code'],
'client_id' => $google_client_id,
'client_secret' => $google_secret,
'redirect_uri' => $google_redirect_uri,
'grant_type' => 'authorization_code',
)
));
$response = curl_exec($curl);
$responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// decode response and id token to retrieve user's email
$response = json_decode($response);
$jwt_id_token = JWT::decode($response->id_token, NULL, FALSE);
$response_info = print_r(array(
'auth_code' => $_GET['code'],
'response_code' => $responseCode,
'response_decoded' => $response,
'id_token' => $jwt_id_token,
'email_is_not_preset' => $jwt_id_token->email ? 'Y' : 'N'
), TRUE);
print '<pre>' . $response_info . '</pre>';
}

Linkedin: Permissions request not working

When i try to request additional permissions from linkedin i do not get any permissions list in the dialog except for the basic permisiions. Could any1 point me to the solution. I tried urlencoding the permissions but still not getting any response. Here is my code: I am calling this function on click of 'Signup with Linkedin' button.
public function linkedinaccessAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$scope = 'r_basicprofile+r_emailaddress+r_network+r_contactinfo';
$options = array(
'version' => '1.0',
'siteUrl' => 'http://localhost/project/development/',
'callbackUrl' => 'http://localhost/project/development/signup/linkedinaccess',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken?scope=' . $scope,
'userAuthorizationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'myconsumerkey',
'consumerSecret' => 'myconsumersecret'
);
$consumer = new Zend_Oauth_Consumer( $options );
if (!isset($_SESSION ['LINKEDIN_ACCESS_TOKEN'])){
if(! empty ( $_GET )){
//consumer = new Zend_Oauth_Consumer( $options );
$accessToken = $consumer->getAccessToken ( $_GET, unserialize ( $_SESSION ['LINKEDIN_REQUEST_TOKEN'] ) );
echo $accessToken;
$_SESSION ['LINKEDIN_ACCESS_TOKEN'] = serialize ( $accessToken );
}else{
$requestToken = $consumer->getRequestToken();
$_SESSION ['LINKEDIN_REQUEST_TOKEN'] = serialize ( $requestToken );
$consumer->redirect();
}
}else{
$accessToken = unserialize ( $_SESSION ['LINKEDIN_ACCESS_TOKEN'] );
// Use HTTP Client with built-in OAuth request handling
$client = $accessToken->getHttpClient($options);
// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();
// Get the XML containing User's Profile
$content = $response->getBody();
print_r($content);
}
}
Thank you.
After rigorous searching finally got the solution from this Linkedin Post
Need to request linkedin permissions as a part of getRequestToken Call:
$requestToken = $consumer->getRequestToken(array('scope' =>'r_emailaddress'));