# Pay several applications from your wallet

- Endpoint: `POST /v1/{organizationId}/application/wallet-pay`
- Production: `https://api.main-team.org/v1/{organizationId}/application/wallet-pay`
- Sandbox: `https://apisnd.main-team.org/v1/{organizationId}/application/wallet-pay`
- Operation: `payApplicationsFromWallet` (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 payments of up to 100 applications of your students in this organization from your wallet, one credit each, all or nothing, under one `reference` and one invoice number.

**Per application.** A free exam never takes a credit (`charged: false`, `reason: free`). A payment this wallet already paid, or one settled another way, comes back `charged: false`, `reason: already_paid`, so a repeat is safe. A pending payment is paid at its amount, or the coding bundle price when that is lower, the student’s applications taken in the order you send them.

**All or nothing.** An id that is not an application of your students (unknown and another account’s look the same) fails the whole call with `404` and the ids in `error.details.applicationIds`. A canceled payment, a card payment still open, or too few credits fails it too, and nothing is paid.

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. At most 30 requests per minute.

## Parameters

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

## Request body

Required fields: `applicationIds`.

```json
{
  "applicationIds": [
    "6650a1b2c3d4e5f6a7b8c9e5"
  ]
}
```

## Response

`200` Success: `message` is "Applications paid from wallet.". Or `message` is "Nothing was taken from the wallet.": Every application was free or already paid.

```json
{
  "data": {
    "charged": 3,
    "invoiceNo": "2425-10042",
    "items": [
      {
        "amount": 5000,
        "applicationId": "6650a1b2c3d4e5f6a7b8c9e5",
        "charged": true,
        "currency": "EUR",
        "entryId": "6650a1b2c3d4e5f6a7b8c9f2",
        "paymentId": "6650a1b2c3d4e5f6a7b8c9e6",
        "reason": "free",
        "reference": "stx-19a2c3d4e5f6a7b8c9"
      }
    ],
    "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) | The body is not valid JSON, breaks a field’s rules, or has a field this operation does not accept ("property <name> should not exist"). |
| 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) | An id matches no application of yours; `error.details.applicationIds` lists them. |
| 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. |
| 413 | [`payload_too_large`](https://hub.main-team.org/api/errors#payload_too_large) | The body is larger than 100 kB. |
| 415 | [`unsupported_media_type`](https://hub.main-team.org/api/errors#unsupported_media_type) | The body declares a charset that is not a UTF one (send UTF-8), or a `Content-Encoding` other than gzip, deflate or br. |
| 429 | [`too_many_requests`](https://hub.main-team.org/api/errors#too_many_requests) | Your account has made more than 30 requests to this operation in the current minute. Wait the seconds in `Retry-After` before sending again. This operation has a budget of its own, lower than the 100 per 60 seconds every other operation gets. |
| 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/wallet-pay' \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "applicationIds": [
    "6650a1b2c3d4e5f6a7b8c9e5"
  ]
}
JSON
```

### 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/wallet-pay', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "applicationIds": [
      "6650a1b2c3d4e5f6a7b8c9e5"
    ]
  }),
});
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/wallet-pay');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'applicationIds' => [
            '6650a1b2c3d4e5f6a7b8c9e5',
        ],
    ]),
    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']);
```
