Invalid Endpoint in Clevertap - php

I am having a problem in clevertap. I tried the test account that clevertap give in postman and it works.
but when I put my account id and passcode it shows Invalid Endpoint.
$profile = [
"identity"=>"jorem34.like#gmail.com",
"ts"=>1419421212,
"type"=>"profile",
"profileData"=>[
"Name"=>"Jorem",
"Email"=>"jorem#gmail.com",
"Phone"=>"+14153412312",
"Gender"=>"M",
"Employed"=>"Y",
"Age"=>21,
"Customer Type"=>"Silver",
]];
$body = json_encode([
'd' => [
$profile
]
]);
$response = $client->request(
'POST',
self::API_URL,
['headers' => [
'X-CleverTap-Account-Id' => '*****************',
'X-CleverTap-Passcode' => '************',
'Content-Type' => 'application/json'
],
'body' => $body
]
);

Related

GuzzleHttp firebase messaging INVALID_ARGUMENT The message is not set

I'm trying to implement a function to send a a notification using FirebaseCloudMessaging, I got the Auth part, But seems there is an issue with the GuzzleHttp\Client and how it passes the data part
This is my code
public function send(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=<path-to-json-file>.json');
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
// create the HTTP client
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://fcm.googleapis.com',
'auth' => 'google_auth'
]);
$data = json_encode(
[
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
],
);
$response = $client->post('/v1/projects/<Project-id>/messages:send', [
[
'json' => $data,
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
]
]);
dd($response);
}
I keep getting that response 400, INVALID_ARGUMENT "The message is not set."
Client error: POST https://fcm.googleapis.com/v1/projects//messages:sendresulted in a400 Bad Request response: { "error": { "code": 400, "message": "The message is not set.", "status": "INVALID_ARGUMENT", "details (truncated...)
Although my data structure is being passed as documented, what I'm missing here?
Note: I use Laravel, I hided the , etc.
Try to use the Laravel wrapper
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Illuminate\Support\Facades\Http;
public function send(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=D:\Projects\waterko_final\waterco-356810-firebase-adminsdk-brisz-11133a2abb.json');
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$data = [
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
];
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://fcm.googleapis.com',
'auth' => 'google_auth'
]);
return Http::withHeaders($headers)->bodyFormat("json")->setClient($client)
->post('https://fcm.googleapis.com/v1/projects/waterco-356810/messages:send', $data);
}
I ran into the exact same issue, here's what worked for me:
$data should not be json encoded, but passed as an array.
And instead of the json key, it's safer to use the constant : GuzzleHttp\RequestOptions::JSON
$data = [
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
];
$response = $client->post('/v1/projects/<Project-id>/messages:send', [
[
GuzzleHttp\RequestOptions::JSON => $data,
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
]
]);

How do I pass apikey and other keys to header in guzzle 6.3?

I have a simple registration form that the user can register in my app, now I want to send submitted data to another service.
First I test my request using postman as follows using a raw option in a postman panel.
Api url : app3.salesmanago.pl/api/contact/upsert
JSON DATA:
{
"clientId":"w2ncrw06k7ny45umsssc",
"apiKey":"ssssj2q8qp4fbp9qf2b8p49fz",
"requestTime":1327056031488,
"sha":"ba0ddddddb543dcaf5ca82b09e33264fedb509cfb4806c",
"async" : true,
"owner" : "adam#rce.com",
"contact" : {
"email" : "test-1#konri.com",
"name" : "Test",
"address":{
"streetAddress":"Brzyczynska 123",
}
}
}
UPDATE I get the following success result
{
"success": true,
"message": [],
"contactId": "b52910be-9d22-4830-82d5-c9dc788888ba",
"externalId": null
}
Now using guuzle htpp request in laravel
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$client = new client();
$current_timestamp = Carbon::now()->timestamp;
try {
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
],
]);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
$status = $request->getStatusCode();
$response = $request->getBody();
$r = json_decode($response);
dd($r);
dd($status, $r );
return $user;
}
When I run my app and send the form data I get this using the same data as in postman I get this
{#306 ▼
+"success": false
+"message": array:1 [▼
0 => "Not authenticated"
]
+"contactId": null
+"externalId": null
}
It seems like my API key and other header data are not passed to the header as required,
Can someone tell me what am I doing wrong here?
Maybe something like this. Notice that according to the API some values should be passed as headers (Accept, and Content-Type -commonly used as headers, btw-), and other values as part of the body. This is the case of the authentication values like clientId and apiKey.
I don't have guzzle 6 installed at hand but you can try and modify the code to include that data not in the headers section of the request but in the body:
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
],
],
]);
I'm not sure about the 'form_params' in under the RequestOptions::JSON, but mabye you can put the values directly under RequestOptions::JSON.
Just FYI, not sure what Laravel you're using but there's now The Laravel HTTP client which make this sooo much easier.
$response = Http::withHeaders([
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
])->post('app3.salesmanago.pl/api/contact/upsert', [
'name' => $data['name'],
'email' => $data['email'],
]);
if($response->successful()){
dd($response->json())
}else{
// handle yo errors
}

