Skip to content
This repository has been archived by the owner on Feb 26, 2018. It is now read-only.

Examples

Sjors van der Pluijm edited this page May 7, 2015 · 48 revisions

Technical documentation can be found in the code and the generated docs in the docs folder. If you have any questions or find a bug, please contact me on twitter (@sjorsvdp), email ([email protected]) or create a new issue.

Setting up
First, we need a connection with your Moneybird accout. You’re advised to create a new user for the API connection. Moneybird also supports oAuth (see below).

An autoloader is included if you need it:

<?php
require('Moneybird/ApiConnector.php');
spl_autoload_register('Moneybird\ApiConnector::autoload');
?>

To connect with Moneybird, we need to create the ApiConnector object:

<?php
$config = array(
    'clientname' => 'yourclientname', // see Moneybird URL: yourclientname.moneybird.nl
    'emailaddress' => 'youremailaddress', // You set this when creating the account
    'password' => 'yourpassword', // The password you set in Moneybird when you confirmed the e-mail address
);

// Create a Transport
$transport = new Moneybird\HttpClient();
$transport->setAuth(
	$config['emailaddress'],
	$config['password']
);
$connector = new Moneybird\ApiConnector(
	$config['clientname'],
	$transport, 
	new Moneybird\XmlMapper() // create a mapper
);
?>

That’s it! If you don’t get an exception thrown at you, you’ve done the right thing. If you do get an exception, you probably filled in the wrong credentials or client name.

The basics – errors
If something goes wrong, an exception is thrown. When a NotValidException is thrown, detailed messages (if any) can be found by calling $connector→getErrors(). This returns an Moneybird\Error\ArrayObject(). The messages are in the exception message too.

<?php
$errors = $connector->getErrors();
foreach ($errors as $error) {
	echo $error->attribute . ': ' . $error->message . '<br />';
}
?>

The basics – services
To get, save or delete contacts, recurring templates, invoices, etc, you need to get their service first:

<?php
$contactService = $connector->getService('Contact');
$invoiceService = $connector->getService('Invoice');
?>

The basics – getAll()
To get all contacts, simply call getAll() on the service:

<?php
$contacts = $contactService->getAll();
foreach ($contacts as $contact) {
	echo $contact->name . '<br />';
}
?>

Some services allow a filter for getAll().

<?php
// Get all invoices
$invoices = $invoiceService->getAll();
// Get all invoices draft invoices
// A list of available filters is defined in ApiConnector::$filters 
$invoices = $invoiceService->getAll('draft');
// Get all invoices that match your saved advanced filter with id 12345
// Warning: if the filter is not found, all invoices will be returned!
$invoices = $invoiceService->getAll(12345);
// Get all late invoices of a contact
$invoices = $contact->getInvoices($invoiceService, 'late');
?>

The basics – getById()
To get a contact by it’s id, use getById():

<?php
$contact = $contactService->getById(12345);
?>

Note that the id of a contact is not it’s customerId. To get a customer by it’s customerId, use Moneybird\Contact\Service::getByCustomerId(). Use Moneybird\Invoice\Service::getByInvoiceId() to get an invoice by it’s number.

The basics – save()
To create a new contact pass an array to the constructor. The keys should match the property name you want to set. You don’t need to set all the fields, just the mandatory ones and the ones you want to set. Which fields are mandatory can be found on the Moneybird website and is stored in Contact::$_requiredAttr.

<?php
$contact = new Moneybird\Contact(array(
	'companyName' => 'My Test company', 
	'attention' => 'Attention', 
	'contactName' => 'Contact name', 
	'address1' => 'Address line 1', 
	'address2' => 'Address line 2', 
	'zipcode' => '1111 AA',
	'city' => 'City name', 
	'country' => 'Country name',
	'bankAccount' => 'Bank account', 
	'chamberOfCommerce' => '1234567', 
	'email' => '[email protected]', 
	'customerId' => '21001', 
	'phone' => '073-1234567', 
	'sendMethod' => 'email', 
	'taxNumber' => 'NL12345678B01', 
));
$contact->save($contactService);
// $contact is updated, so this will work
echo $contact->id; // Shows the contact id
?>

The save method can be used for updating too.

<?php
$contact = $contactService->getById(123456);
$contact->setData(array( // Use setData() to change data
	'firstname' => 'James'
));
$contact->save($contactService);
?>

Save note on contact

<?php
$note = new Moneybird\Contact\Note(array(
    'note' => 'This is a note',
));
$note->save($service, $contact);
?>

The basics – delete()
To delete a contact, call delete:

