# Pay one application from your wallet

- Endpoint: `POST /v1/{organizationId}/application/{applicationId}/wallet-pay`
- Production: `https://api.main-team.org/v1/{organizationId}/application/{applicationId}/wallet-pay`
- Sandbox: `https://apisnd.main-team.org/v1/{organizationId}/application/{applicationId}/wallet-pay`
- Operation: `payApplicationFromWallet` (Applications)
- Authentication: `Authorization: Bearer <token>`, a short-lived token you sign with your API key and secret
- Permission: `application/pay:$org:$ID`

## Description

Pays the pending payment of one application of one of your students from your wallet: one credit of this organization, the payment marked `paid`, and an entry in your wallet history (`listWalletEntries`). No body.

A free exam takes no credit, and an application this wallet already paid answers `200` with `charged: false`, so a retry is safe. A payment settled another way is `409` `already_paid`; a canceled one `409` `payment_canceled`; a card payment the student still has open `409` `payment_in_progress`. On `coding` the price is the bundle price when the student has already paid a bundle exam.

Needs an enabled wallet, which Main Team opens only after an agreement and on your request (otherwise `403` `wallet_not_enabled`), and the `application/pay` permission on this organization. To pay several at once use `payApplicationsFromWallet`.

## Parameters

| Name | In | Required | Type | Description |
| --- | --- | --- | --- | --- |
| `organizationId` | path | yes | string | The organization’s `_id`: 24 hexadecimal digits, as `listOrganizations` (`GET /v1/organization`) lists it. |
| `applicationId` | path | yes | string | The application’s `_id`, from `createApplication` or one of the application lists. |

## Response

`200` Success: `message` is "Application paid from wallet.". Or `message` is "Nothing was taken from the wallet.": The exam is free, or this wallet already paid it.

```json
{
  "data": {
    "amount": 5000,
    "applicationId": "6650a1b2c3d4e5f6a7b8c9e5",
    "charged": true,
    "currency": "EUR",
    "entryId": "6650a1b2c3d4e5f6a7b8c9f2",
    "paymentId": "6650a1b2c3d4e5f6a7b8c9e6",
    "reason": "free",
    "reference": "stx-19a2c3d4e5f6a7b8c9",
    "wallet": {
      "granted": 50,
      "organization": "stem",
      "remaining": 41,
      "spent": 9
    }
  },
  "message": "Nothing was taken from the wallet.",
  "success": true
}
```

## Errors

| Status | Code | When |
| --- | --- | --- |
| 400 | [`bad_request`](https://hub.main-team.org/api/errors#bad_request) | `applicationId` is not 24 hexadecimal digits. |
| 401 | [`unauthorized`](https://hub.main-team.org/api/errors#unauthorized) | The token is missing or malformed, is not signed with your account’s `apiSecret`, breaks the `iat` and `exp` rules, has expired or been revoked, or its account is not active. All of these answer the same. |
| 403 | [`forbidden`](https://hub.main-team.org/api/errors#forbidden) | The token is valid, but no role on your account allows `application/pay` on the organization in the path, or a role denies it. |
| 403 | [`forbidden`](https://hub.main-team.org/api/errors#forbidden) | Your account has no wallet, or it is closed (a wallet is opened only by Main Team, after an agreement and on your request: ask your Main Team contact or info@main-team.org). Asked for by `walletPay: true` even when no credit would be taken. `error.details.reason` is `wallet_not_enabled`. |
| 404 | [`not_found`](https://hub.main-team.org/api/errors#not_found) | `organizationId` is not the `_id` of an organization. |
| 404 | [`not_found`](https://hub.main-team.org/api/errors#not_found) | No application of your students has this id: it matches nothing, or the application belongs to another account’s student. Both get the same answer. |
| 409 | [`conflict`](https://hub.main-team.org/api/errors#conflict) | The wallet holds fewer credits than the call needs. Nothing was paid or written. `error.details.reason` is `insufficient_credits`, and `error.details.organizations` lists `organizationId`, `organization`, `needed`, `available` and `short`. |
| 409 | [`conflict`](https://hub.main-team.org/api/errors#conflict) | The payment was settled another way (a bank transfer, a card), so there is nothing to take. `error.details.reason` is `already_paid`. |
| 409 | [`conflict`](https://hub.main-team.org/api/errors#conflict) | The payment is canceled. `error.details.reason` is `payment_canceled`. |
| 409 | [`conflict`](https://hub.main-team.org/api/errors#conflict) | The student has a card payment open for this application (opened in the last 25 hours). `error.details.reason` is `payment_in_progress`; try again once it has finished or expired. |
| 409 | [`conflict`](https://hub.main-team.org/api/errors#conflict) | The payment changed while it was being paid and the call could not settle it after retrying. Nothing was taken. `error.details.reason` is `payment_changed`; read the application and try again. |
| 429 | [`too_many_requests`](https://hub.main-team.org/api/errors#too_many_requests) | Your account has made more than 100 requests to this operation in the current 60-second window. Wait the seconds in `Retry-After` before sending again. |
| 500 | [`internal_error`](https://hub.main-team.org/api/errors#internal_error) | Something failed on our side. Retry later, and quote `request_id` if it goes on. |
| 503 | [`service_unavailable`](https://hub.main-team.org/api/errors#service_unavailable) | The wallet is not available in this environment yet. Nothing was paid or written. `error.details.reason` is `wallet_unavailable`. |

## Code samples

### curl

```bash
# $TOKEN: a short-lived token you minted with your API key and secret
curl -sS -X POST 'https://api.main-team.org/v1/<organizationId>/application/<applicationId>/wallet-pay' \
  -H "Authorization: Bearer $TOKEN"
```

### Node.js

```js
const token = process.env.TOKEN; // a short-lived token you minted with your API key and secret

const res = await fetch('https://api.main-team.org/v1/<organizationId>/application/<applicationId>/wallet-pay', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${token}`,
  },
});
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`);
console.log(body.data);
```

### PHP

```php
<?php
$token = getenv('TOKEN'); // a short-lived token you minted with your API key and secret

$ch = curl_init('https://api.main-team.org/v1/<organizationId>/application/<applicationId>/wallet-pay');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $token,
    ],
    CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
if ($response === false) {
    throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$body = json_decode($response, true);
if ($status >= 400) {
    $error = $body['error'];
    throw new RuntimeException("$status {$error['code']}: {$error['message']}");
}
print_r($body['data']);
```
