# Usage

### Creating an API context

In order to start making calls with the bunq API, you must first register your API key and device, and create a session. In the SDKs, we group these actions and call it "creating an API context". There are two ways to do it. One is through our interactive script, and the other is programmatically from your code.

`src/Util/InstallationUtil.php`

**Creating an API context using `bunq-install` interactive script**

After installing bunq SDK into your project, run the command below from your project root folder:

```bash
$ vendor/bin/bunq-install
```

And then follow the steps the script offers.

**Creating an API context programmatically**

The context can be created by executing the following code snippet:

```php
use bunq\Context\ApiContext;
use bunq\Util\BunqEnumApiEnvironmentType;
use bunq\Util\InstallationUtil;

// Automatically install and save the API context
InstallationUtil::automaticInstall(
    BunqEnumApiEnvironmentType::SANDBOX(), // Use PRODUCTION() for production
    '/path/to/save/context.conf'
);
```

Load the API Context:

```php
use bunq\Context\BunqContext;

BunqContext::loadApiContext(
    ApiContext::restore('/path/to/saved/context.conf')
);
```

{% hint style="warning" %}
**Please note:** *initializing your application is a heavy task and it is recommended to do it only once per device.*
{% endhint %}

**PSD2**

It is possible to create an ApiContext as PSD2 Service Provider. Although this might seem a complex task, we wrote some helper implementations to get you started. You need to create a certificate and private key to get you started. Our sandbox environment currently accepts all certificates, if these criteria are met:

* Up to 64 characters
* PISP and/or AISP used in the end.

Make sure you have your unique eIDAS certificate number and certificates ready when you want to perform these tasks on our production environment.

Creating a PSD2 context is very easy:

```php
$apiContext = ApiContext::createForPsd2(
    BunqEnumApiEnvironmentType::SANDBOX(), // Could be PRODUCTION as well.
    SecurityUtil::getCertificateFromFile($pathToCertificate),
    SecurityUtil::getPrivateKeyFromFile($pathToKey),
    [
        SecurityUtil::getCertificateFromFile($pathToCertificateInChain), // Could be one file containing chain, or multiple certificate files in array.
    ],
    $description
)
```

