DocuSign - Can't set "sent" on createEnvelope - php

I am using Docusign PHP Client and trying to create and envelope and send it as email. With the current SDK, I was getting an error:
INVALID_REQUEST_BODY The request body is missing or improperly formatted. Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'API_REST.Models.v2.document[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\n ◀
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive t ▶
Path 'documents.documentBase64', line 1, position 31.
So I had to edit EnvelopeApi.php (line 2876) json_encode($httpBody) to make it work.
Now that it's working, I receive a response like this, however I can't change status created to sent is my problem.
EnvelopeSummary {#460 ▼
#container: array:4 [▼
"envelope_id" => "6b9ef863-2ee0-4ea6-9f7e-20b7d4f59b22"
"status" => "created"
"status_date_time" => "2018-10-03T12:30:22.8600000Z"
"uri" => "/envelopes/6b9ef863-2ee0-4ea6-9f7e-20b7d4f59b22"
]
}
My full code:
First, I authenticated and fetched my $accountId
And then creating Envelope:
$path = public_path('test.pdf');
$b64Doc = base64_encode(file_get_contents($path));
$document = new Document();
$document->setName("TEST.pdf");
$document->setFileExtension("pdf");
$document->setDocumentId(1);
$document->setDocumentBase64($b64Doc);
$sign_here = new SignHere();
$sign_here->setXPosition(25);
$sign_here->setYPosition(50);
$sign_here->setDocumentId(1);
$sign_here->setPageNumber(1);
$sign_here->setRecipientId(1);
$tabs = new Tabs();
$tabs->setSignHereTabs($sign_here);
$signers = new Signer();
$signers->setName('Test User');
$signers->setEmail('test#mailinator.com');
$signers->setRoleName('Signer');
$signers->setRecipientId(1);
$signers->setRoutingOrder(1);
$signers->setTabs($tabs);
$recipients = new Recipients();
$recipients->setSigners($signers);
$envelope_definition = new EnvelopeDefinition();
$envelope_definition->setEmailSubject('Signature Request');
$envelope_definition->setStatus("sent"); // ***
$envelope_definition->setDocuments($document);
$envelope_definition->setRecipients($recipients);
$options = new CreateEnvelopeOptions();
$options->setCdseMode(null);
$options->setMergeRolesOnDraft(null);
try {
$envelopeSummary = $envelopeApi->createEnvelope($accountId, $envelope_definition, $options);
dd($envelopeSummary);
// Also tried this:
// $envelopeApi->update($accountId, $envelopeSummary->getEnvelopeId(), json_encode(['status' => 'sent']);
} catch (ApiException $e){
dd($e->getResponseBody()->errorCode . " " . $e->getResponseBody()->message);
}
$envelope_definition->setStatus("sent"); this should trigger the email, right? But it doesn't for some reason. Also I can't see this created envelope in my Sandbox either.

You are not setting signers correctly. It must be an array of signer objects.
Here is some untested code:
# This code creates a signer, not signers
$signer = new Signer();
$signer->setName('Test User');
$signer->setEmail('test#mailinator.com');
$signer->setRoleName('Signer');
$signer->setRecipientId(1);
$signer->setRoutingOrder(1);
$signer->setTabs($tabs);
$recipients = new Recipients();
# setSigners wants an array of signer objects.
# in this case, we make an array with one element
$recipients->setSigners(array($signer));
Also, you are not creating the tabs right either. Again, it needs to be an array of the tab type.
See this example for additional ideas.

Yes, setting status to sent should make DocuSign send the envelope upon creation. The fact that the response contains "status" => "created" seems to indicate that your setting of the property ($envelope_definition->setStatus("sent");) is not actually being included as part of the request that's being issued to DocuSign.
I've compared your code with the code examples provided in GitHub for the PHP SDK, specifically, with the signatureRequestOnDocument function on that page. The only obvious difference I can see between your code and that example code is in the syntax for creating objects. For example, creating the envelope:
Your code: $envelope_definition = new EnvelopeDefinition();
PHP SDK example code: $envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
I don't know much about PHP, let alone about the DocuSign PHP SDK, but I'd suggest that you try to closely mimic the code examples that are part of the SDK repo on GitHub, to see if you get a different result that way.

My code work like this :
$signersArray = array();
$signer = new Signer();
$signer->set...
$signersArray[] = $signer;
$recipients->setSigners($signersArray);
If it's not working try to dump the data send from the SDK to the API and double check that the status is correct :
Go to Docusign/esign-client/src/ApiClient.php and var_dump($postData) at line 159

Related

How to remove DataValidationRule via Google Sheets API

