I get the next error:
Kreait\Firebase\Exception\Messaging\InvalidMessage
Client error: POST https://fcm.googleapis.com/v1/projects/wesig-c9298/messages:send resulted in a 400 Bad Request response:
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT" (truncated...)
This is my code:
$serviceAccount = Firebase\ServiceAccount::fromJsonFile(__DIR__."/apikey.json");
$firebase = (new Firebase\Factory())
->withServiceAccount($serviceAccount)
->create();
$messaging = $firebase->getMessaging();
try {
$generator = new TokenGenerator('AAAALLHVwdc:APA91bFOI1eaWOQTlLq7oezE8E5yWqIb584xDSA10ylTYuIS4Ys9A0qQaqiBSp7A0jRT9_tsaCrNP59Wm-pzD_9wCO4uuxnwD1dmyc5_dF4i9iNHi1TLOxrwmvc-WMPG6K5YFYs5knvla2M_oV7WOKRToawWRNch3g');
$token = $generator
->setData(array('uid' => $user->attributes['uid']))
->create();
} catch (TokenException $e) {
echo "Error: ".$e->getMessage();
}
$notification = [
'title' => "Titulo",
'body' => "Cuerpo"
];
$data = [
'user' => 'yay',
'fecha' => date('d-m-Y')
];
$message = Firebase\Messaging\MessageToRegistrationToken::fromArray([
'token' => $token,
'notification' => $notification, // optional
'data' => $data, // optional
]);
$messaging->send($message);
I think that the error is within the Token, but I just canĀ“t find a way to fix it.
From the documentation, it looks like TokenGenerator produces an auth token. That's not what you want here. The token in the message is the device registration token obtained from a call to a client-side SDK. For example, on Android, it's FirebaseInstanceId.getInstance().getInstanceId().
Related
i try to make API authentication with my WP app
i have write the add the below code to add new fields and upon login it send data to External API if it user exist in API return login or create new WP user if not just don't do anything or gives an error, but i have the issue with Cookie now and get the "Error: Cookies are blocked due to unexpected output."
here is my code:
add_action('login_form', 'businessId', 10, 1);
function businessId()
{
?>
<div class="businessid_wrap">
<label for="businessId">business ID</label>
<input type="text" id="businessId" name="businessId" value=""/>
</div>
<?php
}
function au_auth($user, $username, $password)
{
$endpoint = 'will be my API endpoint url';
// Makes sure there is an endpoint set as well as username and password
if (!$endpoint || $user !== null || (empty($username) && empty($password))) {
return false;
}
$auth_args = [
'method' => 'POST',
'headers' => [
'Content-type: application/json',
],
'sslverify' => false,
'body' => [
'businessId' => $_POST['businessId'],
'userLogin' => $username,
'userPassword' => $password,
],
];
$response = wp_remote_post($endpoint, $auth_args);
$body = json_decode($response['body'], true);
var_dump ($response);
if (!$response) {
// User does not exist, send back an error message
$user = new WP_Error('denied', __('<strong>Error</strong>: Your username or password are incorrect.'));
} elseif ($response) {
/for now i just dumping the return data to check
var_dump ($response);
}
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return $user;
}
add_filter('authenticate', 'au_auth', 10, 3);
In addition to my other tests against my GraphQL API Platform backend, I am attempting to test file uploads. I'm not quite sure whether the ApiPlatform\Core\Bridge\Symfony\Bundle\Test\Client class has the ability to facilitate this test, or if Symfony\Component\HttpFoundation\File\UploadedFile should be used to provide the test file as it is for a REST operation.
Here is roughly where I am at in terms of putting together this test. (With some irrelevant parts removed for simplification)
public function testCreateMediaObject(): void {
$file = new UploadedFile('fixtures/files/logo.png', 'logo.png');
$client = self::createClient();
$gql = <<<GQL
mutation UploadMediaObject(\$file: Upload!) {
uploadMediaObject(input: {file: \$file}) {
mediaObject {
id
contentUrl
}
}
}
GQL;
$response = $client->request('POST', '/api/graphql', [
'headers' => ['Content-Type' => 'application/json'],
'json' => [
'query' => $gql,
'variables' => ["file" => null],
'map' => ['0' => ['variables.file']],
'0' => $file,
]
]);
dd($response);
}
The response I get seems to indicate that the file isn't being included as expected. Something like...
Variable "$file" of non-null type "Upload!" must not be null.
Or.. if I try to attach the file by simply assigning it directly in the variables property...
$response = $client->request('POST', '/api/graphql', [
'headers' => ['Content-Type' => 'application/json'],
'json' => [
'query' => $gql,
'variables' => ["file" => $file],
]
]);
then...
Variable "$file" got invalid value []; Expected type Upload; Could not get uploaded file, be sure to conform to GraphQL multipart request specification. Instead got: []
In my most recent attempt, I changed things up quite a bit after sifting through the graphql code...
$formFields = [
'operations' => '{ "query": "mutation ($file: Upload!) { uploadMediaObject(input: {file: $file}) { mediaObject { id contentUrl } } }", "variables": { "file": null } }',
'map' => "{'0': ['variables.file']}",
'0' => DataPart::fromPath(__DIR__.'/../../fixtures/files/logo.png'),
];
$formData = new FormDataPart($formFields);
$response = $client->request('POST', '/api/graphql', [
'headers' => $formData->getPreparedHeaders()->toArray(),
'body' => $formData->bodyToString(),
]);
The problem with this last attempt is that the server isn't seeing any body parameters. So I receiving the exception
'GraphQL multipart request does not respect the specification.'
Which is found in /api-platform/core/src/GraphQl/Action/EntrypointAction.php within the parseMultipartRequest method.
After a few hours of debugging I found this solution:
$formData = new FormDataPart();
$file = new UploadedFile('src/DataFixtures/files/test.txt', 'test.txt');
$response = $this->$client->request('POST', 'api/graphql', [
'headers' => $formData->getPreparedHeaders()->toArray(),
'extra' => [
'parameters' => [
'operations' => '{ "query": "mutation UploadMediaObject($file: Upload!) { uploadMediaObject(input: {file: $file}) { mediaObject { id contentUrl } } }", "variables": { "file": null } }',
'map' => '{ "0": ["variables.file"] }',
'0' => #$file,
],
'files' => [
$file,
],
],
]);
Refrence:
https://github.com/jaydenseric/graphql-multipart-request-spec
https://api-platform.com/docs/core/graphql/
I want to transform a http post request tested with post man to symfony action :
I want to transform the payload to a json array in symfony to send data to url :
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Routing\Annotation\Route;
class PushNotificationController extends AbstractController
{
/**
* #Route("/api/push_notification", name="push_notification")
*/
public function index()
{
$httpClient = HttpClient::create();
$response = $httpClient->request('POST', 'https://fcm.googleapis.com/fcm/send', [
'headers' => [
// 'Accept' => 'application/json',
// "Content-Type" => "application/json; charset=UTF-8",
'Authorization' => 'Bearer token'
],
'json' => [
'notification' => [
'title' => 'Portugal vs. Denmark',
'message' => 'My Notification Message',
'body' => '5 to 1',
],
'token' => 'token'
],
]);
$statusCode = $response->getStatusCode();
// $statusCode = 200
$contentType = $response->getHeaders()['content-type'][0];
// $contentType = 'application/json'
$content = $response->getContent();
// $content = '{"id":521583, "name":"symfony-docs", ...}'
$content = $response->toArray();
// $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
return $content;
}
}
I got this error :
I think it's an error about the payload . any suggestions please ?
Error 400 Invalid Json input:
Only applies for JSON requests. Indicates that the request could not
be parsed as JSON, or it contained invalid fields (for instance,
passing a string where a number was expected). The exact failure
reason is described in the response and the problem should be
addressed before the request can be retried.
so i guess you need to review your json that you sent.
also , you can use some of the FCM Bundle from Knp or git.
I need to to be authentificate when create a HTTP request, in the documentation
$httpClient = HttpClient::create([
'auth_basic' => ['user#gmail.com', '45#8888'],
]);
$httpClient = HttpClient::create([
// HTTP Basic authentication with only the username and not a password
'auth_basic' => ['the-username'],
// HTTP Basic authentication with a username and a password
'auth_basic' => ['the-username', 'the-password'],
// HTTP Bearer authentication (also called token authentication)
'auth_bearer' => 'the-bearer-token',
]);
So when write
$response = $httpClient->request('GET', 'https://...', [
// use a different HTTP Basic authentication only for this request
'auth_basic' => ['the-username', 'the-password'],
// ...
]);
An exception is throwed
Symfony\Component\HttpClient\Exception\ClientException: HTTP/1.1 400
Bad Request returned for "http://site.test/login_check".
Is the exeption throwed because i haven't post the field user[_token] ?
If yes how to generate it and add to the request ?
If anyone has already logged in with this component please give me the code :)
I used that and it works
Try, for Authentication and Request:
$httpClient = HttpClient::create();
$uri = 'http://test:xxxx/login_check';
$response = $httpClient->request('POST', $uri, [
'headers' => [
'Content-Type' => 'application/json',
],
'json' => [
'username' => 'jhon.doe#gmail.com',
'password' => 'jhon.doe'
],
]);
$statusCode = $response->getStatusCode();
if($statusCode == 200) {
$content = $response->getContent();
dd($content);
}
// JWT Request Http
$uri = 'http://test.xxx/api/xxxx';
$response = $httpClient->request('GET', $uri, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer '.TOKEN
]
]);
$statusCode = $response->getStatusCode();
$content = $response->getContent();
dd($content);
//the easiest
$httpClient->request('POST', $url, [
'auth_bearer' => $jwt,
'body' => $data,
])->getContent();
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 .