I'm trying to use CURL to send a file to PANDADOCS via the Create Document from File API call: https://developers.pandadoc.com/reference/create-document-from-pdf.
In addition to sending the file, I also need to send a data object containing the recipients etc. as part of a multipart/form-data string in JSON. I'm not sure how to set up this call correctly and I keep getting various error messages returned from its API, such as "A field named file exists"
This is what I have so far:
public function createDocument() { $p = getmypid(); $m = "({$p}): PandaDoc::create document: "; $postfields = array(); $postfields['name'] = $this->document->name; $postfields['file'] = $this->document->file; //base 64 encoded PDF $recipients = array( array( 'email' => 'a.mcdoogle@test.com', 'first_name' => 'Andrew', 'last_name' => 'Mcdoogle', 'role' => 'user', 'signing_order' => 1 ) ); $data = array(); $data['recipients'] = $recipients; $owner = array( "email" => "john@example.com" ); $data['owner'] = $owner; $postfields['data'] = json_encode($data); $header = array("Authorization: API-Key {$this->api_key}", "Content-Type: multipart/form-data", "accept" => "application/json") ; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $res = curl_exec($ch); if ($res === false) { $errno = curl_errno($ch); $error = curl_error($ch); error_log("{$m}cURL error: {$error} ({$errno})"); throw new Exception("{$m}cURL error: {$error} ({$errno})"); } $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close ($ch); error_log("{$m}Results from PandaDoc: {$res}"); $response = json_decode($res); return $response; }
Can anyone tell me what I'm doing wrong?
This is wrong:
I find their API documentation disturbing.
Short Tutorial:
This is a simple multipart/form-data HTML form:
Below I translate this form into curl.
To send this in curl you have to put the form data into postfields.
This is the request header:
This is the request body:
I Base64 encode the pdf like this:
For your PandaDoc API
This is the document field, please note $pdf above.
Your content type may need to be
application/pdf;base64
Their examples use binary data.
This is your data field
Source:https://developers.pandadoc.com /docs/upload-and-send-a-local-pdf