This context can be saved the same way as a normal ApiContext. After creating this context, create an OAuth client to get your users to grant you access. For a more detailed example, check the [tinker\_php](https://github.com/bunq/tinker_php/) repository.

**Proxy**

You can use a proxy with the bunq PHP SDK. This option must be a string. This proxy will be used for all requests done with the context for which it was provided. You will be prompted to provide a proxy URL when using the interactive installation script.

```php
$proxyUrl = 'socks5://localhost:1080'; // The proxy for all requests, null to disable

$apiContext = ApiContext::create(
    ...
    $proxyUrl
);
```

**Safety considerations**

The file storing the context details (i.e. `bunq.conf`) is a key to your account. Anyone having access to it is able to perform any Public API actions with your account. Therefore, we recommend choosing a truly safe place to store it.

If you rather save the context in a database, you can use the `fromJson()` and `toJson()` methods.

#### Making API calls

There is a class for each endpoint. Each class has functions for each supported action. These actions can be `create`, `get`, `update`, `delete` and `listing`.

Before you can start making calls, you must ensure that you have create an ApiContext and loaded in into BunqContext as shown in the examples above.

The SDK will take care of your user Id, as this id will never change per ApiContext. The SDK also uses your first active monetary account as primary monetary account. This is almost always the same as your billing account. This means that when you do not explicitly pass a Monetary Account ID, the SDK will use the Monetary Account ID of your billing account.

### **Basic Operations**

#### Monetary Accounts

**Create a monetary account:**

```php
use bunq\Model\Generated\Endpoint\MonetaryAccountBankApiObject;

$accountId = MonetaryAccountBankApiObject::create(
    'EUR',                     // Currency
    'My account description'   // Description
)->getValue();
```

**Get account details:**

```php
$monetaryAccount = MonetaryAccountBankApiObject::get($accountId)->getValue();
```

**Close a monetary account:**

```php
MonetaryAccountBankApiObject::update(    
    $accountId,    
    null,      // New description (null = no change)    
    null,      // Avatar (null = no change)    
    null,      // Status (null = no change)    
    'CANCELLED',  // Status    
    'REDEMPTION_VOLUNTARY',  // Sub-status    
    'OTHER',   // Reason    
    'Closing this test account'  // Reason description
);
```

#### Payments

**Make a payment:**

```php
use bunq\Model\Generated\Endpoint\PaymentApiObject;
use bunq\Model\Generated\Object\AmountObject;
use bunq\Model\Generated\Object\PointerObject;

// Create payment to another user
$payment = PaymentApiObject::create(
    new AmountObject('0.01', 'EUR'),  // Amount and currency    
    new PointerObject('EMAIL', 'recipient@example.com'),  // Recipient    
    'Payment description'  // Description
);
```

**Make a payment to another monetary account:**

```php
// Get the IBAN pointer of the recipient account
$recipientAccountAlias = $monetaryAccount->getAlias()[0]; // Get the first alias
$paymentId = PaymentApiObject::create(
    new AmountObject('0.01', 'EUR'),    
    $recipientAccountAlias,    
    'Payment description'
);
```

#### Batch Payments

```php
use bunq\Model\Generated\Endpoint\PaymentBatchApiObject;

// Create an array of payments
$payments = [];for ($i = 0; $i < 10; $i++) {
    $payment = new PaymentApiObject(
            new AmountObject('0.01', 'EUR'),
            new PointerObject('EMAIL', 'recipient@example.com'),        
            'Batch payment #' . $i    
    );    
    $payments[] = $payment;
}

// Create the batch payment
$batchId = PaymentBatchApiObject::create($payments)->getValue();
```

#### Payment Requests

**Create a payment request:**

```php
use bunq\Model\Generated\Endpoint\RequestInquiryApiObject;

$requestId = RequestInquiryApiObject::create(
    new AmountObject('0.01', 'EUR'),    
    new PointerObject('EMAIL', 'recipient@example.com'),    
    'Request description',    
    false  // Don't allow bunqme
)->getValue();
```

**Accept a payment request:**

```php
use bunq\Model\Generated\Endpoint\RequestResponseApiObject;

// List responses to find the ID
$responses = RequestResponseApiObject::listing($monetaryAccountId)->getValue();
$requestResponseId = $responses[0]->getId();

// Accept the request
RequestResponseApiObject::update(
    $requestResponseId,
    $monetaryAccountId,    
    null,    
    'ACCEPTED'  // Status
);
```

#### bunq.me

**Create a bunqme tab:**

```php
use bunq\Model\Generated\Endpoint\BunqMeTabApiObject;
use bunq\Model\Generated\Endpoint\BunqMeTabEntryApiObject;

$tabId = BunqMeTabApiObject::create(
    new BunqMeTabEntryApiObject(
            new AmountObject('0.01', 'EUR'),        
            'Tab description'    
    )
)->getValue();

// Get tab details
$tab = BunqMeTabApiObject::get($tabId);
```

#### Attachments

**Create a public attachment:**

```php
use bunq\Http\ApiClient;
use bunq\Model\Generated\Endpoint\AttachmentPublicApiObject;

// Read the file content
$fileContents = file_get_contents('/path/to/file.png');

// Create the attachment
$attachmentUuid = AttachmentPublicApiObject::create(
    $fileContents,
    [
            ApiClient::HEADER_CONTENT_TYPE => 'image/png',        
            ApiClient::HEADER_ATTACHMENT_DESCRIPTION => 'Attachment description'    
    ]
)->getValue();
```

**Get attachment content:**

```php
use bunq\Model\Generated\Endpoint\AttachmentPublicContentApiObject;

$fileContents = AttachmentPublicContentApiObject::listing($attachmentUuid)->getValue();
```

#### Avatar

**Create an avatar:**

```php
use bunq\Model\Generated\Endpoint\AvatarApiObject;

// First create a public attachment
$attachmentUuid = AttachmentPublicApiObject::create(
    $fileContents,    
    [
            ApiClient::HEADER_CONTENT_TYPE => 'image/png',        
            ApiClient::HEADER_ATTACHMENT_DESCRIPTION => 'Avatar image'    
    ]
)->getValue();

// Create the avatar using the attachment
$avatarUuid = AvatarApiObject::create($attachmentUuid)->getValue();
```

#### Cards

**Get allowed card names:**

```php
use bunq\Model\Generated\Endpoint\CardNameApiObject;

$cardNamesAllowed = CardNameApiObject::listing()->getValue();
$possibleNames = $cardNamesAllowed[0]->getPossibleCardNameArray();
```

**Order a debit card:**

```php
use bunq\Model\Generated\Endpoint\CardDebitApiObject;
use bunq\Model\Generated\Object\CardPinAssignmentObject;

$cardDebit = CardDebitApiObject::create(
    'My Card',                   // Card description    
    $possibleNames[0],           // Name on card    
    'MASTERCARD',                // Card type    
    'MASTERCARD_DEBIT',          // Product type    
    $userAlias->getName(),       // Second line on card    
    $userAlias,                  // User alias    
    [                           // PIN assignments
            new CardPinAssignmentObject(
                        'PRIMARY',           // PIN assignment type            
                        'MANUAL',            // Routing type            
                        '1234',              // PIN code            
                        $primaryAccountId    // Account ID        
            ),    
    ]
)->getValue();
```

#### Notifications (webhooks)

**Create notification filters for a monetary account:**

```php
use bunq\Model\Generated\Endpoint\NotificationFilterUrlMonetaryAccountInternal;
use bunq\Model\Generated\Object\NotificationFilterUrlObject;

$filter = new NotificationFilterUrlObject(
    'MUTATION',                    // Category    
    'https://example.com/callback'  // Callback URL
);

$filters = NotificationFilterUrlMonetaryAccountInternal::createWithListResponse(
    $monetaryAccountId,    
    [$filter]
)->getValue();
```

**Create notification filters for a user:**

<pre class="language-php"><code class="lang-php">use bunq\Model\Generated\Endpoint\NotificationFilterUrlUserInternal;
<strong>
</strong><strong>$filter = new NotificationFilterUrlObject(
</strong>    'MUTATION',    
    'https://example.com/callback'
);

$filters = NotificationFilterUrlUserInternal::createWithListResponse(
    [$filter]
)->getValue();
</code></pre>

**Create push notification filters:**

```php
use bunq\Model\Generated\Endpoint\NotificationFilterPushUserInternal;
use bunq\Model\Generated\Object\NotificationFilterPushObject;

$filter = new NotificationFilterPushObject('MUTATION');
$filters = NotificationFilterPushUserInternal::createWithListResponse(
    [$filter]
)->getValue();
```

#### OAuth

**Create OAuth authorization URI:**

```php
use bunq\Model\Core\BunqEnumOauthResponseType;
use bunq\Model\Core\OauthAuthorizationUri;
use bunq\Model\Generated\Endpoint\OauthClientApiObject;

$authUri = OauthAuthorizationUri::create(
    BunqEnumOauthResponseType::CODE(),    
    'https://redirect.example.com',    
    new OauthClientApiObject('client_status'),    
    'state_parameter'
)->getAuthorizationUriString();
```

#### Session Management

**Delete a session:**

```php
use bunq\Model\Generated\Endpoint\SessionApiObject;

SessionApiObject::delete(0);  // 0 refers to the current session
```

**Reset a session:**

```php
BunqContext::getApiContext()->resetSession();
BunqContext::getApiContext()->save('/path/to/context.conf');
```

### User Context Helper Methods

```php
// Get the primary monetary account
$primaryAccount = BunqContext::getUserContext()->getPrimaryMonetaryAccount();

// Get the user alias
$userAlias = null;
if (BunqContext::getUserContext()->isOnlyUserPersonSet()) {
    $userAlias = BunqContext::getUserContext()->getUserPerson()->getAlias()[0];
} elseif (BunqContext::getUserContext()->isOnlyUserCompanySet()) {
    $userAlias = BunqContext::getUserContext()->getUserCompany()->getAlias()[0];
} elseif (BunqContext::getUserContext()->isOnlyUserApiKeySet()) {
    $userAlias = BunqContext::getUserContext()
            ->getUserApiKey()        
            ->getRequestedByUser()        
            ->getReferencedObject()        
            ->getAlias()[0];
}

// Refresh user context
BunqContext::getUserContext()->refreshUserContext();
```

**Reading objects**

To use the read method you must pass the identifier of the object to read (ID or UUID) except for the endpoints `User`, `UserPerson`, `UserCompany` and `MonetaryAccount`. The SDK will use the default IDs when none are passed. For all other endpoints you must pass the identifier.

This type of calls always returns a model.

```php
BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

$userCompany = UserCompany::get();

printf($userCompany->getPublicNickName());
```

**Updating objects**

```php
BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

MonetaryAccountBank::update(
    $monetaryAccount->getId(),
    $description
);
```

**Deleting objects**

```php
BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

CustomerStatementExport::delete($customerStatementExportId);
```

**Listing objects**

```php
BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

$monetaryAccountList = MonetaryAccount::listing();

foreach ($monetaryAccountList as $monetaryAccount) {
    printf($monetaryAccount->getMonetaryAccountBank->getDescription() . PHP_EOL);
}
```