Currently I'm using the Google Sheets API via their PHP library to build a dynamic spreadsheet. I've set validation rules on a spreadsheet, specifically to create a dropdown list of states to select.
I have since updated the spreadsheet to have the state dropdown list in a different column. Upon doing this however, it seems the DataValidationRule that was set for the previous column, is still there.
I've attempted to create a method to REMOVE all validation from my sheet before re-applying any validation I want, but it does not seem to be working.
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#conditiontype
When setting a Condition Type, I'd like to revert the validation back to CONDITION_TYPE_UNSPECIFIED, however the API simply returns an error if I do so. I've attempted to use others such as ONE_OF_LIST, but then every cell errors saying:
Invalid: Input must be an item on specified list
Which makes sense, considering there is no list being generated (nor do I want one).
The rest of the columns can be any sort of combination of numbers/dates/text so I'd like to simply remove all validation before applying validation again.
Here's my current clearValidation code:
public function clearSpreadsheetValidations($spreadsheetId) {
$client = $this->getClient();
$service = new Google_Service_Sheets($client);
$conditions = new Google_Service_Sheets_BooleanCondition();
$conditions->setType('CONDITION_TYPE_UNSPECIFIED');
$conditions->setValues(null);
$setRule= new Google_Service_Sheets_DataValidationRule();
$setRule->setCondition($conditions);
$setRule->setInputMessage(null);
$setRule->setShowCustomUi(false);
$valReq = new Google_Service_Sheets_SetDataValidationRequest();
$valReq->setRule($setRule);
$sheetReq = new Google_Service_Sheets_Request();
$sheetReq->setSetDataValidation($valReq);
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$requestBody->setRequests($sheetReq);
$service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
}
How can I call the sheets API to remove all previously set DataValidationRules in a spreadsheet?
Thanks!
Okay, as noted here
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request
SetDataValidationRequest
Sets a data validation rule to every cell in the range. To clear
validation in a range, call this with no rule specified.
So all I had to do, was simply not declare a range, or set a rule, and ran this method on the existing spreadsheet to clear all existing validations
public function clearSpreadsheetValidations($spreadsheetId) {
$client = $this->getSheetsClient();
$service = new Google_Service_Sheets($client);
$valReq = new Google_Service_Sheets_SetDataValidationRequest();
$sheetReq = new Google_Service_Sheets_Request();
$sheetReq->setSetDataValidation($valReq);
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$requestBody->setRequests($sheetReq);
$service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
}
For java this code worked in my case.
public BatchUpdateSpreadsheetResponse removeAllDataValidation(String spreadsheetId, Sheets service)
throws IOException {
// [START sheets_conditional_formatting]
List<Request> requests = Arrays.asList(new Request().setSetDataValidation(
new SetDataValidationRequest()));
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse result = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
System.out.printf("%d cells updated.", result.getReplies().size());
// [END sheets_conditional_formatting]
return result;
}

how to get response in json format using twilio sdk

I am using Twilio's PHP SDK to send SMS. Below is the code:
<?php
// Required if your environment does not handle autoloading
require './autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'XXXXXXXXXXXXXXXXXXXXXXXX';
$token = 'XXXXXXXXXXXXXXXXXXXX';
$client = new Client($sid, $token);
// Use the client to do fun stuff like send text messages!
$client->messages->create(
// the number you'd like to send the message to
'+XXXXXXXXXX',
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => '+XXXXXXXX',
// the body of the text message you'd like to send
'body' => 'Hey Jenny! Good luck on the bar exam!'
)
);
**Response:
[Twilio.Api.V2010.MessageInstance accountSid=XXXXXXXXXXXXXXXX sid=XXXXXXXXXXXXXXX]**
How I can get the response in JSON Format?
Any help is appreciated.
I'm not sure if I have understood your intent properly, however, I've created a new GitHub repository which I hope gives you the information that you're after, if you're still interested.
The MessageInstance object which the call to $client->messages->create() returns won't return anything of value when passed to json_encode(). This is because the relevant properties are contained in a protected property, so json_encode() cannot access them.
One option to get around this is to use a class which implements JsonSerializable and returns a JSON representation of a MessageInstance object, such as JsonMessageInstance.
Have a look at the code and let me know if this does what you wanted.
The quick answer is:
$json_string = json_encode(</POST|GET>);
Use the $_POST or $_GET super globals and you get a json string format.
e.g.
/*
* Imagine this is the POST request
*
* $_POST = [
* 'foo' => 'Hello',
* 'bar' => 'World!'
* ];
*
*/
$json_string = json_encode($_POST); // You get → {"foo":"Hello","bar":"World!"}
In this way you encode the values in a JSON representation.

