Laravel 5.0 Socialite with Wunderlist - php

I've created a custom Provider for Laravel Socialite.
The authentication part is going well until i'll try to call the user method.
Not sure what's going wrong.
Method documentation at wunderlist
My code:
/**
* {#inheritdoc}
*/
protected function getUserByToken($token)
{
$response = $this->getHttpClient()->get('https://a.wunderlist.com/api/v1/users', [
'X-Access-Token: ' . $token . ' X-Client-ID: ' . $this->clientId
]);
return json_decode($response->getBody(), true);
}
I get the following error:
InvalidArgumentException in MessageFactory.php line 202:
allow_redirects must be true, false, or array
Do i miss things in the options array?
Jos

Actually socialite is not supposed to do something like this. But instead you may use Guzzle. There is a good video at laracasts. Just search for Easy HTTP Requests. And here's the code that you may use for guzzle:
$client = new \Guzzle\Service\Client('a.wunderlist.com/api/v1/');
$response = $client->get('user')->send();
// If you want this response in array:
$user = $response->json();
Just read the docs here.

When using this with straight forward curl there is no issue.
As far as i can see the issue lies in the headers i'll parse.
The following solution is something i can live with, although it's not perfect.
$headers = array();
$headers[] = 'X-Access-Token: ' . $token;
$headers[] = 'X-Client-ID: ' . $this->clientId;
$response = $this->getHttpClient()->get('a.wunderlist.com/api/v1/user', [
'config' => [
'curl' => [
CURLOPT_POST => 0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false
]
]
]);
return json_decode($response->getBody(), true);

Related

Azure Marketplace SaaS fulfilment API- resolving subscription - PHP

I am trying to resolve an azure marketplace subscription using the azure fulfilment api. I have followed the instructions on the Microsoft's SaaS fulfilment api's docs but I am not able to resolve the subscription using PHP.
I am able to get access_token and incidentally I am able to use the token and and use this together with the purchase identification token i get from azure portal when the subscriber is re-directed to the SaaS landing page, to get a successful json response when using postman.
I cannot achieve the same success when using PHP. I get a 403 error - Authorization is missing, incorrect or invalid. I am thinking that the query string bit of authorization parameter is malformed. This has nothing to do with privileges or permissions as I am able to get a successful output on Postman. Here is the code
<?php
use Microsoft\Graph\Graph;
use Microsoft\Graph\Http;
use Microsoft\Graph\Model;
use GuzzleHttp\Client;
class GraphHelper {
private static Client $tokenClient;
private static Client $tokenWebClient;
private static string $clientId = '';
private static string $tenantId = '';
private static string $clientSec = '';
private static string $graphUserScopes = '';
private static Graph $userClient;
private static string $userToken;
private static string $resolveToken;
private static string $subToken= '';
public static function initializeGraphForUserAuth(): void {
GraphHelper::$tokenClient = new Client();
GraphHelper::$clientId = $_ENV['CLIENT_ID'];
GraphHelper::$clientSec = $_ENV['CLIENT_SECRET'];
GraphHelper::$tenantId = $_ENV['TENANT_ID'];
GraphHelper::$graphUserScopes = $_ENV['GRAPH_USER_SCOPES'];
GraphHelper::$userClient = new Graph();
}
public static function getUserToken(): void {
//getting the access token
$accessCodeRequestUrl = 'https://login.microsoftonline.com/'.GraphHelper::$tenantId.'/oauth2/token';
$tokenRequestUrl = 'https://marketplaceapi.microsoft.com/api/saas/subscriptions/resolve?api-version=2018-08-31';
$subToken = $_SESSION['subToken'];
$tokenResponse = GraphHelper::$tokenClient->post($accessCodeRequestUrl, [
'form_params' => [
'client_id' => GraphHelper::$clientId,
'grant_type' => 'client_credentials',
'client_secret' => GraphHelper::$clientSec,
'resource' => '20e940b3-4c77-4b0b-9a53-9e16a1b010a7'
],
// These options are needed to enable getting
// the response body from a 4xx response
'http_errors' => false,
'curl' => [
CURLOPT_FAILONERROR => false
]
]);
if ($tokenResponse->getStatusCode() == 200) {
// Return the access_token
$responseBody = json_decode($tokenResponse->getBody()->getContents());
GraphHelper::$resolveToken = $responseBody->access_token;
$resolveAccessToken= $responseBody->access_token;
} else if ($tokenResponse->getStatusCode() == 400) {
// Check the error in the response body
$responseBody = json_decode($tokenResponse->getBody()->getContents());
if (isset($responseBody->error)) {
$error = $responseBody->error;
// authorization_pending means we should keep polling
if (strcmp($error, 'authorization_pending') != 0) {
throw new Exception('Token endpoint returned '.$error, 100);
}
}
}
//resolving the subscription
$resolveResponse = GraphHelper::$tokenClient->post($tokenRequestUrl, [
'form_params' => [
'content-type' => 'application/json',
'authorization' => 'Bearer '.$resolveAccessToken,
'x-ms-marketplace-token'=> $subToken
],
// These options are needed to enable getting
// the response body from a 4xx response
'http_errors' => false,
'curl' => [
CURLOPT_FAILONERROR => false
]
]);
//test whether there is a reponse
return $resolveResponse->getStatusCode(); // this returns a 403 - Authorization is missing, incorrect or invalid.
}
}
?>
I figured out that I needed to use cUrl for option to include authorization and other headers. Postman did this automatically hence the reason I was able to get results with postman and not with PHP. Eventually this code did it for me.
$subToken = rawurldecode($_SESSION['subToken']);
$ch = curl_init ();
curl_setopt ($ch, CURLOPT_URL, $tokenRequestUrl);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.GraphHelper::$resolveToken,
'Content-type: application/json',
'X-ms-marketplace-token:'. $subToken));
curl_setopt($ch, CURLOPT_POST, true);
$results = json_decode (curl_exec ($ch), 1);
if (array_key_exists ('error', $results)){
echo ($results['error']);
die();
}
curl_close($ch);
return $results['subscriptionName'] ;
I found out that the endpoint was not accepting a get request. It threw an error of Subscription resolve not found","target":"subscriptionId","code":"EntityNotFound . However including a post option corrected that and no error was thrown after this. Again when decoding the token from the url - don't use urldecode() use rawurldecode () instead.