<?php
$contact = new Moneybird\Contact(array(
    'id' => 123456,
));
$contact->delete($contactService);
?>

Syncing
Contacts and invoices have a revision number. If you store this revision number and the id of the contact in your local database, you’re ready to sync.

<?php
// Get the revision numbers of all contacts
$syncList = $contactService->getSyncList();
$updateIds = array();
foreach ($syncList as $sync) {
	// Compare $sync with your local storage
	// $sync->id contains the id of the contact or invoice
	// $sync->revision contains the revision of the contact at Moneybird
	if ($sync->revision > $localRevision) {
		$updateIds[] = $sync->id;
	}
}
// Get the contacts that need updating (max 100; break up requests if you need more)
$contacts = $contactService->getByIds($updateIds);
foreach ($contacts as $contact) {
	// Update your local contact
}
?>

Create and send your first invoice
To create an invoice, create the invoice details (lines) first. You can pass the $contact to the constructor of Invoice, or you can specify contactId in the data array.

<?php
define('TAXRATEID_HIGH', 12345); // Change this to your tax rate id (see Moneybird)
$details = new Moneybird\Invoice\Detail\ArrayObject();
$details->append(new Moneybird\Invoice\Detail(array(
	'amount' => 5, 
	'description' => 'My invoice line',
	'price' => 20,
	'taxRateId' => TAXRATEID_HIGH,
)));
$details->append(new Moneybird\Invoice\Detail(array(
	'amount' => 1, 
	'description' => 'My second invoice line',
	'price' => 12,
	'taxRateId' => TAXRATEID_HIGH,
)));
$details->append(new Moneybird\Invoice\Detail(array(
	'amount' => 5, 
	'product' => $productService->getById(1234), // puts price, description, etc from product in invoice detail
)));
$invoice = new Moneybird\Invoice(array(
	'poNumber' => 'PO Number',
	'details' => $details,
	//'contactId' => 12345,
	'lastname' => 'Custom lastname', 
	'pricesAreInclTax' => true,
), $contact);
$invoice->save($invoiceService);
?>

Once saved, it can be send. If the invoice was not saved yet, calling Invoice::send() will save it. This feature might be removed in a future release.

<?php
$invoice->send($invoiceService, 'email', '[email protected]');
?>

The invoice needs to be sent before you can get the PDF or register payments.

Register payments

<?php
$payment = new Moneybird\Invoice\Payment(array(
	'paymentDate' => new DateTime(),
	'paymentMethod' => 'bank_transfer',
	'price' => 123.14,
	'sendEmail' => false,
));
$invoice->registerPayment(
	$invoiceService,
	$payment
);
?>

Save note on invoice

<?php
$note = new Moneybird\Invoice\History(array(
    'description' => 'This is a note',
));
$note->save($service, $invoice);
?>

Copy an invoice / create a credit note

<?php
$copy = $invoice->copy();
$credit = $invoice->createCredit();
// $copy and $credit are not saved until you call $credit->save($invoiceService);
?>

Settle payments between two invoices of the same type
Both invoices need to be payable.

<?php
$credit->markAsSent($invoiceService);
$invoice->settle($invoiceService, $credit);
?>

Get PDF documents
If you want to store the invoice PDF you can download it with getPdf()

<?php
file_put_contents('invoice.pdf', $invoice->getPdf($invoiceService));
?>

Receiving push messages
If you ask nicely Moneybird can notify you when invoices change state. This is done by a post request to your website or application. To get the invoice from the request, use:

<?php
$invoice = $invoiceService->getByPushMessage();
?>

oAuth
To use the library to connect through oAuth you need a token and token secret. More info about setting up oAuth for Moneybird.

Using oAuth is just a matter of using another Transport.

<?php
$transport = new Moneybird\HttpClient\Oauth();
$consumer = new Moneybird\Lib\OAuthConsumer(
	$config['oauth']['consumerKey'], 
	$config['oauth']['consumerSecret'], 
	NULL
);
$token = new Moneybird\Lib\OAuthConsumer(
	$config['oauth']['token'], 
	$config['oauth']['tokenSecret']
);
$transport->setConsumerAndToken($consumer, $token);
$connector = new Moneybird\ApiConnector(
	$config['clientname'], // put your client name here (<...>.moneybird.nl)
	$transport, 
	new Moneybird\XmlMapper() // create a mapper
);
?>

Requests limit
Moneybird limits the number of requests (350/h). You can find out how many requests you have left using Moneybird\ApiConnector::requestsLeft().

<?php
echo 'Requests left: ' . $connector->requestsLeft();
?>
Clone this wiki locally