How to integrate PowerBI in symfony4 - symfony

I want to integrate an Advanced statistics in my project symfony 4
so i decide to use PowerBI ( if you have an alternative please let me know),
my question is how to integrate it in my local project symfony4 and in relation with my database MySQL

Untill now , there no Symfony bundle for power bi , but instead you can use :
the adevait/power-bi
In case you don't find options you are looking for , you can using the native power bi rest api
You need to create an account and manage it by creating your dataset etc ...
Requirement :
GuzzleHttp
The point here is to create for example a service that manage calling the api :
example for authentication :
try {
/** #var GuzzleHttp\Client $client **/
$response = $client->post(
'https://login.windows.net/<tenant-id>/oauth2/token',
[
"headers" => [
"Accept" => "application/json"
],
'form_params' => [
'resource' => 'https://analysis.windows.net/powerbi/api',
'client_id' => $this->clientId,
'client_secret' => $this->secret,
'grant_type' => 'password',
'username' => $this->username,
'password' => $this->password,
'scope' => 'openid',
]
]
);
$body = json_decode($response->getBody()->getContents(), true);
return $body['access_token'];
} catch (ClientException $e) {
return ['error' => $e->getMessage()];
}
At this point , you need the token to call other endpoint , so you need to inject the returned token in the header of any request you send like :
try {
/** #var GuzzleHttp\Client $client **/
$client->post(
https://api.powerbi.com/v1.0/myorg/groups/<group-id>/datasets/<dataset-id>/tables/<table-name>/rows,
[
'headers' => [
"Accept" => "application/json",
"Authorization" => sprintf("Bearer %s", $token),
],
'json' => $data
]
);
return true;
} catch (ClientException $e) {
return false;
}
Hope that help you .

Related

How can I pass my UploadedFile data via http guzzle request?

I have two different website : my application and my backoffice (in Laravel)
I create an API route to store a document on my application. I made a request with Guzzle on my backoffice to store a document.
My guzzle http request on backoffice website :
public static function storeDocument($token, $request)
{
$client = new \GuzzleHttp\Client([
'Content-Type' => 'multipart/form-data'
]);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
];
$datas = [
'document' => $request->file('document'),
'doc_name' => $request->doc_name ?? '',
];
$request = $client->post(env('API_URL') . '/api/document/store/', ['headers' => $headers, 'form_params' => $datas]);
$result = json_decode($request->getBody()->getContents());
return $result;
}
And there is my API route method on application website :
public function store(Request $request) {
$validator = Validator::make($request->all(), [
'document' => 'bail|required|mimes:pdf,doc,docs,csv,txt|max:2048',
'doc_name' => 'bail|string|max:80|nullable',
]);
if($validator->fails()){
return response()->json($validator->errors());
};
$document = $request->document;
$fileName = '';
if(isset($request->doc_name)) {
$fileName = $request->doc_name . '.' . $document->extension();
} else {
$fileName = $document->getClientOriginalName();
}
$result = Storage::putFileAs(
'documentations',
$document,
$fileName,
'public'
);
if($result) {
return response()->json(['success' => 'Le fichier a bien été enregistré'], 201);
} else {
return response()->json(['error' => $errors], 400);
};
}
It seems that my datas aren't sent correctly because storeDocument() gives me an error : 'This field is required'. So it looks like it can't find $request->document which is required...
And with Insomnia I have no error, my file is correctly save.
I want to specify that I pass correct datas to storeDocument.
That is the result of $request->file('document') :
Illuminate\Http\UploadedFile {#1354 ▼
-test: false
-originalName: "test.pdf"
-mimeType: "application/pdf"
-error: 0
#hashName: null
path: "/tmp"
filename: "phpPOxtfN"
basename: "phpPOxtfN"
pathname: "/tmp/phpPOxtfN"
extension: ""
realPath: "/tmp/phpPOxtfN"
aTime: 2022-08-25 14:30:14
mTime: 2022-08-25 14:30:13
cTime: 2022-08-25 14:30:13
inode: 4856076
size: 48632
perms: 0100600
owner: 33
group: 33
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
I'm stuck since several hours on this, does anyone has any idea to help me?
Thanks ;)
EDIT: I finally found that I have to pass 'multipart' instead of 'form_params' on my http request.
Moreover I found that I have to use fopen or file_get_contents to send raw datas...
So my storeDocument function looks like this now :
public static function storeDocument($token, $request)
{
$client = new \GuzzleHttp\Client([
'Content-Type' => 'multipart/form-data'
]);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
];
$datas = [
[
'name' => 'document',
'contents' => file_get_contents($request->file('document')),
],
[
'name' => 'doc_name',
'contents' => $request->doc_name ?? '',
]
];
$request = $client->post(env('API_URL') . '/api/document/store/', ['headers' => $headers, 'multipart' => $datas]);
$result = json_decode($request->getBody()->getContents());
return $result;
}
But it still doesn't work...
Continue searching...