How to pass arguments to the PUT request in codeigniter?

I am using codeigniter-3, i have to update the data but the API is extrenal API .i am using Guzzle class to contact with that api it's working fine but it's not updating the data because it's not taking the data ,can you tell me how to pass the arguments or body to the curl request..?
library
public function putcurl($url,$headers,$args){
$client = new GuzzleHttp\Client();
$response = $client->request('PUT',$url,['headers' => $headers],['body'=>$args]);
$body = $response->getBody();
$arr_body = json_decode($body);
return ($arr_body);
}
controller.php
$url = $this->config->item('url')['editstation'].$id;
$headers=[
'Authorization' => 'Basic xxxxxxxxxxxxxx',
'Content-Type' => ' application/json',
'Cookie' =>'ci_session=3e7c29f86fd6b8e738d8caefc37fa5b61e3b9ed0',
'x-api-key' => 'test#123',
];
$res = $this->customcurls->putcurl($url,$headers,$args);

Request header not set in test

I have a test which is trying to login and get details. I need to pass a bearer token in request header for this operation. Please see the below code. I could see that the header seldom has the headers that I set. Can anyone give me a pointer to fix this issue?
I am using Laravel 7.2.2, PHP 7.4,
And I am running php artisan test
Code:
public function a_user_can_get_details()
{
$this->create_user();
$response = $this->json('POST',
'/api/login',
[
"email" => "john.doe#example.com",
"password" => "john123"
]);
$response->assertSuccessful();
$token = Str::replaceLast('"', '', Str::replaceFirst('"', '', $response->getContent()));
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $token
];
$response = $this->withHeaders($headers)
->get('api/user');
$response->assertSuccessful();
$this->assertCount(1, User::all());
}
And here is the error I am getting. Actually, the test must pass. That is the right user name and password:
Response status code [403] is not a successful status code. Failed asserting that false is true.
at tests/Feature/UserTest.php:141
137|
138| $response = $this->withHeaders($headers)
139| ->get('api/user');
140|
> 141| $response->assertSuccessful();
142| $this->assertCount(1, User::all());
143|
144| }
145|
I solved this issue.
Cause: I had added a middleware condition in Spatie Permissions to check for a permission for that specific route. I had to remove that to get this working.
Instead of that, I now, check the logged in status of the user. So that the route could be hit and needed checks are done inside the route.
Thanks all for the questions/comments which helped me to solve this.

Convert the curl example to Requests util usage

I use the Requests for http request:
I also package it to a util function:
function http_util($url, $params, $add_headers = null, $base_url = null ){
$headers = array('Accept'=>'application/json');
if($add_headers){
$headers = array_merge($headers, $add_headers);
}
if($base_url) {
$url = $base_url . $url;
}
$request = Requests::post($url, $headers, $params);
return $request;
}
but I found, such as the curl example:
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
if the curl example convert to use my http_util, how to use? I am not sure whether my http_util will have more optimize action. and how to use the http_util request the curl example?
You cant use it as-is you'll need to add the $options param as noted in the docs: http://requests.ryanmccue.info/docs/authentication.html
The "util" function is simply setting a content Accept header. Not worth writing a function for that.
$result = Requests::post('http://localhost:8000/o/token' [
// headers
'Accept' => 'application/json'
], [
// data
'grant_type' => 'password',
'username' => '<user_name>',
'password' => '<password>',
], [
// options
'auth' => new Requests_Auth_Basic(['<client_id>', '<client_secret>'])
]);

php google api contacts 403 in php, working with postman

I want to query the google rest api endpoint to get user contacts:
public static function getContacts(string $token) {
$url = "https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=999999";
$opts = [
"http" => [
"method" => "GET",
"header" => "Authorization: Bearer {$token}"
]
];
$response = file_get_contents($url, false, stream_context_create($opts));
$contacts = json_decode($response);
return $contacts;
}
However, the request returns 403 even thought the token is valid and the request works when sending it via Postman.
Use curl to call api. i think it will work fine there.

Categories