问题
Can anyone help me add a pdf to a Xero Invoice using the official (non calcanai) PHP SDK. I'm connected with oAuth2 and have previously created a draft invoice.
I then update the invoice to Authorised and try to add an attachment to the invoice. At this point I am not getting any luck, the attachments is sent but comes back in the respose as null. The docs are not at all useful and do not give any examples of adding an attachment or even minimal fields. So this is what I have:
...
$attachments = $apiResponse->getInvoices()[0]->getAttachments();
$attachment = new XeroAPI\XeroPHP\Models\Accounting\Attachment;
$attachment->setFileName( $filename )
->setIncludeOnline( true )
->setMimeType( 'application/pdf' );
$attachments[] = $attachment;
$apiResponse->getInvoices()[0]->setAttachments( $attachments );
$apiResult = $accountingApi->updateOrCreateInvoices( $xeroTenantId, $apiAuth );
if ( !$apiResult->getInvoices()[0]->getHasAttachments() ) {
$errors[] = 'Pdf file was not added to Xero.';
}
$errorList = array();
$errList = $apiResult->getInvoices()[0]->getValidationErrors()[0];
if ( !is_null( $errList ) ) {
$errorList = $errList;
}
foreach ( $errorList as $err ) {
$errors[] = $err->getMessage();
}
if ( count( $errors ) == 0 ) {
$result['message'] = 'New Invoice Authorised: ' . $xeroInvoice->getReference();
$result['apiResult'] = $apiResult;
$result['success'] = true;
} else {
$result['message'] = print_r( $errors );
$result['success'] = false;
}
...
any ideas?
thanks
* CODE AFTER *
public function attachPDF( $xeroTenantId, $accountingApi, $invoice ) {
$filename = 'AUTH#' . sprintf( '%08d', $invoice->id ) . '.pdf';
$guid = $invoice->invoice_id;
$content = $invoice->getPDF( \Mpdf\Output\Destination::FILE, true, $filename );
$handle = fopen( $filename, "r" );
$contents = fread( $handle, filesize( $filename ) );
fclose( $handle );
unlink( $filename );
return $accountingApi->createInvoiceAttachmentByFileName( $xeroTenantId, $guid, $filename, $contents, true );
}
回答1:
Adding an attachment requires two API calls.
// Create or Get your Invoice ID, then create Attachment
$invoices = $apiInstance->getInvoices($xeroTenantId);
$guid = $invoices->getInvoices()[0]->getInvoiceId();
// file in the same dir.
$filename = "./helo-heros.jpg";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$result = $apiInstance->createInvoiceAttachmentByFileName($xeroTenantId,$guid,"helo-heros.jpg",$contents);
回答2:
Anyone else who has this same issue it is due to the filename having a # in it (AUTH#00000123.pdf in my example) the updated code based on sidneys answer is also the way forward
来源:https://stackoverflow.com/questions/62155858/add-an-attachment-in-xero-using-php-xero-api