Laravel 5.8 API + WordPress integration

I am building an APP with Laravel and all functions from User model must provide through API and show them in WP.
They need to "connect with MyApp(login)" and use the same credentials like in Laravel. I made login API and it returns token, expiration date, but when I need to access user object and return it, it says "message": "Unauthenticated."
This is my code:
LOGIN
public function login(Request $request){
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials)) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token ' . str_random(10));
$token = $tokenResult->token;
if ($request->remember_me) {
$token->expires_at = Carbon::now()->addWeeks(10);
}
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at)
->toDateTimeString(),
]);
}
Auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
]
],
Api.php
Route::post('/login', 'Api\AuthController#login')->name('login.api');
Route::middleware('auth:api')->get('/user', function (Request $request){return $request->user();});
// Route::post('/register', 'Api\AuthController#register')->name('register.api');
Route::middleware('auth:api')->group(function () {
Route::get('/logout', 'Api\AuthController#logout')->name('logout');
});
Also i have this in both .htaccess
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
I need to fetch user object and retrieve informations by calling model function ex. $user->allClients.

Integrating wordpress and laravel login

I am developing three area for my website.. using WordPress (Front Page), XenForo (Forum), and Laravel (Member Area) ... i already succeed integrating my laravel and XenForo, so when XenForo user login to Member Area my function will check if the user already exist (If XenForo user exist then laravel will create the user in database using XenForo user data, if not exist then login failed)
Now i want to do the same for WordPress .. when user login to member area the function will check if WordPress user is exist or not .. if exist then new user will be created using wordpress user data (name, email, password, and token if possible) if not exist then login failed, but how do i do this? unlike XenForo .. i can't find WordPress API documentation for getting user data
Edit 1 :
This is my login function
public function login_post(Request $request){
// XENFORO API AUTH START
$http = Http::withHeaders([
'XF-Api-Key' => 'SECRET'
])->asForm()->post('http://forum.mywebsite.com/api/auth', [
'login' => $request->email,
'password' => $request->password
]);
if(isset($http['errors'])){
return redirect('login')->with('error', 'Username and Password Error');
}
$name = $http['user']['username'];
$email = $http['user']['email'];
$password = $request->password;
$is_admin = $http['user']['is_admin'];
$user_id = $http['user']['user_id'];
// XENFORO API AUTH END
// WordPress API AUTH START
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://mywebsite.com/',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", 'Authorization' => 'Basic ' . base64_encode( 'ADMIN' . ':' . 'PASSWORD' ),],
]);
$response = $client->get('users/', [
'query' => [
'email' => $request->email,
]
]);
return json_decode($response->getBody());
// WordPress API AUTH END
if (Auth::attempt(['email' => $email, 'password' => $password])) {
# code...
if(Auth::user()->role == 0){
return redirect('dashboard');
}
return redirect('login');
} else {
$newUser = new User;
$newUser->name = $name ;
$newUser->email = $email;
$newUser->password = bcrypt($password);
$newUser->role = $is_admin;
$newUser->save();
auth()->login($newUser, true);
return redirect('dashboard');
}
}
Edit 2 :
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://mywebsite.com/wp-json/wp/v2/',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", 'Authorization' => 'Basic ' . base64_encode( 'ADMIN' . ':' . 'PASSWORD' ),],
]);
$response = $client->get('users/', [
'query' => [
'email' => $request->email,
]
]);
$response = json_decode($response->getBody());
$name = $response['username'];
$email = $response['email'];
$password = $request->password;
$is_admin = $response['role'];
$user_id = $response['id'];
The Response :
array:3 [▼
0 => {#287 ▼
+"id": 1
+"name": "Admin"
+"url": "http://www.mywebsite.com"
+"description": ""
+"link": "http://mywebsite.com/author/admin/"
+"slug": "admin"
+"avatar_urls": {#285 ▶}
+"meta": []
+"_links": {#281 ▶}
}
1 => {#274 ▼
+"id": 2
+"name": "Prima"
+"url": ""
+"description": ""
+"link": "http://mywebsite.com/author/prima/"
+"slug": "prima"
+"avatar_urls": {#272 ▶}
+"meta": []
+"_links": {#279 ▶}
}
2 => {#288 ▼
+"id": 3
+"name": "TEST ER"
+"url": ""
+"description": ""
+"link": "http://mywebsite.com/author/testing/"
+"slug": "testing"
+"avatar_urls": {#289 ▶}
+"meta": []
+"_links": {#291 ▶}
}
]
WordPress doesn't provide API to check user exists or not, however you can check this by using List Users API.
Here is what I have done in Laravel:
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://www.example.com',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json"],
]);
$response = $client->get('users/', [
'query' => [
'search' => 'example#email.com',
]
]);
return json_decode($response->getBody());
With Authorization:
Install this https://github.com/WP-API/Basic-Auth plugin and update headers, $username & $password refers to WP admin credentials.
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://www.example.com',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", 'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),],
]);

How to store and log for all http request and response in wordpress?

I want to store all outgoing http request from my wordpress site. I want to store all internal and external http request and response also request made with curl. Any help should be useful to me.
Hook into WP_Http::_dispatch_request()
function fn_log_http_request_response( $wp_http_response, $request, $url ) {
$request = [
'method' => $request['method'],
'url' => $url,
'headers' => $request['headers'],
'body' => $request['body'],
];
if($wp_http_response instanceof WP_Error) {
$response = [
'errors' => $wp_http_response->errors,
'error_data' => $wp_http_response->error_data,
];
} else {
$response = [
'status' => [
'code' => wp_remote_retrieve_response_code($wp_http_response),
'message' => wp_remote_retrieve_response_message($wp_http_response),
],
'headers' => wp_remote_retrieve_headers($wp_http_response)->getAll(),
'body' => wp_remote_retrieve_body($wp_http_response),
];
}
error_log(print_r([
'request' => $request,
'response' => $response,
], true));
return $wp_http_response;
}
// hook into WP_Http::_dispatch_request()
add_filter('http_response', 'fn_log_http_request_response', 10, 3 );
Adopted from hinnerk-a
You can also try the following plugin as well
https://wordpress.org/plugins/log-http-requests

Guzzle Bearer Authorization header cannot be setted to request

I am trying to set an Authorization header with Guzzle/6.2.0 on Ubuntu 18.04.1. But I cannot set it. Can anyone help me with this problem?
I have following code:
use GuzzleHttp\Client;
$url = 'my_url';
$client = new Client();
$response = $client->get( $url, [
'headers' => [
'Authorization' => "Bearer {$my_token}"
]
]);
echo '<pre>';
print_r(json_decode($response->getBody(), true));
echo '</pre>';
The server returns all the headers from the request. Here in this function, the authorization header is no longer present.
return $this->handleView($this->view([
'headers' => $request->headers->all()
], 200));
And answer is:
Array {
[headers] => Array {
[host] => Array{ [0]=>'my_url' }
[user-agent] => Array { [0] => GuzzleHttp/6.2.0 curl/7.58.0 PHP/7.1.22-1+ubuntu18.04.1+deb.sury.org+1 }
[x-php-ob-level] => Array{ [0] => 1 }
}
}
So, "Authorization" was not setted.
Thank you!
Can you try with the debug option turned on? What do you see in the logs?
Also can you upgrade to the latest version? I don't remember any bugs related to the question, but if you want to report it in the end, you have to do it against the latest version.

Resources