I'm trying to send an email via Dynamic template in SendGrid using Guzzle HTTP in PHP.
But I was not able to send mail. As I get only the error like below without any reason in it.
Type: GuzzleHttp\Exception\ClientException
Message: Client error: `POST https://api.sendgrid.com/v3/mail/send` resulted in a `400 Bad Request` response: {"errors":[{"message":"Bad Request","field":null,"help":null}]}
My PHP example code:
require __DIR__.'../../vendor/autoload.php';
$CLIENT = new GuzzleHttp\Client();
$response = $CLIENT->request('POST', 'https://api.sendgrid.com/v3/mail/send', [
"headers" => [
"Authorization" => "Bearer my-api-key",
"Content-Type" => "application/json"
],
'data' => '{
"from": {
"email": "admin#example.com"
},
"personalizations": [{
"to": [{
"email": "me#gmail.com"
}],
"dynamic_template_data": {
"email_data": [{
"id": "2",
"title": "Artificial Intelligence in Health Care",
"image": "https://example.com//uploads/3663581583995181_0724.jpg",
"description": "Immediate application of AI in the Health Care domains."
}, {
"id": "199",
"title": "Aesthetics Skill Discussion 3 by Jranand",
"image": "",
"description": "Aesthetics Skill Discussion 3 by Jranand"
}]
}
}],
"template_id": "my-template-id"
}',
]);
echo $response->getStatusCode();
I was able to send an email via the dynamic template test method in SendGrid with the same dynamic_template_data. But trying this with Guzzle HTTP. I m not able to find the reason for the error.
Able to send an email with dynamic JSON data in the testing.
Can anyone help me out to solve the problem?
Thanks in advance.
There is no data request option in json, you need to change your code either you can use json request option from guzzle(will need lesser effort) or you can directly right your body.
try{
$CLIENT = new GuzzleHttp\Client();
$data = [
"from" => [
"email" => "admin#example.com"
],
"personalizations" => [
[
"to" => [
[
"email" => "me#gmail.com"
]
],
"dynamic_template_data" => [
"email_data" => [
[
"id" => "2",
"title" => "Artificial Intelligence in Health Care",
"image" => "https://example.com//uploads/3663581583995181_0724.jpg",
"description"=> "Immediate application of AI in the Health Care domains."
],
[
"id" => "199",
"title" => "Aesthetics Skill Discussion 3 by Jranand",
"image" => "",
"description" => "Aesthetics Skill Discussion 3 by Jranand"
]
]
]
]
],
"template_id" => "my-template-id"
];
$response = $CLIENT->request('POST', 'https://api.sendgrid.com/v3/mail/send', [
"headers" => [
"Authorization" => "Bearer my-api-key",
"Content-Type" => "application/json"
],
'json' => $data,
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors and log those errors
}catch(Exception $e){
//other errors
}
Related
I am just starting to work this lib and need some help in first steps.
I need to have template for sending to defined in code recipients with prefilled data.
I have template with fullName field and one sign field
In code I am creating new envelope. Code example is:
$envelopeDefinition = new \DocuSign\eSign\Model\EnvelopeDefinition(
[
'status' => 'sent',
'template_id' => $templateId,
]
);
$signer = new \DocuSign\eSign\Model\TemplateRole(
[
'email' => $email,
'name' => $name,
'role_name' => 'signer',
'client_user_id' => 1000,
'tabs' => new \DocuSign\eSign\Model\Tabs(
[
'sign_here_tabs' => [
new \DocuSign\eSign\Model\SignHere(['tab_label' => 'sign'])
]
]
)
]
);
$envelopeDefinition->setTemplateRoles([$signer]);
$envelopeApi = new \DocuSign\eSign\Api\EnvelopesApi($authService->getAuthorizedApiClient());
$envelopeApi->createEnvelope($accountId, $envelopeDefinition);
Envelope was created and it is displayed in manage tab in DocusignUI
In history there are only register event listed. I can't see any sending invitations to email event
No email was received
Could you explain what's wrong with my code?
Addition
I am also trying to create new template in similar way as in EG008CreateTemplate from examples in short version to check if there are any problems with my template configuration.
My request sends post-data:
{
"description": "Example template created via the API",
"documents": [
{
"documentBase64": "...",
"documentId": "1",
"fileExtension": "pdf",
"name": "Debug Agreement"
}
],
"emailSubject": "Please sign this document",
"name": "Debug Agreement Template",
"recipients": {
"signers": [
{
"recipientId": "1",
"roleName": "signer",
"routingOrder": "1",
"tabs": {
"numberTabs": [
{
"documentId": "1",
"font": "helvetica",
"fontSize": "size14",
"pageNumber": "1",
"required": "false",
"tabLabel": "numbersOnly",
"width": "84",
"xPosition": "163",
"yPosition": "260"
}
],
"signHereTabs": [
{
"documentId": "1",
"pageNumber": "1",
"xPosition": "191",
"yPosition": "148"
}
],
"textTabs": [
{
"documentId": "1",
"font": "helvetica",
"fontSize": "size14",
"height": "23",
"pageNumber": "1",
"required": "false",
"tabLabel": "text",
"width": "84",
"xPosition": "153",
"yPosition": "230"
}
]
}
}
]
},
"shared": "false",
"status": "created"
}
And receives again error The request body is missing or improperly formatted. New Account definition(s) not found in the request body.
Who can explain what does this error means? I can't find any descriptions for this case
Take out this line:
'client_user_id' => 1000
This line is used for embedded signing, which is not sending an email, because you embed it in your app.
You want remote signing with an email, so you shouldn't provide a client_user_id.
After digging up code and request process it was detected that accountId was empty and request called https://demo.docusign.net/restapi/v2.1/accounts//templates
Provided error message is not correct as I tend to think.
It is strange for me that I was able to get templates list, create new envelopes with empty accountId...
I have an API. In this API, I pass X-AUTH_TOKEN & X-AUTH-KEY as headers and in the body, I pass raw array data ["1", "2", "3"....]
I have tested it using postman, it is returning me response.
But when I implement it using symfony, I am getting HTTP/2 404 returned for "
This is what I have implemented in Symfony.
$response = $this->httpClient->request('POST', $url, [
'headers' => [
'x-auth-token' => $authToken,
'x-auth-key' => $authKey
],
'body' => [
"1",
"2",
"3",
"4",
]
]);
Can anybody please help me how can I implement?
Thank You.
Instead of body pass json
$response = $this->httpClient->request('POST', $url, [
'headers' => [
'x-auth-token' => $authToken,
'x-auth-key' => $authKey
],
'body' => [
"1",
"2",
"3",
"4",
]
]);
I am using Magento 2.2.2 version. I am trying to update tracking information through their rest API. Here is my code:
$tracking_str =
'{
"items": [
{
"extension_attributes": {},
"order_item_id": "'.$orderItemId.'",
"qty": "'.$qty_invoiced.'"
}
],
"notify": false,
"appendComment": true,
"comment": {
"extension_attributes": {},
"comment": "Item(s) has been shipped",
"is_visible_on_front": 0
},
"tracks": [
{
"extension_attributes": {},
"track_number": "'.$TrackingNumber.'",
"title": "'.$ShipTitle.'",
"carrier_code": "'.$carrierCode.'"
}
],
"packages": [
{
"extension_attributes": {}
}
],
"arguments": {
"extension_attributes": {}
}
}';
I am passing the above things to php curl and for the first time, I am getting a response of shipment id. And the Order status is changing to 'complete' over the Magento API. However, tracking information like carrier code and tracking number are not being updated. When I run the code again, I am getting response as:
res is: stdClass Object
( [message] => Shipment Document Validation Error(s):
The order does not allow a shipment to be created.
You can't create a shipment without products.
)
I don't know, where I am going wrong.
Finally it worked!!!
$tracking_str = [ "items"=> [ [ "order_item_id"=>$orderItemId, "qty"=> $qty_invoiced ] ], "notify" => true, "appendComment" => true, "comment" => [ "extension_attributes" => [], "comment" => "Item(s) has been shipped", "is_visible_on_front" => 0 ], "tracks" => [ [ "extension_attributes" => [], "track_number" => $TrackingNumber, "title" => $ShipTitle, "carrier_code" => $carrierCode ] ] ]
The above code, i have used. some one in github forum's helped me. Thanks to them. Now tracking number, carrier code and title are being updated.
this solution it works for me.
{
"appendComment": true,
"notify": true,
"comment": {
"comment": "shipment creado via webservice",
"is_visible_on_front": 1
},
"tracks": [
{
"track_number": "3SCEMW182389201",
"title": "UPS",
"carrier_code": "Carrier code n"
}
]
}
remove items.
I need to make a POST request to claim voucher. At API docs I find this:
POST /vouchers/{voucherId}/claim
{
"Participant": {
"FirstName": "John",
"LastName": "Jones",
"Telephone": "99999 127 127",
"EmailAddress": "hahahah#hahaha.net",
"PostCode": "HP18 9HX",
"HouseNameNumber": "2",
"Street": "Bridge Road",
"Locality": "Ickford",
"Town": "Lodnon",
"County": "Bucks"
},
"ExperienceDate": "2015-10-01T00:00:00"
}
Now I, using Laravel guzzle library I make this request:
public function testclaim()
{
$client = new GuzzleHttp\Client;
$headers = ['Content-Type' => 'application/json'];
$res = $client->post('https://apidev.asdasd.com/vouchers/11989898_1-9FDD/claim', [
'headers'=>$headers,
'auth' => [
'PET_RES', 'asdasdasd111111'
],
'form_params' => [
'FirstName' => 'Peter',
'LastName' => 'Alexo',
'Telephone' => '8888888888888'
]
]);
$res = json_decode($res->getBody()->getContents(), true);
dd($res);
}
but what I get is:
400 Bad Request
{ "Message": "The request is invalid.", "ModelState": { "claim": [ "An
error has occurred." ] (truncated...)
What is the right way to send a request to the API with following data?
try this
...
'form_params' => [
'Participant' => [
'FirstName' => 'Peter',
'LastName' => 'Alexo',
'Telephone' => '8888888888888'
],
'ExperienceDate' => '2015-10-01T00:00:00'
]
...
if your api just accept json, try replace form_params with json
I am new to Codeception and I am trying to test my web service using the same. Right now I am trying to figure out how to dig deep and test the output that comes from different API points. For example, I am trying to create a user and check if the response contains the necessary details.
CreateUserCept.php
<?php
$faker = Faker\Factory::create();
$I = new ApiTester($scenario);
$I->wantTo('create a new user');
$I->haveHttpHeader('Authorization', 'Bearer ' . file_get_contents('tests/api/token'));
$I->sendPost('users', [
"first_name" => "Test",
"last_name" => "Test",
"email" => 'test#test.com',
"password" => "testing",
"role" => "1"
]);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
The response looks something like:
{
"status": "success",
"data": {
"first_name": "Test",
"last_name": "Test",
"email": "test#test.com",
"updated_at": "2015-11-12 09:08:31",
"created_at": "2015-11-12 09:08:31",
"id": 54
},
"errors": null,
"message": "Resource Created Successfully"
}
Now I can do assertions like:
$I->seeResponseContainsJson(['status' => 'success']);
And it works like a charm but when I do this:
$I->seeResponseContainsJson(['data.first_name' => 'Test']);
It fails. What is the correct way to dig into these and check the JSON response is correct?
This worked for me finally:
$I->seeResponseContainsJson(['data' => [
'first_name' => 'Test'
]]);