how fix Authorization Bearer Problem in guzzle

I'm trying to send this request to the server, but with a 401 error
Which part of the code can the problem be?
"guzzle version 6.3"
try {
$urlDoPayment = 'https://api.example.com/v1/pay';
$client = new Client();
try {
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody();
dd($content);
} catch (GuzzleException $e) {
dd($e->getMessage());
}
} catch (\Exception $exception) {
dd($exception->getCode());
}
The headers in the request are nested in the wrong part of the request options. That should at least fix the 401 error if the token is valid.
Try:
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
// headers should not be here
], // json post body params end
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
This problem solved using this code
$response = $client->request('POST', $urlDoPayment, [
'json' => [
'amount' => 100,
'returnUrl' => "http://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
I suspect that the problem lays in undefined port or protocol. Headers content wasn't an issue for me. I resolved same problem by changing:
115.12.3.44 to 115.12.3.44:80
also tested
115.12.3.44 to http://115.12.3.44
or
google.com to http://google.com

Why is Guzzle POST showing this foreach error?

I am using
"guzzlehttp/guzzle": "^6.3"
and I am running
$client = new \GuzzleHttp\Client([
'base_uri' => 'http://myapp.loc',
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
Then
$response = $client->post('/api/books', [
'json' => [
'bookId' => '123',
'title' => 'My Random Test Book',
'author' => 'Test Author'
]
]);
But I get
GuzzleHttp\Exception\ClientException : Client error: POST http://myapp.loc/api/books resulted in a 404 Not Found response:
Invalid argument supplied for foreach()
If I use the same route and data in Postman everything works, so the route and method is ok.
I have tried also
$response = $client->post('/api/books', [
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'body' => json_encode([
'bookId' => '123',
'title' => 'My Random Test Book',
'author' => 'Test Author'
])
]);
but it returns the same foreach error.
Any ideas on why Guzzle is showing this foreach error?
Digging a bit into this with Xdebug, the error arises from \GuzzleHttp\Psr7\Stream at the fread point
public function read($length)
{
...
$string = fread($this->stream, $length);
So the solution was to form the request like:
$response = $client->request('POST', 'http://myapp.loc/api/books', [
'form_params' => [
'parameters' => json_encode([[
'bookId' => '123',
'title' => 'My Random Test Book',
'author' => 'Test Author'
]])
]
]);

Guzzle 6 send multipart data

I'd like to add some data to a Guzzle Http Request. There are file name, file content and header with authorization key.
$this->request = $this->client->request('POST', 'url', [
'multipart' => [
'name' => 'image_file',
'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
'headers' =>
['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
]]);
but I get error
Catchable Fatal Error: Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string
given, called in vendor\guzzlehttp\psr7\src\MultipartStream.php on line 70 and defined in vendor\guzzlehttp\psr7\src\MultipartStream.php line 79
In Guzzle 6 documentation is something like this: http://docs.guzzlephp.org/en/latest/request-options.html#multipart
Who knows where I made a mistake?
Here is the solution. Header with access token should be outside multipart section.
$this->request = $this->client->request('POST', 'request_url', [
'headers' => [
'Authorization' => 'Bearer access_token'
],
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => 'image_file',
'contents' => fopen('image_file_url', 'r')
]
]
]);
As per the docs, "The value of multipart is an array of associative arrays", so you need to nest one level deeper:
$this->request = $this->client->request('POST', 'url', [
'multipart' => [
[
'name' => 'image_file',
'contents' => fopen('http://localhost:8000/vendor/l5-swagger/images/logo_small.png', 'r'),
'headers' => ['Authorization' => 'Bearer uCMvsgyuYm0idmedWFVUx8DXsN8QzYQj82XDkUTw']
]
]
]);
try this
works for me
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Utils;
$this->client = new Client([
'base_uri' => 'https://baseurl'
]);
$body = Utils::tryFopen($tempPath . $fileName, 'r');
$res = $this->client->request(
'POST',
'url',
[
'headers' => [
...
],
'body' => $body
]
);

Categories