I need to connect to an API to claim a voucher. At API doc I see:
POST /api/v1/vouchers/{voucherId}/claim
{
"Participant": {
"FirstName": "John",
"LastName": "James,
"Telephone": "08456 127 127",
"EmailAddress": "tim#asdasd.net",
"PostCode": "ASD 9HX",
"HouseNameNumber": "2",
"Street": "Bridge Road2",
"Locality": "LONDON",
"Town": "Aylesbury",
"County": "Bucks"
},
"ExperienceDate": "2017-10-01T00:00:00"
}
Based on this I write my function using Laravel framework:
public function testclaim()
{
$client = new GuzzleHttp\Client;
$headers = ['Content-Type' => 'application/json'];
try {
$res = $client->post('https://api.example.com/api/v1/vouchers/244775_2-H8SC/claim', [
'headers'=>$headers,
'auth' => [
'JAMES-JJ', 'ajhsdajsdhaj32423'
],
'json' => [
'Participant' => [
"FirstName"=> "asdasd",
"LastName"=> "asdasd",
"Telephone"=> "08456 127 127",
"EmailAddress"=> "tim#asdasd.net",
"PostCode"=> "HP18 9HX",
"HouseNameNumber"=> "1",
"Street"=> "Bridge Road",
"Locality"=> "Ickford",
"Town"=> "Aylesbury",
"County"=> "Bucks"
],
'ExperienceDate' => '2017-11-01T00:00:00'
]
]);
$res = json_decode($res->getBody()->getContents(), true);
return response()->json(['data' => $res]);
//dd($res);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
Now when I run this function I just get:
{"data":null}
ANybody see what is wrong in my code?
How to solve this issue?
I also try without header to send a request but again I get the same response from API.
You don't need getContents() if you want to convert the body to an Array.
Related
We are working with docusign Composite Template API with PHP. We Tried to add a custom document with base64 encoded format with signHereTabs object with values. We are able to create envelope and views for recipient successfully.But the issue is it's not generating signHereTabs which we are tried for recipient. Can you please help us to resolve this issue?
Sample Request in json to create envelope:
{
"status": "sent",
"compositeTemplates": [
{
"compositeTemplateId": "1",
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"signers": [
{
"clientUserId": "1000",
"name": "Full Name",
"email": "my email",
"recipientId": "1",
"roleName": "Sender",
"tabs": {
"signHereTabs": [
{
"anchorString": "\/sig1\/",
"anchorUnits": "pixels",
"anchorXOffset": "20",
"anchorYOffset": "10"
}
]
}
}
]
},
"customFields": {
"textCustomFields": [
{
"name": "MyOwnField",
"required": "true",
"show": "true",
"value": "MyValue"
}
]
}
}
],
"document": {
"documentBase64": "<base64 encoded string>",
"documentId": "1",
"fileExtension": "pdf",
"name": "Agreement.pdf",
"transformPdfFields": false
}
}
]
}
View Recipient sample request:
{
"document": {
"documentBase64": "<base64 encoded string>",
"documentId": "1",
"fileExtension": "pdf",
"name": "Agreement.pdf",
"transformPdfFields": false
}
}
The fields (tabs) need to be a part of the signers object.
Here's a working example from the API Request Builder:
{
"emailSubject": "Please sign the attached document",
"status": "sent",
"compositeTemplates": [
{
"compositeTemplateId": "1",
"document": {
"filename": "anchorfields.pdf",
"name": "Example document",
"fileExtension": "pdf",
"documentId": "1"
},
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"signers": [
{
"email": "signer_email#example.com",
"name": "Signer's name",
"recipientId": "1",
"clientUserId": "1000",
"tabs": {
"signHereTabs": [
{
"anchorString": "/sig1/",
"anchorXOffset": "20",
"anchorUnits": "pixels"
}
]
}
}
]
}
}
]
}
]
}
Here it is with the PHP SDK (auto-generated by the API Request Builder):
<?php # DocuSign Builder example. Generated: Sat, 03 Sep 2022 18:34:12 GMT
# DocuSign Ⓒ 2022. MIT License -- https://opensource.org/licenses/MIT
# #see DocuSign Developer Center
require_once ('vendor/autoload.php');
require_once ('vendor/docusign/esign-client/autoload.php');
# Note: the access_token is for testing and is temporary. It is only good for 8 hours from the time you
# authenticated with API Request Builder.
const base_uri = 'https://demo.docusign.net/';
const access_token = '';
const account_id = '';
const document_directory = '.'; # The directory with your documents, relative to this script's directory
#
function sendDocuSignEnvelope() {
$docs_path = getcwd() . '/' . document_directory . '/';
$document1 = new \DocuSign\eSign\Model\Document([
'document_id' => "1",
'file_extension' => "pdf",
'document_base64' => base64_encode(file_get_contents($docs_path.'anchorfields.pdf')), # filename is anchorfields.pdf
'name' => "Example document"
]);
$sign_here_tab1 = new \DocuSign\eSign\Model\SignHere([
'anchor_string' => "/sig1/",
'anchor_units' => "pixels",
'anchor_x_offset' => "20"
]);
$sign_here_tabs1 = [$sign_here_tab1];
$tabs1 = new \DocuSign\eSign\Model\Tabs([
'sign_here_tabs' => $sign_here_tabs1
]);
$signer1 = new \DocuSign\eSign\Model\Signer([
'client_user_id' => "1000",
'email' => "signer_email#example.com",
'name' => "Signer's name",
'recipient_id' => "1",
'tabs' => $tabs1
]);
$signers1 = [$signer1];
$recipients1 = new \DocuSign\eSign\Model\Recipients([
'signers' => $signers1
]);
$inline_template1 = new \DocuSign\eSign\Model\InlineTemplate([
'recipients' => $recipients1,
'sequence' => "1"
]);
$inline_templates1 = [$inline_template1];
$composite_template1 = new \DocuSign\eSign\Model\CompositeTemplate([
'composite_template_id' => "1",
'document' => $document1,
'inline_templates' => $inline_templates1
]);
$composite_templates1 = [$composite_template1];
$envelope_definition = new \DocuSign\eSign\Model\EnvelopeDefinition([
'composite_templates' => $composite_templates1,
'email_subject' => "Please sign the attached document",
'status' => "sent"
]);
try {
$config = new \DocuSign\eSign\Configuration();
$config->setHost(base_uri . 'restapi');
$config->addDefaultHeader('Authorization', 'Bearer ' . access_token);
$api_client = new \DocuSign\eSign\Client\ApiClient($config);
$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);
$result = $envelope_api->createEnvelope(account_id, $envelope_definition);
$envelope_id = $result->getEnvelopeId();
printf("\nEnvelope status: %s. Envelope ID: %s\n", $result->getStatus(), $result->getEnvelopeId());
return $envelope_id;
} catch (Exception $e) {
printf ("\n\nException from createEnvelope!\n%s", $e->getMessage());
if ($e instanceof DocuSign\eSign\Client\ApiException) {
printf ("\nAPI error information: \n%s", $e->getResponseBody());
}
return FALSE;
}
}
function recipientView ($envelope_id) {
$recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest([
'authentication_method' => "None",
'client_user_id' => "1000",
'email' => "signer_email#example.com",
'return_url' => "https://docusign.com",
'user_name' => "Signer's name"
]);
if (!$recipient_view_request || !$envelope_id) {return;}
try {
$config = new \DocuSign\eSign\Configuration();
$config->setHost(base_uri . 'restapi');
$config->addDefaultHeader('Authorization', 'Bearer ' . access_token);
$api_client = new \DocuSign\eSign\Client\ApiClient($config);
$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);
$result = $envelope_api->createRecipientView(account_id, $envelope_id,
$recipient_view_request);
print ("\nCreate recipient view succeeded.");
printf ("Open the signing ceremony's long URL within 5 minutes: \n%s\n\n", $result->getUrl());
} catch (Exception $e) {
printf ("\n\nException from createRecipientView!\n%s", $e->getMessage());
if ($e instanceof DocuSign\eSign\Client\ApiException) {
printf ("\nAPI error information: \n%s", $e->getResponseBody());
}
}
}
# The mainline
$envelope_id = sendDocuSignEnvelope();
recipientView($envelope_id);
print("Done.\n");
I want to get only the value of the kilometres to save it in a new variable.
I also tried to access the array with index.
My code:
/**
* #Route("/routesetting", name="api_routeset_set", methods={"GET"})
*/
public function getRouteAction(Request $request) {
$distanceMatrix = new GoogleDistanceMatrix('AIzaSyBdAHFe4MsbIr417NlPioNhYW7as-adBa8');
$distance = $distanceMatrix
->addOrigin('Van Bronckhorststraat 94, 5961SM Horst, The Netherlands')
->addDestination('Maistraße 10, 80337 München, Deutschland')
->setMode(GoogleDistanceMatrix::MODE_DRIVING)
->setLanguage('en-EN')
->setUnits(GoogleDistanceMatrix::UNITS_METRIC)
->setAvoid(GoogleDistanceMatrix::AVOID_FERRIES)
->sendRequest();
return $this->json([
'message' => $distance
]);
}
Result:
{
"message": {
"status": "OK",
"responseObject": [],
"originAddresses": [
[]
],
"destinationAddresses": [
[]
],
"rows": [
{
"elements": [
{
"status": "OK",
"duration": {
"text": "6 hours 48 mins",
"value": 24461
},
"distance": {
"text": "695 km",
"value": 695380
}
}
]
}
]
}
}
Expected result:
695380
$distance here seems to be a PHP array (I've never worked with this Google API).
So just before calling return $this->json(['message' => $distance]); you should just get the value you want from the $distance variable.
Which seems to be $distance['rows']['elements']['distance']['value'].
So returning $this->json(['message' => $distance['rows']['elements']['distance']['value']]); seems to be your trick. ;)
Be careful I haven't done any content verification here (isset()).
I'm using Guzzle for HTTP Requests/Responses in my PHP project.
I'm sending the following request :
GET https://graph.microsoft.com/v1.0/me/events('[some_id]')
which, in Postman, returns something that looks like this :
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('...')/events/$entity",
"#odata.etag": "W/\"...==\"",
"id": "...",
"createdDateTime": "2018-06-14T08:03:44.5688916Z",
"lastModifiedDateTime": "2018-06-14T08:03:44.7407671Z",
"changeKey": "...==",
"categories": [],
"originalStartTimeZone": "UTC",
"originalEndTimeZone": "UTC",
"iCalUId": "...",
"reminderMinutesBeforeStart": 15,
"isReminderOn": true,
"hasAttachments": false,
"subject": "Created ?",
"bodyPreview": "",
"importance": "normal",
"sensitivity": "normal",
"isAllDay": false,
"isCancelled": false,
"isOrganizer": true,
"responseRequested": true,
"seriesMasterId": null,
"showAs": "busy",
"type": "singleInstance",
"webLink": "https://outlook.office365.com/owa/?itemid=...%3D&exvsurl=1&path=/calendar/item",
"onlineMeetingUrl": null,
"recurrence": null,
"responseStatus": {
"response": "organizer",
"time": "0001-01-01T00:00:00Z"
},
"body": {
"contentType": "html",
"content": ""
},
"start": {
"dateTime": "2018-06-15T10:00:00.0000000",
"timeZone": "UTC"
},
"end": {
"dateTime": "2018-06-15T13:30:00.0000000",
"timeZone": "UTC"
},
"location": {
"displayName": "",
"locationType": "default",
"uniqueIdType": "unknown",
"address": {},
"coordinates": {}
},
"locations": [],
"attendees": [],
"organizer": {
"emailAddress": {
"name": "...",
"address": "..."
}
}
}
So I build my request like this :
$client = new Client();
$header = array(
"Authorization" => "Bearer ".$token
);
$url = "https://graph.microsoft.com/v1.0/me/events('" .$idEvent. "')";
$request = new Request("GET", $url, $header, "");
try {
$eventInfos = $client->send($request);
}
catch (GuzzleException $e) {
var_dump($e->getMessage());
}
But when I var_dump($eventInfos), I get a GuzzleHttp\Psr7\Request object.
What is the correct way to get the JSON I was expecting please ?
You have to extract the body of from the response. Try this,
$client = new Client();
$header = array(
"Authorization" => "Bearer ".$token
);
$url = "https://graph.microsoft.com/v1.0/me/events('" .$idEvent. "')";
$request = new Request("GET", $url, $header, "");
try {
$eventInfos = $client->send($request);
$response = (string)$eventInfos->getBody();
}
catch (GuzzleException $e) {
var_dump($e->getMessage());
}
Also, you can use getContents() to get the response.
$request->getBody()->getContents()
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 implementing an API using Laravel 5.4 . I want to send the title, description, time and user_id as a JSON and after that to get the JSON response with the input data.
Here is my code:
$title = $request->input('title');
$description = $request->input('description');
$time = $request->input('time');
$user_id = $request->input('user_id');
$meeting = [
'title' => $title,
'description' => $description,
'time' => $time,
'user_id' => $user_id,
'view_meeting' => [
'href' => 'api/v1/meeting/1',
'method' => 'GET1'
]
];
$response = [
'msg' => 'Meeting created',
'meeting' => $meeting
];
return response()->json($response, 201);
After running the server, I make a post request using POSTMAN (body->raw:)
{
"time": "201601301330CET",
"title": "Test meeting 2",
"description": "Test",
"user_id": 2
}
But it return this:
{
"msg": "Meeting created",
"meeting": {
"title": null,
"description": null,
"time": null,
"user_id": null,
"view_meeting": {
"href": "api/v1/meeting/1",
"method": "GET1"
}
}
}
Why the title, description, time and user_id fields are null?
You need to set Postman's content-type dropdown to JSON (application/json). Changing that setting changed the null values in the response to:
{
"msg": "Meeting created",
"meeting": {
"title": "Test meeting 2",
"description": "Test",
"time": "201601301330CET",
"user_id": 2,
"view_meeting": {
"href": "api/v1/meeting/1",
"method": "GET1"
}
}
}