使用 php Xero api 在 Xero 中添加附件

add an attachment in Xero using php Xero api

任何人都可以使用官方(非 calcanai)PHP SDK 帮助我将 pdf 添加到 Xero 发票。我与 oAuth2 相关联并且之前创建了草稿发票。

然后我将发票更新为已授权并尝试在发票中添加附件。在这一点上我没有任何运气,附件已发送但返回时为空。这些文档一点用处都没有,也没有给出任何添加附件甚至最小字段的示例。这就是我所拥有的:

...
        $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;
            }
...

有什么想法吗?

谢谢

* *

之后的代码
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 );
    }

添加附件需要两次 API 调用。

// 创建或获取您的发票 ID,然后创建附件

    $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);

其他人遇到同样的问题是因为文件名中有#(在我的示例中为 AUTH#00000123.pdf),基于 sidneys 答案的更新代码也是前进的方向