A minimal example of a connection to the Twinfield API with PHP. It logs in once from the command line and lists the offices (companies) you have access to. You do not need a Twinfield client ID of your own.
- PHP 8.3 or newer
- Composer
- A Twinfield account
| Package | What it does |
|---|---|
| solvebeam/twinfield | The Twinfield PHP SDK: offices, customers, transactions and the rest of the Twinfield API. |
| solvebeam/twinfield-cli | vendor/bin/twf login stores your Twinfield login; Credentials::default() reads it in PHP. |
Composer installs these packages with them:
- solvebeam/twinfield-connect: logs in through Twinfield Connect, so you need no client ID.
- solvebeam/oauth2-twinfield: the OAuth 2.0 login of Twinfield.
- Guzzle: the HTTP client.
Install the packages:
git clone https://github.com/solvebeam/twinfield-php-test.git
cd twinfield-php-test
composer installLog in to Twinfield, once:
vendor/bin/twf loginThis opens the Twinfield login in your browser. After you log in, the login is stored in ~/.config/twinfield/credentials.json; check it with vendor/bin/twf status.
Run the example:
composer exampleOr without Composer: php example.php.
Offices (3):
- 1000 Example B.V.
- 1001 Example Holding B.V.
- 1002 Example Services B.V.
example.php is all the code there is:
use SolveBeam\Twinfield\Cli\Credentials;
use SolveBeam\Twinfield\Twinfield;
require __DIR__ . '/vendor/autoload.php';
$twinfield = Twinfield::create(Credentials::default());
foreach ($twinfield->offices()->list() as $office) {
echo $office->code, ' ', $office->name, PHP_EOL;
}Credentials::default()reads the login oftwf login. It refreshes the access token when it expires and stores the new tokens.Twinfield::create()creates the client of the SDK.offices()->list()lists the offices you have access to.
Most other requests are for one office. Choose it with company():
$customer = $twinfield->company('1000')->customers()->get('1000');See the documentation of the SDK for everything you can do.
Use a profile per organisation:
vendor/bin/twf login --profile=acme$twinfield = Twinfield::create(Credentials::default('acme'));In CI you cannot log in with a browser. Set TWINFIELD_REFRESH_TOKEN, TWINFIELD_CONNECT_CLIENT_ID and TWINFIELD_CONNECT_CLIENT_SECRET instead, with the values from ~/.config/twinfield/credentials.json. See twinfield-cli.
This example is for scripts you run yourself. In an application where users log in to Twinfield themselves, use solvebeam/twinfield-connect (or your own client ID with solvebeam/oauth2-twinfield) and store the refresh token of each user yourself.
composer phpcsChecks the code against PSR-12.