dcblogdev / laravel-xero

Laravel package for working with Xero API
Other
39 stars 23 forks source link

Attachments #22

Closed fazeelDQ closed 1 year ago

fazeelDQ commented 1 year ago

I am trying to send attachments along with the invoice that are already uploaded to server.. The invoice is sent but the attachment is empty. i am trying to send only the URL .. Is this possible at the moment it's not ..

Can you help me with sending attachments that are already uploaded to Laravel ?

rjocoleman commented 1 year ago

To upload attachments:

  1. You need to set a Content-Type on the POST that this library doesn't support.
  2. You have to POST the attachment raw data, not URL, to Xero.
  3. Make sure your authenticated scopes include accounting.attachments (not default in this library's config file)

Here's an example using Laravel HTTP client in conjunction with this library's auth to upload an attachment

use Dcblogdev\Xero\Facades\Xero;
use Illuminate\Support\Facades\Http;

$invoiceId = '381b51c9-6b7f-43a6-8566-7315490c393f'; // the invoice I want to attach a file to
$attachmentFilename = 'example.png'; // the attachment name (in Xero)
$attachmentContentType = 'image/png'; // the attachment content type, for the HTTP client
$attachmentData = file_get_contents('https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG'); // the raw attachment data.

$resp = Http::acceptJson()
  ->withToken(Xero::getAccessToken(false))
  ->withHeaders(['Xero-tenant-id' => Xero::getTenantId()])
  ->withBody($attachmentData, $attachmentContentType)
  ->post("https://api.xero.com/api.xro/2.0/Invoices/{$invoiceId}/Attachments/{$attachmentFilename}");

You'll get a Nyan cat on your invoice with the filename example.png. If the $resp has Unauthorized you probably don't have the correct scopes set.

Of course, you could pull data from laravel storage, or wherever and not use file_get_contents like this (the point is we're sending the raw file as the body).

aurawindsurfing commented 1 month ago

@rjocoleman awesome detailed explanation! Thank you so much!