yii2 blocking api call and giving failed to open stream: Connection timed - api

I need to call a private api in my app. the call works fine using php script.php.
However, when i copy the same php code into an action of a yii controller it gives me an error
failed to open stream: Connection timed
i tried removing the behaviors and other configurations to have a basic yii environment
anyone has an idea why this is happening?
here is some code
public function actionInfo() {
$url = "private url";
$data = array();
$data['function'] = "Getinfo";
$data['login'] = "login";
$data['password'] = "password";
$data['input'] = "data";
$post = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded",
'method' => "POST",
'content' => $post,
),
);
$context = stream_context_create($options);
$resultat = "";
if (!$resultat = file_get_contents($url, false, $context)) {
$resultat = "Echec de l'envoi de la requête";
}
$resultat = json_decode($resultat);
print_r($resultat);
echo "\r\n";
this code works fine outside yii but in this action it does not!!!!

it was a server configuration the firewall was blocking my id on the api side

Related

Automatic Authentication using Grafana API

In my web application, I want to provide the ability to pass authenticated users from my dashboard across to Grafana.
Once a user logged in my dashboard using credentials, a link to Grafana Dashboard will be displayed on my application. When user clicks that link, he/she will be redirected to Grafana page and automatically log in without displaying the Grafana login page. I don't want my users must encounter a second login screen, where they will be confused as to what username/password to enter.
I've followed Automatic login to grafana from web application, Auto login to grafana dashboard, Auto login to grafana from Web application using credentials or token
and Automatic login by token url, but no luck. I couldn't find appropriate & clean solution.
I'm using Grafana v6.2.5 installed on Ubuntu Server 18.04.
How can I implement it? Any help would be appreciated.
Server Details: Ubuntu Server 18.04, Apache 2.4.29
After some digging, I've found a workaround using Grafana's Generic OAuth Authentication.
Step 1: Create files with the following code in it.
GrafanaOAuth.php:
<?php
declare(strict_types=1);
class GrafanaOAuth
{
protected $user;
/**
* Create a new GrafanaOAuth instance.
* #param array $user
* #return void
*/
public function __construct(array $user)
{
$this->user = $user;
}
/**
* Redirect to authentication URL.
* #param string $state
* #return void
*/
public function auth(string $state): void
{
$state = urlencode($state);
$url = "http://localhost:3000/login/generic_oauth?state={$state}&code=cc536d98d27750394a87ab9d057016e636a8ac31";
header("Location: {$url}");
}
/**
* User access token.
* #return void
*/
public function token(): void
{
$token = [
'access_token' => $this->user['access_token'],
'token_type' => 'Bearer',
'expiry_in' => '1566172800', // 20.08.2019
'refresh_token' => $this->user['refresh_token']
];
echo json_encode($token);
}
/**
* User credentials.
* #return void
*/
public function user(): void
{
$user = [
'username' => $this->user['username'],
'email' => $this->user['email']
];
echo json_encode($user);
}
}
oauth/auth.php:
<?php
declare(strict_types=1);
require __DIR__ . '/../GrafanaOAuth.php';
/**
* Fetch the details of Grafana user from your database.
*/
$user = [
'username' => 'nbayramberdiyev',
'email' => 'nbayramberdiyev#outlook.com',
'dasboard_id' => 'oNNhAtdWz',
'access_token' => md5(uniqid('nbayramberdiyev', true)),
'refresh_token' => md5(uniqid('nbayramberdiyev', true))
];
(new GrafanaOAuth($user))->auth($_GET['state']);
oauth/token.php:
<?php
declare(strict_types=1);
header('Content-Type: application/json');
require __DIR__ . '/../GrafanaOAuth.php';
/**
* Fetch the details of Grafana user from your database.
*/
$user = [
'username' => 'nbayramberdiyev',
'email' => 'nbayramberdiyev#outlook.com',
'dasboard_id' => 'oNNhAtdWz',
'access_token' => md5(uniqid('nbayramberdiyev', true)),
'refresh_token' => md5(uniqid('nbayramberdiyev', true))
];
(new GrafanaOAuth($user))->token();
oauth/user.php:
<?php
declare(strict_types=1);
header('Content-Type: application/json');
require __DIR__ . '/../GrafanaOAuth.php';
/**
* Fetch the details of Grafana user from your database.
*/
$user = [
'username' => 'nbayramberdiyev',
'email' => 'nbayramberdiyev#outlook.com',
'dasboard_id' => 'oNNhAtdWz',
'access_token' => md5(uniqid('nbayramberdiyev', true)),
'refresh_token' => md5(uniqid('nbayramberdiyev', true))
];
(new GrafanaOAuth($user))->user();
custom.js:
$(function() {
'use strict';
if (location.pathname === '/login') {
location.href = $('a.btn-service--oauth').attr('href');
}
});
Step 2: Edit Grafana configuration file which is located at /etc/grafana/grafana.ini on Ubuntu / Debian, /usr/local/etc/grafana/grafana.ini on MAC, <GRAFANA_PROJECT_FOLDER>/conf/custom.ini on Windows.
Uncomment these lines and enter your client_id, client_secret, auth_url, token_url, api_url:
#################################### Generic OAuth ##########################
[auth.generic_oauth]
;enabled = true
;name = OAuth
;allow_sign_up = false
;client_id = some_id
;client_secret = some_secret
;scopes = user:email,read:org
;auth_url =
;token_url =
;api_url =
Like so:
#################################### Generic OAuth ##########################
[auth.generic_oauth]
enabled = true
name = OAuth
allow_sign_up = false
client_id = YOUR_APP_CLIENT_ID
client_secret = YOUR_APP_CLIENT_SECRET
scopes = user:email,read:org
auth_url = http://foo.bar/oauth/auth.php
token_url = http://foo.bar/oauth/token.php
api_url = http://foo.bar/oauth/user.php
Step 3: Place custom.js in /usr/share/grafana/public/build/index.html file (Ubuntu / Debian) at the bottom of <body> tag.
Step 4: Restart Grafana server.
sudo service grafana-server restart (Ubuntu / Debian)
brew services restart grafana (MAC)
For the example and detailed explanation, have a look at my Github repo.

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)

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'));

Authentication useing PHP SDK not working

I am having some trouble with authentication using PHP SDK. I have downloaded "facebook.php" and "base_facebook.php" from github.
Below is the code I am useing but cant figure out where I am going wrong (new to all this).
<?php
require 'facebook.php' ;
$fbconfig['appid' ] = xxx;
$fbconfig['secret'] = "xxxx";
$fbconfig['baseurl'] = "xxx";
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'xxx'
);
$loginUrl = $facebook->getLoginUrl($params​);
$logoutUrl = $facebook->getLogoutUrl();
if(!$user)
{
echo "<P>You need to log into FB</p>\n";
exit();
}
else
{
echo "<p style=\"margin-bottom:20px;\">​<a href=\"{$logoutUrl}\">Logout</​p>\n";
}
?>
Any suggestions much appriciated :)
Based on this site, it looks like you need to explicitly construct your own Facebook object:
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);