send Notification to device using by tag value using pushwoosh

So i am developing an application which requires push notifications and i'm using pushwoosh. but currently i'm stuck on how to send targeted notifications to a device by a tag value.
I am using [http://gomoob.github.io/php-pushwoosh/]
Any help will be appreciated. thanks
$filter = '';
$request = CreateTargetedMessageRequest::create()
->setContent($options['body'])
->setData(
[
'custom' => 'json data'
]
)
->setDevicesFilter($filter);
$pushwoosh->createTargetedMessage($request);
what i want is the value for the filter
I ended up solving it myself. I used the setCondition() method to specify the tag name and value for what i wanted.
$request = CreateMessageRequest::create()
->addNotification(Notification::create()
->setContent($options['body'])
->setConditions([
IntCondition::create('userId')->eq($user_id)
]));
// Call the REST Web Service
$response = $pushwoosh->createMessage($request);

Hotelbeds PHP API - how to get daily rate of available hotel rooms?

I am working with Hotelbeds APItude PHP API to find out the information of available hotel rooms.
Well, I am able to get all information of available hotels through the documentation
But, I am facing problem with getting daily rate of all available hotel rooms.
There is an option in documentation to send request attribute for getting daily rate of each room. Here is the request attribute -
availabilityRQ/#dailyRate -- Boolean -- Optional -- Display the rate day-by-day
dailyRate is an boolean value that confirms is the API ll send back daily rate info (I think so far).
So, in implementation, I send following request parameter -
$rqData = new \hotelbeds\hotel_api_sdk\helpers\Availability();
$rqData->stay = new Stay(DateTime::createFromFormat("Y-m-d", "2016-09-01"),
DateTime::createFromFormat("Y-m-d", "2016-09-10"));
$rqData->hotels = ["hotel" => [1067, 1070,]];
// $rqData->destination = new Destination("PMI");
$occupancy = new Occupancy();
$occupancy->adults = 2;
$occupancy->children = 1;
$occupancy->rooms = 1;
$occupancy->paxes = [new Pax(Pax::AD, 30, "Mike", "Doe"), new Pax(Pax::AD, 27, "Jane", "Doe"), new Pax(Pax::CH, 8, "Mack", "Doe")];
$rqData->occupancies = [$occupancy];
$rqData->dailyRate = TRUE;
$availRS = $apiClient->Availability($rqData);
I checked, everything work fine except the $rqData->dailyRate = TRUE; parameter.
I get following error -
Bad Request: The request is not compliant with the specified version of the API. Error at property dailyRate: Can not construct instance of boolean from String value 'Y': only "true" or "false" recognized
I think, I am missing something like creating boolean parameter for the dailyRate attribute.
How can I solve the issue?
This looks like a bug with their public API or their PHP library. File a bug report.
class Availability extends ApiHelper. class ApiHelper extends DataContainer.
In DataContainer, if (is_bool($item)) return $item ? "Y" : "N";.
https://github.com/hotelbeds-sdk/hotel-api-sdk-php/blob/56b4621bbf488a878f1eb1a194f6a63d928dc9db/src/generic/DataContainer.php#L105
Their DataContainer.php in their library casts boolean values to Y or N. As such, when you do your API request - any values which are true/false get converted to Y/N.
But their API requires true/false.

shopify Unprocessable Entity

while running this code with the app instalation,i am getting the Unprocessable Entity status code 422 error.
Here is the code
$sc = new ShopifyClient($_SESSION['shop'], $_SESSION['token'], $api_key, $secret);
$charge = array
(
"webhooks"=> array
(
"topic"=>"orders/create",
"address"=>"http://www.abc123no.com/nomi/s.php?key=123456789",
"format"=>"json"
)
);
try
{
$webhooks = $sc->call('POST','/admin/webhooks.json',$charge);
}
catch (ShopifyApiException $e)
{
var_dump($e->getResponseHeaders());
}
Error code 422 is for validation errors. The body of the response will describe the error to help you debug your application.
e.g. The response might be: {"errors":{"address":["for this topic has already been taken"]}}
Your error appears to be from using the wrong format for the request. The create endpoint doesn't take an array of webhooks, and you should use the singular "webhook" for the top-level key.
The Webhook API documentation has the correct format for the request body.
Change webhooks to webhook , it might create bad request error
"**webhooks**"=> array
(
"topic"=>"orders/create",
"address"=>"http://www.abc123no.com/nomi/s.php?key=123456789",
"format"=>"json"
)

Categories