# Integration and Testing
source: https://developer.mastercard.com/carbon-calculator/documentation/tutorials-and-guides/api-testing-tutorial/index.md

This guide walks through the steps required to test Carbon Calculator API after creating a Sandbox project. You can follow similar steps to test API in Production once your access is approved.
>
> #### What you will learn {#what-you-will-learn}
>
> * How to configure the API for testing via the Insomnia tool for the Sandbox environment. The Insomnia tool can test API calls by simply filling in the parameters without writing any code.
> * How to build an end-to-end application.

### Assumption {#assumption}

Test cases are about below test bank details. Replace with your relevant data.

**Client ID:** fjl2fxzsYl1OpvxkBItC9nVw1PSQc_b-eQMcmQFg011ab4b5

**CustomerName:** ABC Bank

**Supported Account Range:** 534403, 518145, 518152, 5403, 5424

**NOTE:** Refer to [API Reference](https://developer.mastercard.com/carbon-calculator/documentation/api-reference/index.md) page for more details on each API and related parameters.

### Insomnia {#insomnia}

* The Insomnia tool is a popular open-source REST client application that works on Windows, Mac, and Linux operating systems.
* It is a handy tool for developers to test API calls by simply filling in the parameters without writing any code.
* The Carbon Calculator API can also be tested with this tool.

> #### What you will learn {#what-you-will-learn-1}
>
> * How to configure the API for testing via the Insomnia tool.
> * How to set up the Sandbox environment in the Insomnia tool.
> * How to test the API.
>
> #### Estimated time to complete this tutorial {#estimated-time-to-complete-this-tutorial}
>
> * 15-20 minutes

### Pre-requisites {#pre-requisites}

1. Create a project for the Carbon Calculator API.
2. On-board for the Carbon Calculator API with a valid BIN range by Mastercard.
3. [Insomnia tool](https://insomnia.rest/) installed.
4. [Mastercard Insomnia Plugin](https://github.com/Mastercard/insomnia-plugin-mastercard-auth#installation-) installed.

Tip: To create your project on Mastercard Developers, refer to the [Before You Start](https://developer.mastercard.com/carbon-calculator/documentation/index.md#before-you-start) section for more information.

### Set up Sandbox Environment {#set-up-sandbox-environment}

1. Create a new workspace by selecting the "Create Workspace" option from the drop-down of the top-left purple bar.

2. Name the workspace as "Carbon Calculator" and click **Create** .
   ![Create Workspace](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_1.png)

3. Add Sandbox as one of the environments.

4. Go to "Manage Environments" from the "No Environment" drop-down list.
   ![Manage Environment](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_2.png)

5. Click '+' and select "Environment" to create a new environment.
   ![Create Environment](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_3_1.png)

6. Name the new environment as "Sandbox" by double-clicking the "New Environment" on the left-side under "Sub Environments".
   ![Rename Environment](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_4_1.png)

7. Copy and paste the below configuration under Sandbox and click **Done** to finish.

```json
{
    "host": "<HOST URL>",
    "mastercard": {
        "consumerKey": "<CONSUMER KEY>",
        "keyAlias": "<KEY ALIAS>",
        "keystoreP12Path": "<PATH to .p12 FILE>",
        "keystorePassword": "<KEYSTORE PASSWORD>"
    }
}
```

![Set up Complete](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_5_1.png) 8. The Insomnia tool is successfully set up. Follow the next section.

### Configure Sandbox Environment {#configure-sandbox-environment}

Now, as your Insomnia tool has been set up, let's configure it by adding the Sandbox environment.

1. Log in to your Mastercard Developers account and go to your project.

2. Use the following details from the "Sandbox" section of your project:

   * Consumer Key
   * Key Alias
   * Keystore Password
3. Use the following details:

   * host as `https://sandbox.api.mastercard.com/carbon`
   * keystoreP12Path as the absolute location of the .p12 file which was generated during your project creation  
4. Go to the **Manage Environments** of Insomnia tool and update the configurations as shown below and click **Done** to finish.
   ![Configuration Complete](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_6_1.png)

5. The Insomnia tool is successfully configured and ready to test the API in Sandbox. Follow the next section.

### Services Testability list {#services-testability-list}

The following table captures the services of Carbon Calculator API that can be tested using Insomnia:

|                 Service                 |                        Endpoint                         | Testable using Insomnia |
|-----------------------------------------|---------------------------------------------------------|-------------------------|
| Add Payment Cards                       | /service-providers/payment-cards                        | No                      |
| Add Payment Card(to be deprecated)      | /payment-cards                                          | No                      |
| Delete Payment Card                     | /service-providers/payment-cards/{payment_card_id}      | Yes                     |
| View Historical Transaction Footprints  | /payment-cards/{payment_card_id}/transaction-footprints | Yes                     |
| View Aggregate Transaction Footprints   | /payment-cards/transaction-footprints/aggregates        | Yes                     |
| Transaction Footprint Notification      | /payment-cards/transaction-footprints/notifications     | No                      |
| Transaction Footprints Calculation      | /transaction-footprints                                 | Yes                     |
| Get Supported Currencies                | /supported-currencies                                   | Yes                     |
| Get Supported Merchant Categories       | /supported-merchant-categories                          | Yes                     |
| View Service Provider Details           | /service-providers                                      | Yes                     |
| Update Service Provider Details         | /service-providers                                      | Yes                     |
| Delete Payment Cards (to be deprecated) | /payment-card-deletions                                 | Yes                     |

## Invoking Add Payment Cards API using Insomnia {#invoking-add-payment-cards-api-using-insomnia}

This section provides step-by-step directions to call the `/service-providers/payment-cards` service from the Insomnia tool.
Note: Call the [View Service Provider Details](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/service_provider_details/index.md) API first to validate that any account information is registered with the Carbon Calculator application or call the [Update Service Provider Details](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/update_service_provider_details/index.md) API if the issuer wants to update any information.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *Add Payment Card* , select the request method as *POST* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_30.png)
   ![Request Method](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_31.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_32.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_33.png)

3. Paste the text **{{host}}/service-providers/payment-cards** in the request URL to configure.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_72.png)

4. Paste the JSON payload to configure the request.

   Note: The [Add Payment Cards](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/add_payment_card_single_and_bulk/index.md) service expects an encrypted request object as it contains PCI data. Refer to the [Build an end-to-end application](https://developer.mastercard.com/carbon-calculator/documentation/quick-start-guide/api-testing-tutorial/index.md) tutorial for more information on how to encrypt a request object.  

   <br />

```json
[
	{
		"id": "4a737ddd-9e8e-4047-b214-8d350fb541f9",
		"fpan": "5111116683093602",
		"cardBaseCurrency": "USD"
	},
	{
		"id": "bba90cdd-76f1-4bfc-95f0-e938b9db528f",
		"fpan": "5111111058916826",
		"cardBaseCurrency": "USD"
	},
	{
		"id": "7df233aa-8de3-4a2e-a9dd-382a670c907b",
		"fpan": "5111118879002207",
		"cardBaseCurrency": "USD"
	},
	{
		"id": "dc852686-d878-40d9-be7b-96010bab6fde",
		"fpan": "5111115628906915",
		"cardBaseCurrency": "USD"
	}
]
```

![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_73.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_74.png)

6. You have successfully invoked the `/service-providers/payment-cards` service from the Insomnia tool.  

## Test Cases for Add Payment Cards API {#test-cases-for-add-payment-cards-api}

Allows a registered Service Provider to add list of new Payment Cards under its profile.

### Pre-requisites {#pre-requisites-1}

Refer to the [Add Payment Cards](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/add_payment_card_single_and_bulk/index.md) use case.


API Reference: `GET /service-providers/payment-cards`

<br />

### Test Case: Success-Add Payment Cards {#test-case-success-add-payment-cards}

#### Request {#request}

```json
{
    "encryptedData": "3a1ce4719811b528ad517f2a3dba6dbc43152225c2cb5b1f5c05580bf7c97f6ef9d2366f587f6e35c8af2299e7635b5212930c8ac4faf09802a4e5b07688c7aa",
    "encryptedKey": "2323232ccef1f06acb6d4fe0c4828c9b5c0dd62909bb33b80c959b8852dc6014feecc9e66ddd38ceb4800cc856135401c9123fff498c5555aa1b6946525f459face4d20f9ff796c2e0a90d28d84f64e8b0d3b96654e5b231aab0eb3bbc961c5a59b1033c91c3ea3aeab23849a73612e25ee5904a4118b35f82c84c2de496ec6ec37aec71177a788eda5b66f9fa279d62e98408a5f42e693fc8a9b2141efeba77ab46ea4d0381a297cffa35b5c39242266bf2b0a3c7d6f83a0895d02edb00f008c652e683ed11b32278c9d2db943dad85fe5c8ad1d2376904aafc643be0e48a12a939834800e89bc78f50539fdaa1a56fa9d8232592704e6c23f560e2ea58fbd5",
    "iv": "2323a534b22011b4150b0fab77d1978a",
    "oaepHashingAlgorithm": "SHA256",
    "publicKeyFingerprint": "232323a0c1309b08c181cb49e37337984188d066644d431912623a7b6269a807e5"
}
```

#### Response {#response}

```json
[
  {
    "id": "4a737ddd-9e8e-4047-b214-8d350fb541f9",
    "bin": "545502",
    "last4fpan": "8351",
    "status": "ACTIVE",
    "paymentCardId": "9f12f385-0b47-4cca-9e9d-baced21bca61"
  },
  {
    "id": "bba90cdd-76f1-4bfc-95f0-e938b9db528f",
    "bin": "545502",
    "last4fpan": "0762",
    "status": "ACTIVE",
    "paymentCardId": "f506521c-38c6-4e87-bf1a-14023ce10d41"
  }
]
```

### Test Case: Fail-Invalid FPAN {#test-case-fail-invalid-fpan}

#### Request {#request-1}

```json
{
    "encryptedData": "3a1ce4719811b528ad517f2a3dba6dbc43152225c2cb5b1f5c05580bf7c97f6ef9d2366f587f6e35c8af2299e7635b5212930c8ac4faf09802a4e5b07688c7aa",
    "encryptedKey": "2323232ccef1f06acb6d4fe0c4828c9b5c0dd62909bb33b80c959b8852dc6014feecc9e66ddd38ceb4800cc856135401c9123fff498c5555aa1b6946525f459face4d20f9ff796c2e0a90d28d84f64e8b0d3b96654e5b231aab0eb3bbc961c5a59b1033c91c3ea3aeab23849a73612e25ee5904a4118b35f82c84c2de496ec6ec37aec71177a788eda5b66f9fa279d62e98408a5f42e693fc8a9b2141efeba77ab46ea4d0381a297cffa35b5c39242266bf2b0a3c7d6f83a0895d02edb00f008c652e683ed11b32278c9d2db943dad85fe5c8ad1d2376904aafc643be0e48a12a939834800e89bc78f50539fdaa1a56fa9d8232592704e6c23f560e2ea58fbd5",
    "iv": "2323a534b22011b4150b0fab77d1978a",
    "oaepHashingAlgorithm": "SHA256",
    "publicKeyFingerprint": "232323a0c1309b08c181cb49e37337984188d066644d431912623a7b6269a807e5"
}
```

#### Response {#response-1}

```json
[
  {
    "id": "4a737ddd-9e8e-4047-b214-8d350fb541f9",
    "bin": "545502",
    "last4fpan": "8351",
    "status": "ACTIVE",
    "paymentCardId": "9f12f385-0b47-4cca-9e9d-baced21bca61"
  },
  {
      "id": "c8ac6454-4378-4160-91bb-c36811bbf8ee",
      "bin": "545502",
      "last4fpan": "2824",
      "errorCode": "INVALID_FPAN"
  }
]
```

### Test Case: Success-If Payment card exist {#test-case-success-if-payment-card-exist}

#### Request {#request-2}

```json
{
    "encryptedData": "3a1ce4719811b528ad517f2a3dba6dbc43152225c2cb5b1f5c05580bf7c97f6ef9d2366f587f6e35c8af2299e7635b5212930c8ac4faf09802a4e5b07688c7aa",
    "encryptedKey": "2323232ccef1f06acb6d4fe0c4828c9b5c0dd62909bb33b80c959b8852dc6014feecc9e66ddd38ceb4800cc856135401c9123fff498c5555aa1b6946525f459face4d20f9ff796c2e0a90d28d84f64e8b0d3b96654e5b231aab0eb3bbc961c5a59b1033c91c3ea3aeab23849a73612e25ee5904a4118b35f82c84c2de496ec6ec37aec71177a788eda5b66f9fa279d62e98408a5f42e693fc8a9b2141efeba77ab46ea4d0381a297cffa35b5c39242266bf2b0a3c7d6f83a0895d02edb00f008c652e683ed11b32278c9d2db943dad85fe5c8ad1d2376904aafc643be0e48a12a939834800e89bc78f50539fdaa1a56fa9d8232592704e6c23f560e2ea58fbd5",
    "iv": "2323a534b22011b4150b0fab77d1978a",
    "oaepHashingAlgorithm": "SHA256",
    "publicKeyFingerprint": "232323a0c1309b08c181cb49e37337984188d066644d431912623a7b6269a807e5"
}
```

#### Response {#response-2}

```json
[
  {
    "id": "4a737ddd-9e8e-4047-b214-8d350fb541f9",
    "bin": "545502",
    "last4fpan": "8351",
    "status": "ACTIVE",
    "paymentCardId": "9f12f385-0b47-4cca-9e9d-baced21bca61"
  },
  {
      "id": "d2b02acf-f89f-4209-a10d-e18f89d9a0fe",
      "bin": "545502",
      "last4fpan": "8351",
      "status": "ACTIVE",
      "paymentCardId": "9f12f385-0b47-4cca-9e9d-baced21bca61"
    }
]
```

## Invoking Add Payment Card API using Insomnia {#invoking-add-payment-card-api-using-insomnia}

This section provides step-by-step directions to call the `/payment-cards` service from the Insomnia tool.
Note: Before calling Add Payment Card, you need to call [View Service Provider Details](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/service_provider_details/index.md) API to validate that any account information is registered with the Carbon Calculator application or not OR call [Update Service Provider Details](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/update_service_provider_details/index.md) API if the issuer wants to update any information.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *Add Payment Card* , select the request method as *POST* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_30.png)
   ![Request Method](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_31.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_32.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_33.png)

3. Configure the request URL by copying and pasting the text **{{host}}/payment-cards** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_34.png)

4. Configure the request payload by copying and pasting the following JSON payload.

   Note: The [Add Payment Card](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/add_payment_card/index.md) service expects an encrypted request object as it contains PCI data. To understand how to encrypt a request object, refer to the [Build an end-to-end application](https://developer.mastercard.com/carbon-calculator/documentation/quick-start-guide/api-testing-tutorial/index.md) tutorial.  

   <br />

```json
{
"fpan":"5123455937750237",
"cardBaseCurrency":"USD"
}
```

![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_35.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_36.png)

6. You have successfully invoked the `/payment-cards` service from the Insomnia tool.  

## Test Cases for Add Payment Card API {#test-cases-for-add-payment-card-api}

Allows a registered Service Provider to add a new Payment Card under its profile.

### Pre-requisites {#pre-requisites-2}

Refer to the [Add Payment Card](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/add_payment_card/index.md) use case.


API Reference: `GET /payment-cards`

<br />

### Test Case: Success-Add Card {#test-case-success-add-card}

##### Request {#request-3}

```json
{
    "encryptedData": "3a1ce4719811b528ad517f2a3dba6dbc43152225c2cb5b1f5c05580bf7c97f6ef9d2366f587f6e35c8af2299e7635b5212930c8ac4faf09802a4e5b07688c7aa",
    "encryptedKey": "2323232ccef1f06acb6d4fe0c4828c9b5c0dd62909bb33b80c959b8852dc6014feecc9e66ddd38ceb4800cc856135401c9123fff498c5555aa1b6946525f459face4d20f9ff796c2e0a90d28d84f64e8b0d3b96654e5b231aab0eb3bbc961c5a59b1033c91c3ea3aeab23849a73612e25ee5904a4118b35f82c84c2de496ec6ec37aec71177a788eda5b66f9fa279d62e98408a5f42e693fc8a9b2141efeba77ab46ea4d0381a297cffa35b5c39242266bf2b0a3c7d6f83a0895d02edb00f008c652e683ed11b32278c9d2db943dad85fe5c8ad1d2376904aafc643be0e48a12a939834800e89bc78f50539fdaa1a56fa9d8232592704e6c23f560e2ea58fbd5",
    "iv": "2323a534b22011b4150b0fab77d1978a",
    "oaepHashingAlgorithm": "SHA256",
    "publicKeyFingerprint": "232323a0c1309b08c181cb49e37337984188d066644d431912623a7b6269a807e5"
}
```

##### Response {#response-3}

```json
{
    "bin": "545502",
    "last4fpan": "8351",
    "status": "ACTIVE",
    "paymentCardId": "9f12f385-0b47-4cca-9e9d-baced21bca63"
}
```

### Test Case: Fail-Invalid PAN {#test-case-fail-invalid-pan}

##### Request {#request-4}

```json
{
    "encryptedData": "4a1ce4719811b528ad517f2a3dba6dbc43152225c2cb5b1f5c05580bf7c97f6ef9d2366f587f6e35c8af2299e7635b5212930c8ac4faf09802a4e5b07688c7aa",
    "encryptedKey": "1323232ccef1f06acb6d4fe0c4828c9b5c0dd62909bb33b80c959b8852dc6014feecc9e66ddd38ceb4800cc856135401c9123fff498c5555aa1b6946525f459face4d20f9ff796c2e0a90d28d84f64e8b0d3b96654e5b231aab0eb3bbc961c5a59b1033c91c3ea3aeab23849a73612e25ee5904a4118b35f82c84c2de496ec6ec37aec71177a788eda5b66f9fa279d62e98408a5f42e693fc8a9b2141efeba77ab46ea4d0381a297cffa35b5c39242266bf2b0a3c7d6f83a0895d02edb00f008c652e683ed11b32278c9d2db943dad85fe5c8ad1d2376904aafc643be0e48a12a939834800e89bc78f50539fdaa1a56fa9d8232592704e6c23f560e2ea58fbd5",
    "iv": "2323a534b22011b4150b0fab77d19788a",
    "oaepHashingAlgorithm": "SHA256",
    "publicKeyFingerprint": "232323a0c1309b08c181cb49e37337984188d066644d431912623a7b6269a807e5"
}
```

##### Response {#response-4}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "INVALID_FPAN",
        "Description": "The card number in the request is either invalid or does not match with your currently supported account range. Try again with a valid card number or update the supported account range.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

## Invoking Delete Payment Card API using Insomnia {#invoking-delete-payment-card-api-using-insomnia}

This section provides step-by-step directions to call the `/service-providers/payment-cards/{payment_card_id}` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *Delete Payment Card* , select the request method as *DELETE* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_37.png)
   ![Request Method](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_38.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_76.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_77.png)

3. Configure the request URL by copying and pasting the text **{{host}}/service-providers/payment-cards/{payment_card_id}** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_78.png)

4. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_79.png)

5. You have successfully invoked the `/service-providers/payment-cards/{payment_card_id}` service from the Insomnia tool.  

## Test Cases for Delete Payment Card API {#test-cases-for-delete-payment-card-api}

Allows a registered Service Provider to delete a Payment Card from its profile.

### Pre-requisites {#pre-requisites-3}

Refer to the [Delete Payment Card](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/delete_payment_cards/index.md) use case.


API Reference: `GET /service-providers/payment-cards/{payment_card_id}`

<br />

### Test Case: Success-Delete Card {#test-case-success-delete-card}

##### Response {#response-5}

Response Code : `202`

### Test Case: Fail-Invalid request parameter {#test-case-fail-invalid-request-parameter}

##### Response {#response-6}

```json
{
 "Errors": {
   "Error": [
     {
       "Source": "Service-Provider",
       "ReasonCode": "INVALID_REQUEST_PARAMETER",
       "Description": "One of the request parameters is invalid, try again with correct request.",
       "Recoverable": false,
       "Details": ""
     }
   ]
 }
}
```

### Test Case: Fail-Payment card invalid or not found {#test-case-fail-payment-card-invalid-or-not-found}

##### Response {#response-7}

```json
{
 "Errors": {
   "Error": [
     {
       "Source": "Service-Provider",
       "ReasonCode": "PAYMENT_CARD_NOT_FOUND",
       "Description": "Paymentcard Not Found for the given payment card id in the path.",
       "Recoverable": false,
       "Details": ""
     }
   ]
 }
}
```

## Invoking Transaction Footprints API using Insomnia {#invoking-transaction-footprints-api-using-insomnia}

This section provides step-by-step directions to call the `/transaction-footprints` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_7.png)

2. Name the request *Transaction Footprints* , select the request method as *POST* , the body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_8.png)
   ![Request Method](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_9.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_10.png)

3. Configure the request URL by copying and pasting the text **{{host}}/transaction-footprints** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_11.png)

4. Configure the request payload by copying and pasting the following JSON payload.

```json
[
	{
		"transactionId": "fdc4626c-f51e-4ba6-9728-c79ac1d9aec8",
		"mcc": "5962",
		"amount": {
			"value": 50,
			"currencyCode": "EUR"
		}
	}
]
```

![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_12.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_13.png)

6. You can also send multiple transactions in the request payload.
   ![Multiple Requests](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_75.png)

7. In the case of profile-based scoring, configure the request payload by copying and pasting the following JSON payload.

```json
[
      {
          "transactionId": "yBNC8EJvzr",
          "type": "MCC",
          "mcc": "3000",
          "amount": {
            "currencyCode": "USD",
            "value": 10.35
          },
          "cardBaseCurrencyCode": "USD",
          "profile": {
              "traits": {
                  "knowledge": 0.575,
                  "lifestyle": 0.324,
                  "motivated": 0.575
              },
              "userAttributes": {
                  "demo": 65,
                  "diet": 512,
                  "lifestyle": 1,
                  "energy": 1,
                  "transport": 1,
                  "country": "IN"
              },
              "created": "2023-08-07T12:39:35.087Z",
              "surveys": {
                  "viewed": {
                      "onboardingVersion": 1.0
                  }
              },
              "persona": "5",
              "version": "1.0"
          }
      }
]
```

![Successful Response with profile](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_97.png)

8. You have successfully invoked the `/transaction-footprints` service from the Insomnia tool.  

## Test Cases for Transaction Footprints API {#test-cases-for-transaction-footprints-api}

Calculates carbon emission based on the payment transaction amount and the merchant category code.

### Pre-requisites {#pre-requisites-4}

Refer to the [Transaction Footprints Calculation](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/txn_footprint_calculation/index.md) use case.


API Reference: `GET /transaction-footprints`

<br />

### Test Case: Success-Calculate carbon footprint {#test-case-success-calculate-carbon-footprint}

##### Request {#request-5}

```json
[
  {
    "transactionId": "ee421c25-f928-4bf-b8843600b76b860d",
    "type": "AIIA",
    "amount": {
      "value": 100,
      "currencyCode": "USD"
    },
    "cardBrand": "OTH",
    "additionalInformation": [
      {
        "key": "aiiaCode",
        "value": "115"
      }
    ]
  },
  {
    "transactionId": "fdc4626c-f51e-4ba6-9728-c79ac1d9aec8",
    "mcc": "5962",
    "amount": {
      "value": 50,
      "currencyCode": "EUR"
    }
  }
]
```

##### Response {#response-8}

```json
[
  {
    "transactionId": "a213c72c-f13a-4930-a5f9-8cf765d42ca1",
    "cardBrand": "OTH",
    "scoreReference": "AIIA",
    "carbonEmissionInGrams": 469343.47,
    "carbonEmissionInOunces": 16555.62,
    "category": {
      "mainCategory": "Home,",
      "subCategory": "Utilities,",
      "sector": "Electric utilities,",
      "sectorCode": 151010
    }
  },
  {
    "transactionId": "fdc4626c-f51e-4ba6-9728-c79ac1d9aec8",
    "mcc": "5962",
    "scoreReference": "MCC",
    "carbonEmissionInGrams": 11905.7,
    "carbonEmissionInOunces": 419.96,
    "category": {
      "mainCategory": "Shopping",
      "subCategory": "Department Store",
      "sector": "Specialty Retail & Services",
      "sectorCode": "302"
    }
  }
]
```

### Test Case: Fail-Invalid request parameter {#test-case-fail-invalid-request-parameter-1}

##### Request {#request-6}

```json
[
  {
    "transactionId": "ee421c25-f928-4bf6-b884-3600b76b860d",
    "mcc": 399798,
    "amount": {
      "value": 100,
      "currencyCode": "USD"
    }
  }
]
```

##### Response {#response-9}

```json
{
   "Errors": {
     "Error": [
       {
         "Source": "Carbon-Calculator",
         "ReasonCode": "INVALID_REQUEST_PARAMETER",
         "Description": "One of the request parameters is invalid, try again with correct request.",
         "Recoverable": false,
         "Details": "transactions[0].mcc size must be between 1 and 4"
       }
     ]
   }
 }
```

### Test Case: Success-Calculate carbon footprint based on profile {#test-case-success-calculate-carbon-footprint-based-on-profile}

##### Request {#request-7}

```json
[
  {
    "transactionId": "yBNC8EJvzr",
    "type": "MCC",
    "mcc": "3000",
    "amount": {
      "currencyCode": "USD",
      "value": 10.35
    },
    "cardBaseCurrencyCode": "USD",
    "profile": {
        "traits": {
            "knowledge": 0.575,
            "lifestyle": 0.324,
            "motivated": 0.575
        },
        "userAttributes": {
            "demo": 65,
            "diet": 512,
            "lifestyle": 1,
            "energy": 1,
            "transport": 1,
            "country": "IN"
        },
        "created": "2023-08-07T12:39:35.087Z",
        "surveys": {
            "viewed": {
                "onboardingVersion": 1.0
            }
        },
        "persona": "5",
        "version": "1.0"
    }
  }
]
```

##### Response {#response-10}

```json
[
    {
        "carbonEmissionInGrams": 339495.86,
        "carbonEmissionInOunces": 11975.38,
        "transactionId": "yBNC8EJvzr",
        "mcc": "3000",
        "category": {
            "mainCategory": "Transport",
            "subCategory": "Flights",
            "sector": "Flights",
            "sectorCode": "351"
        },
        "scoreReference": "MCC",
        "profile": {
            "userAttributes": {
                "country": "IN",
                "demo": 65,
                "diet": 512,
                "energy": 1,
                "lifestyle": 1,
                "transport": 1
            },
            "created": "2023-08-07T12:39:35.087Z",
            "persona": "5",
            "surveys": {
                "viewed": {
                    "onboardingVersion": 1.0
                }
            },
            "traits": {
                "knowledge": 0.575,
                "lifestyle": 0.324,
                "motivated": 0.575
            },
            "version": "1.0"
        },
        "spendingAreaId": 40,
        "classification": {
            "id": "3000",
            "type": "mcc"
        }
    }
]
```

### Test Case: Invalid request parameter in profile object {#test-case-invalid-request-parameter-in-profile-object}

##### Request {#request-8}

```json
[
  {
    "transactionId": "yBNC8EJvzr",
    "type": "MCC",
    "mcc": "2000",
    "amount": {
      "currencyCode": "USD",
      "value": 10.35
    },
    "cardBaseCurrencyCode": "USD",
    "profile": {
        "traits": {
            "knowledge": 0.575,
            "lifestyle": 0.324,
            "motivated": 0.575
        },
        "created": "2023-08-07T12:39:35.087Z",
        "surveys": {
            "viewed": {
                "onboardingVersion": 1.0
            }
        },
        "persona": "5",
        "version": "1.0"
    }
  }
]
```

##### Response {#response-11}

```json
{
    "Errors": {
        "Error": [
            {
                "Source": "Carbon-Calculator",
                "ReasonCode": "INVALID_REQUEST_PARAMETER",
                "Description": "One of the request parameters is invalid, try again with correct request.",
                "Recoverable": false,
                "Details": "footprintsByTransactionData.transactionData[0].profile.userAttributes: must not be null"
            }
        ]
    }
}
```

## Invoking View Historical Transaction Footprints API using Insomnia {#invoking-view-historical-transaction-footprints-api-using-insomnia}

This section provides step-by-step directions to call the `/payment-cards/{payment_card_id}/transaction-footprints` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *View Historical Transaction Footprints* , select the request method as *GET* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_16.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_17.png)

3. Configure the request URL by copying and pasting the text **{{host}}/payment-cards/{payment_card_id}/transaction-footprints** in the request URL.  

   **NOTE:** Replace `{payment_card_id}` with the actual payment card ID for which we request historical transactions.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_18.png)

4. Configure request header and query parameters.  

   **NOTE:** Refer to the [API Reference](https://developer.mastercard.com/carbon-calculator/documentation/api-reference/index.md) section for more details on each parameter.
   ![Request Header](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_19.png)
   ![Request Query Parameters](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_20.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Send Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_21.png)
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_22.png)

6. You have successfully invoked the `/payment-cards/{payment_card_id}/transaction-footprints` service from the Insomnia tool.

## Test Cases for View Historical Transaction Footprints API {#test-cases-for-view-historical-transaction-footprints-api}

Allows a Service Provider to fetch historical transactions for a payment card. Note that maximum of one year of transactions can be retrieved using this API.

### Pre-requisites {#pre-requisites-5}

Refer to the [View Historical Transaction Footprints](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/historical_txn_footprint/index.md) use case.


API Reference: `GET /payment-cards/{payment_card_id}/transaction-footprints`

<br />

### Test Case: Success-Fetch Historical Transaction Footprints {#test-case-success-fetch-historical-transaction-footprints}

##### Response {#response-12}

```json
{
  "count": 2,
  "offset": 1,
  "limit": 2,
  "total": 5,
  "items": [
    {
      "transactionMetadata": {
        "id": "ee421c25-f928-4bf6-b884-3600b76b860d",
        "traceId": "9f52386ce297173ecfeb9120aabb0805bbeeb1350ce1de640864852e800bd206",
        "banknetReferenceNumber": "MPL0R6B2R",
        "banknetDate": "0525",
        "retrievalRefNumber": "MCC000100",
        "processingCode": "00",
        "dateAndTime": "2018-07-02T19:20+01:00",
        "merchantName": "ABC Store",
        "acquiringInstitutionCountryCode": "USA",
        "acquiringInstitutionCode": "12312312312",
        "amount": "25.50",
        "currencyCode": "USD",
        "indicator": "CL"
      },
      "transactionFootPrint": {
        "mcc": 3997,
        "carbonEmissionInGrams": 48.52,
        "carbonEmissionInOunces": 1.71,
        "category": {
          "mainCategory": "Lesure & Entertainment",
          "subCategory": "Hotels & Vacation",
          "sector": "Hotels, Motels & Resorts",
          "sectorCode": "604"
        },
        "scoreReference": "MCC"
      }
    },
    {
      "transactionMetadata": {
        "id": "fdc4626c-f51e-4ba6-9728-c79ac1d9aec8",
        "traceId": "af55386ce297173ecfeb9120aabb0805bbeeb1350ce1de640864852e800bd854",
        "banknetReferenceNumber": "MPL0R8C2A",
        "banknetDate": "0624",
        "retrievalRefNumber": "MCC000480",
        "processingCode": "01",
        "dateAndTime": "2019-12-25T19:20+01:00",
        "merchantName": "ABC Store",
        "acquiringInstitutionCountryCode": "USA",
        "acquiringInstitutionCode": "23423423423",
        "amount": "30.00",
        "currencyCode": "USD",
        "indicator": "CL"
      },
      "transactionFootPrint": {
        "mcc": 5962,
        "carbonEmissionInGrams": 27.98,
        "carbonEmissionInOunces": 0.99,
        "category": {
          "mainCategory": "Shopping",
          "subCategory": "Department Store",
          "sector": "Specialty Retail & Services",
          "sectorCode": "302"
        },
        "scoreReference": "MCC"
      }
    }
  ]
}
```

### Test Case: Success-Invalid request parameter {#test-case-success-invalid-request-parameter}

##### Response {#response-13}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "Payment card is not registered.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

### Test Case: Success-Invalid date range {#test-case-success-invalid-date-range}

##### Response {#response-14}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "INVALID_DATE_RANGE",
        "Description": "Requested date range is either invalid or exceeds one year limit. Try again with valid date range.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

## Invoking View Aggregate Transaction Footprints API using Insomnia {#invoking-view-aggregate-transaction-footprints-api-using-insomnia}

This section provides step-by-step directions to call the `/payment-cards/transaction-footprints/aggregates` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *View Aggregate Transaction Footprints* , select the request method as *POST* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_23.png)
   ![Request Method](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_24.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_25.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_26.png)

3. Configure the request URL by copying and pasting the text **{{host}}/payment-cards/transaction-footprints/aggregates** into the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_80_1.png)

4. Configure the request payload by copying and pasting the following JSON payload.

```json
{
  "aggregateType": 2,
  "paymentCardIds": [
    "411a4a00-49e2-461b-8784-bd08e1c2becf"
  ],
"crossPANAggregate": "Y",
"fromDate": "2024-10-18",
"toDate": "2024-11-14"
}
```

![Request Payload](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_81_1.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_82_1.png)

6. You have successfully invoked the `/payment-cards/transaction-footprints/aggregates` service from the Insomnia tool.

## Test Cases for View Aggregate Transaction Footprints API {#test-cases-for-view-aggregate-transaction-footprints-api}

Fetches carbon score for payment cards and aggregate the same on weekly and monthly basis.

### Pre-requisites {#pre-requisites-6}

Refer to the [View Aggregate Transaction Footprints](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/aggregate_txn_footprint/index.md) use case.


API Reference: `GET /payment-cards/transaction-footprints/aggregates`

<br />

### Test Case: Success-Aggregate Transaction Footprint {#test-case-success-aggregate-transaction-footprint}

##### Request {#request-9}

```json
{
  "aggregateType": 2,
  "crossPANAggregate": "Y",
  "paymentCardIds": [
     "76182790-092a-44d0-bb2b-23bacdfa0882",
     "da541e91-23a9-49a1-a500-5dc034cc18d7"
  ],
  "fromDate": "2022-01-01",
  "toDate": "2022-02-01"
}
```

##### Response {#response-15}

```json
{
  "aggregateTransactionFootprint": [
    {
      "paymentCardId": "da541e91-23a9-49a1-a500-5dc034cc18d7",
      "footprintAggregations": [
        {
          "carbonEmissionInGrams": 9524.56,
          "carbonEmissionInOunces": 335.96,
          "aggregateValue": "February|2022"
        },
        {
          "carbonEmissionInGrams": 540748.0,
          "carbonEmissionInOunces": 19074.28,
          "aggregateValue": "January|2022"
        }
      ]
    },
    {
      "paymentCardId": "76182790-092a-44d0-bb2b-23bacdfa0882",
      "footprintAggregations": [
        {
          "carbonEmissionInGrams": 3398.54,
          "carbonEmissionInOunces": 119.88,
          "aggregateValue": "February|2022"
        },
        {
          "carbonEmissionInGrams": 291991.76,
          "carbonEmissionInOunces": 10299.67,
          "aggregateValue": "January|2022"
        }
      ]
    }
  ],
  "crossPANAggregations": [
       {
         "carbonEmissionInGrams": 12923.10,
         "carbonEmissionInOunces": 455.84,
         "aggregateValue": "February|2022"
       },
       {
         "carbonEmissionInGrams": 832739.76,
         "carbonEmissionInOunces": 29373.95,
         "aggregateValue": "January|2022"
       }
  ]
}
```

### Test Case: Fail-Invalid request parameter {#test-case-fail-invalid-request-parameter-2}

##### Request {#request-10}

```json
{
  "aggregateType": 7,
  "crossPANAggregate": "Y",
  "paymentCardIds": [
     "76182790-092a-44d0-bb2b-23bacdfa0882",
     "da541e91-23a9-49a1-a500-5dc034cc18d7"
  ],
  "fromDate": "2022-01-01",
  "toDate": "2022-02-01"
}
```

##### Response {#response-16}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "aggregateType must be less than or equal to 3"
      }
    ]
  }
}
```

### Test Case: Fail-Payment card invalid or not found {#test-case-fail-payment-card-invalid-or-not-found-1}

##### Request {#request-11}

```json
{
  "aggregateType": "2",
  "crossPANAggregate": "N",
  "paymentCardIds": [
    "8a581a55-bcea-4c3e-8e0f-9b4726e5e6d3",
    "328b62d4-287c-4c9f-a05d-6d4a67f208d8",
    "b86fd2ba-c095-4acb-b9df-f3805655ba24"
  ],
     "fromDate": "2022-01-01",
     "toDate": "2022-02-01"
}
```

##### Response {#response-17}

```json
{
  "Errors": {
    "Error": [
      {
         "Source": "Service-Provider",
         "ReasonCode": "INVALID_REQUEST_PARAMETER",
         "Description": "Payment card id - [b86fd2ba-c095-4acb-b9df-f3805655ba24,328b62d4-287c-4c9f-a05d-6d4a67f208d8 ] is/are invalid or not found. Please try again with valid payment card id.",
         "Recoverable": false,
         "Details": ""
      }
    ]
  }
}
```

### Test Case: Fail-Invalid Date Range {#test-case-fail-invalid-date-range}

##### Request {#request-12}

```json
{
  "aggregateType": 1,
  "crossPANAggregate": "Y",
  "paymentCardIds": [
     "76182790-092a-44d0-bb2b-23bacdfa0882",
     "da541e91-23a9-49a1-a500-5dc034cc18d7"
  ],
  "fromDate": "2022-01-01",
  "toDate": "2023-08-01"
}
```

##### Response {#response-18}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider",
        "ReasonCode": "INVALID_DATE_RANGE",
        "Description": "Requested date range is either invalid or exceeds supported limit (i.e. 26 weeks for weekly aggregate and 12 months for monthly aggregate).",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

### Test Case: Fail-Invalid Date Format {#test-case-fail-invalid-date-format}

##### Request {#request-13}

```json
{
  "aggregateType": 1,
  "crossPANAggregate": "Y",
  "paymentCardIds": [
     "76182790-092a-44d0-bb2b-23bacdfa0882",
     "da541e91-23a9-49a1-a500-5dc034cc18d7"
  ],
  "fromDate": "01-01-2022",
  "toDate": "01-02-2022"
}
```

##### Response {#response-19}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "fromDate must match \"^((?:19|20)[0-9][0-9])-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$\""
      },
      {
        "Source": "Service-Provider",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "toDate must match \"^((?:19|20)[0-9][0-9])-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$\""
      }
    ]
  }
}
```

## Invoking View Service Provider Details API using Insomnia {#invoking-view-service-provider-details-api-using-insomnia}

This section provides step-by-step directions to call the `/service-providers` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *Get Service Provider Details* , select the request method as *GET* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_51.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_52.png)

3. Configure the request URL by copying and pasting the text **{{host}}/service-providers** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_53.png)

4. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_54.png)

5. You have successfully invoked the `/service-providers` service from the Insomnia tool.  

## Test Cases for View Service Provider Details API {#test-cases-for-view-service-provider-details-api}

Allows a registered Service Provider to fetch its information from the server.

### Pre-requisites {#pre-requisites-7}

Refer to the [View Service Provider Details](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/service_provider_details/index.md) use case.


API Reference: `GET /service-providers`

<br />

### Test Case: Success-View Service Provider {#test-case-success-view-service-provider}

##### Response {#response-20}

```json
{
  "clientId": "fjl2fxzsYl1OpvxkBItC9nVw1PSQc_b-eQMcmQFg011ab4b5",
  "customerId": "customer1",
  "customerName": "ABC Bank",
  "supportedAccountRange": "534403, 518145, 518152, 5403, 5424",
  "status": "ACTIVE",
  "cardHolderBase": "54123"
}
```

### Test Case: Fail-Service Provider Not Found {#test-case-fail-service-provider-not-found}

##### Response {#response-21}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider",
        "ReasonCode": "ACCOUNT_NOT_FOUND",
        "Description": "We cannot find the account which you are using to access this service. Kindly register your account or contact your Mastercard associate if you have already registered with us earlier.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

## Invoking Update Service Provider Details API using Insomnia {#invoking-update-service-provider-details-api-using-insomnia}

This section provides step-by-step directions to call the `/service-providers` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *Update Service Provider Details* , select the request method as *PUT* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_55.png)
   ![Request Method](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_56.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_57.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_58.png)

3. Configure the request URL by copying and pasting the text **{{host}}/service-providers** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_59.png)

4. Configure the request payload by copying and pasting the following JSON payload.

```json
{
  "customerName": "ABC Bank",
  "supportedAccountRange": "534403, 518145, 518152, 5403, 5424",
  "cardHolderBase": "1221"
}
```

![Request Payload](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_60.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_61.png)

6. You have successfully invoked the `/service-providers` service from the Insomnia tool.  

## Test Cases for Update Service Provider Details API {#test-cases-for-update-service-provider-details-api}

Allows a registered Service Provider to update its configuration on the server.

### Pre-requisites {#pre-requisites-8}

Refer to the [Update Service Provider Details](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/update_service_provider_details/index.md) use case.


API Reference: `PUT /service-providers`

<br />

### Test Case: Success-Update Service Provider {#test-case-success-update-service-provider}

##### Request {#request-14}

```json
{
  "customerName": "ABC Bank New",
  "supportedAccountRange": "534403, 518145, 518152, 5403, 5424",
  "cardHolderBase": "1221"
}
```

##### Response {#response-22}

```json
{
  "clientId": "fjl2fxzsYl1OpvxkBItC9nVw1PSQc_b-eQMcmQFg011ab4b5",
  "customerId": "customer1",
  "customerName": "ABC Bank New",
  "supportedAccountRange": "534403, 518145, 518152, 5403, 5424",
  "status": "ACTIVE",
  "cardHolderBase": "1221"
}
```

### Test Case: Fail-Invalid Request parameter {#test-case-fail-invalid-request-parameter-3}

##### Request {#request-15}

```json
{
  "customerName": "",
  "supportedAccountRange": "534403, 518145, 518152, 5403, 5424"
}
```

##### Response {#response-23}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "customerName must match \"^(?!\\s*$)[\\w]{1,200}(?:\\s[\\w]+)*$\""
      },
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "customerName size must be between 1 and 200"
      }
    ]
  }
}
```

### Test Case: Fail-Service Provider Not Found {#test-case-fail-service-provider-not-found-1}

##### Request {#request-16}

```json
{
  "customerName": "ABC Bank",
  "supportedAccountRange": "534403, 518145, 518152, 5403, 5424"
}
```

##### Response {#response-24}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider",
        "ReasonCode": "ACCOUNT_NOT_FOUND",
        "Description": "We cannot find the account which you are using to access this service. Kindly register your account or contact your Mastercard associate if you have already registered with us earlier.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

## Invoking Delete Payment Cards API using Insomnia {#invoking-delete-payment-cards-api-using-insomnia}

This section provides step-by-step directions to call the `/payment-card-deletions` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *Delete Payment Cards* , select the request method as *POST* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_37.png)
   ![Request Method](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_38.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_39.png)
   ![Request Created](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_40.png)

3. Configure the request URL by copying and pasting the text **{{host}}/payment-card-deletions** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_41.png)

4. Configure the request payload by copying and pasting the following JSON payload.

```json
[
  "d6b38160-9dc2-4443-befd-f11ace3e0fa7",
  "a5eeef93-9433-4b63-b0f2-61d874c74563",
  "0d60256f-cbab-4c4e-a9f8-7f43c22323cc",
  "d5f851bf-d0e1-4197-aa94-34a1a12d252f"
]
```

![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_42.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_49.png)

6. You have successfully invoked the `/payment-card-deletions` service from the Insomnia tool.  

## Test Cases for Delete Payment Cards API {#test-cases-for-delete-payment-cards-api}

Allows a registered Service Provider to delete one or more Payment Cards from its profile.

### Pre-requisites {#pre-requisites-9}

Refer to the [Delete Payment Cards (to be deprecated)](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/delete_payment_cards_deprecated/index.md) use case.


API Reference: `GET /payment-card-deletions`

<br />

### Test Case: Success-Delete Cards {#test-case-success-delete-cards}

##### Request {#request-17}

```json
[
  "c5d88571-ac15-465a-a0d8-1ad1327b9a06",
  "8a581a55-bcea-4c3e-8e0f-9b4726e5e6d3"
]
```

##### Response {#response-25}

Response Code : `202`

### Test Case: Fail-Invalid request parameter {#test-case-fail-invalid-request-parameter-4}

##### Request {#request-18}

```json
[
  "c5d88571-ac15-235a-a0d6-1ad1327b9a06",
  "8a581a55-bcea-233e-8e06-9b4726e5e6d3"
]
```

##### Response {#response-26}

```json
{
 "Errors": {
   "Error": [
     {
       "Source": "Service-Provider",
       "ReasonCode": "INVALID_REQUEST_PARAMETER",
       "Description": "One of the request parameters is invalid, try again with correct request.",
       "Recoverable": false,
       "Details": ""
     }
   ]
 }
}
```

## Invoking Surveys API using Insomnia {#invoking-surveys-api-using-insomnia}

This section provides step-by-step directions to call the `surveys` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request *Get Surveys* , click the **Rename** button, and select the request method as *GET* .
   ![Name and create Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_83.png)

3. Configure the request URL by copying and pasting the text **{{host}}/surveys** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_84.png)

4. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_87.png)

5. You have successfully invoked the `surveys` service from the Insomnia tool.  

## Test Cases for Surveys API {#test-cases-for-surveys-api}

Allows an issuer to fetch the survey from the server that can be answered by the consumer.

### Pre-requisites {#pre-requisites-10}

Refer to the [Surveys](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/engagement-services/surveys/index.md) use case.


API Reference: `GET /surveys`

<br />

### Test Case: Success-Surveys {#test-case-success-surveys}

##### Response {#response-27}

```json
{
    "language": "en",
    "type": "survey",
    "id": "onboarding",
    "version": "1.1",
    "survey": {
      "showQuestionNumber": "off",
      "showProgressBar": "top",
      "pages": [
        {
          "name": "page1",
          "questions": [
            {
              "type": "radiogroup",
              "name": "sex",
              "title": "What do you identify as?",
              "description": "",
              "choices": [
                {
                  "value": "demo.m",
                  "text": "Male"
                },
                {
                  "value": "demo.f",
                  "text": "Female"
                }
              ]
            }
          ]
        },
        {
          "name": "page2",
          "questions": [
            {
              "type": "dropdown",
              "name": "age",
              "title": "What age range are you in?",
              "description": "",
              "choices": [
                {
                  "value": "demo.lt10",
                  "text": "0-9"
                },
                {
                  "value": "demo.lt20",
                  "text": "10-19"
                },
                {
                  "value": "demo.lt30",
                  "text": "20-29"
                }
              ]
            }
          ]
        },
        {
          "name": "page3",
          "questions": [
            {
              "type": "dropdown",
              "name": "country",
              "title": "Which is your country of residence?",
              "description": "",
              "choices": [
                {
                  "value": "AF",
                  "text": "Afghanistan"
                },
                {
                  "value": "AX",
                  "text": "Åland Islands"
                },
                {
                  "value": "AL",
                  "text": "Albania"
                }
              ]
            }
          ]
        },
        {
          "name": "page4",
          "questions": [
            {
              "type": "radiogroup",
              "name": "interest",
              "title": "I am curious about my own carbon footprint and how I personally contribute to climate change",
              "description": "",
              "choices": [
                {
                  "value": "stronglyAgree",
                  "text": "Strongly agree"
                },
                {
                  "value": "somewhatAgree",
                  "text": "Somewhat agree"
                },
                {
                  "value": "neutral",
                  "text": "Neutral"
                }
              ]
            }
          ]
        },
        {
          "name": "page5",
          "questions": [
            {
              "type": "radiogroup",
              "name": "knowledge",
              "title": "I have good knowledge about climate change and its effects",
              "description": "",
              "choices": [
                {
                  "value": "stronglyAgree",
                  "text": "Strongly agree"
                },
                {
                  "value": "somewhatAgree",
                  "text": "Somewhat agree"
                },
                {
                  "value": "neutral",
                  "text": "Neutral"
                }
              ]
            }
          ]
        },
        {
          "name": "page6",
          "questions": [
            {
              "type": "radiogroup",
              "name": "diet",
              "title": "What best describes your diet?",
              "description": "",
              "choices": [
                {
                  "value": "diet.all",
                  "text": "I eat everything"
                },
                {
                  "value": "diet.meatlessDay",
                  "text": "One meatless day a week"
                },
                {
                  "value": "diet.avoidRed",
                  "text": "I try to avoid eating red meat"
                },
                {
                  "value": "diet.noRed",
                  "text": "I don't eat red meat"
                }
              ]
            }
          ]
        },
        {
          "name": "page7",
          "questions": [
            {
              "type": "radiogroup",
              "name": "renewableElectricity",
              "title": "Does your household use renewable electricity?",
              "description": "(e.g. solar, wind or hydro)",
              "choices": [
                {
                  "value": "energy.renewable",
                  "text": "Yes, we use a supplier of renewable electricity"
                },
                {
                  "value": "energy.selfProduced",
                  "text": "Yes, we produce our own renewable electricity"
                }
              ]
            }
          ]
        },
        {
          "name": "page8",
          "questions": [
            {
              "type": "radiogroup",
              "name": "haveCar",
              "title": "Do you have a car?",
              "description": "This only refers to cars you drive for personal or family needs, not a company car that is exclusively used professionally.",
              "choices": [
                {
                  "value": "transport.hasCar",
                  "text": "Yes"
                },
                {
                  "value": "transport.noCar",
                  "text": "No"
                }
              ]
            }
          ]
        },
        {
          "name": "page9",
          "visibleIf": "{haveCar} = 'transport.hasCar'",
          "questions": [
            {
              "type": "radiogroup",
              "name": "carFuel",
              "title": "What kind of car is it?",
              "description": "",
              "choices": [
                {
                  "value": "transport.petrol",
                  "text": "Petrol"
                },
                {
                  "value": "transport.diesel",
                  "text": "Diesel"
                },
                {
                  "value": "transport.bio",
                  "text": "Bio-fuel or bio-gas"
                }
              ]
            }
          ]
        },
        {
          "name": "page10",
          "questions": [
            {
              "type": "radiogroup",
              "name": "flyFrequency",
              "title": "How often do you travel by plane for personal or leisure purposes?",
              "description": "Do not include business travels.",
              "choices": [
                {
                  "value": "transport.twice",
                  "text": "A couple of times a year"
                }
              ]
            }
          ]
        }
      ]
    }
}
```

### Test Case: Fail-Service Provider Not Found {#test-case-fail-service-provider-not-found-2}

##### Response {#response-28}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider",
        "ReasonCode": "ACCOUNT_NOT_FOUND",
        "Description": "We cannot find the account which you are using to access this service. Kindly register your account or contact your Mastercard associate if you have already registered with us earlier.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

## Invoking Profiles API using Insomnia {#invoking-profiles-api-using-insomnia}

This section provides step-by-step directions to call the `profiles` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *Get Climate Profile* , select the request method as *POST* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_86.png)
   ![Body Type](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_88.png)

3. Configure the request URL by copying and pasting the text **{{host}}/profiles** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_89_1.png)

4. Configure the request payload by copying and pasting the following JSON payload.

```json
{
    "surveyioResults": {
        "sex": "demo.f",
        "age": "demo.lt30",
        "country": "GB",
        "interest": "stronglyAgree",
        "knowledge": "stronglyAgree",
        "diet": "diet.noRed",
        "renewableElectricity": "energy.selfProduced",
        "haveCar": "transport.hasCar",
        "carFuel": "transport.petrol",
        "flyFrequency": "transport.secondMonth",
        "shopFrequency": "lifestyle.shopVeryOften",
        "difference": "somewhatDisagree",
        "consciousPurchasingDecision": "somewhatAgree",
        "explainCarbonFootprint": "neutral"
    }
}
```

![Request Payload](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_91.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_90_1.png)

6. You have successfully invoked the `profiles` service from the Insomnia tool.  

## Test Cases for Profiles API {#test-cases-for-profiles-api}

Calculates the climate profile of the issuer based on survey answers.

### Pre-requisites {#pre-requisites-11}

Refer to the [Engagement Profiles](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/engagement-services/profiles/index.md) use case.


API Reference: `POST /profiles`

<br />

### Test Case: Success-Update Climate Profile {#test-case-success-update-climate-profile}

##### Request {#request-19}

```json
{
      "surveyioResults": {
          "sex": "demo.m",
          "age": "demo.lt50",
          "country": "IN",
          "interest": "stronglyAgree",
          "knowledge": "stronglyAgree",
          "diet": "diet.vegan",
          "renewableElectricity": "energy.idk",
          "haveCar": "transport.noCar",
          "flyFrequency": "transport.never",
          "shopFrequency": "lifestyle.shopRarely",
          "difference": "stronglyAgree",
          "consciousPurchasingDecision": "stronglyDisagree",
          "explainCarbonFootprint": "stronglyDisagree"
      }
}
```

##### Response {#response-29}

```json

{
  "profile": {
    "traits": {
      "knowledge": 0,
      "lifestyle": 0.683,
      "motivated": 0.3
    },
    "userAttributes": {
      "demo": 34,
      "diet": 16399,
      "lifestyle": 16,
      "energy": 0,
      "transport": 0,
      "country": "AF"
    },
    "created": "2024-01-19T09:31:08.065Z",
    "surveys": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    },
    "persona": "5",
    "benchmarks": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    }
  }
}
```

### Test Case: Fail-Invalid Request parameter {#test-case-fail-invalid-request-parameter-5}

##### Request {#request-20}

```json
{
  "surveyioResults": {
    "sex": "demo.f",
    "age": "demo.lt20",
    "country": "AX",
    "interest": "stronglyDisagree",
    "knowledge": "stronglyDisagree",
    "diet": "diet.vegan",
    "renewableElectricity": "energy.idk",
    "haveCar": "transport.noCar",
    "flyFrequency": "transport.mo",
    "shopFrequency": "lifestyle.shopRarely",
    "difference": "stronglyDisagree",
    "consciousPurchasingDecision": "stronglyDisagree",
    "explainCarbonFootprint": "stronglyDisagree"
  }
}
```

##### Response {#response-30}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Carbon-Calculator-Engagement-Services",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "surveyioResults.flyFrequency must be in valid format"
      }
    ]
  }
}
```

### Test Case: Fail-Service Provider Not Found {#test-case-fail-service-provider-not-found-3}

##### Request {#request-21}

```json
{
        "surveyioResults": {
            "sex": "demo.m",
            "age": "demo.lt50",
            "country": "IN",
            "interest": "stronglyAgree",
            "knowledge": "stronglyAgree",
            "diet": "diet.vegan",
            "renewableElectricity": "energy.idk",
            "haveCar": "transport.noCar",
            "flyFrequency": "transport.never",
            "shopFrequency": "lifestyle.shopRarely",
            "difference": "stronglyAgree",
            "consciousPurchasingDecision": "stronglyDisagree",
            "explainCarbonFootprint": "stronglyDisagree"
        }
}
```

##### Response {#response-31}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "ACCOUNT_NOT_FOUND",
        "Description": "We cannot find the account which you are using to access this service. Kindly register your account or contact your Mastercard associate if you have already registered with us earlier.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

## Invoking Personas API using Insomnia {#invoking-personas-api-using-insomnia}

This section provides step-by-step directions to call the `/personas` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *GET Personas* and click the **Rename** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_104.png)

3. Configure the request URL by copying and pasting the text **{{host}}/personas** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_105.png)

4. Configure the query parameters.  


   Note: Refer to the [API Reference](https://developer.mastercard.com/carbon-calculator/documentation/api-reference/index.md) section for more details on each parameter. ![Request Query Parameters](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_106.png)

   <br />

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_107.png)

6. You have successfully invoked the `/personas` service from the Insomnia tool.  

## Test Cases for Personas API {#test-cases-for-personas-api}

**Personas** delivers a list of available climate profile personas.

### Pre-requisites {#pre-requisites-12}

Refer to the [Personas](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/engagement-services/personas/index.md) use case.


API Reference: `GET /personas`

<br />

### Test Case: Success-Personas {#test-case-success-personas}

##### Request {#request-22}

    {{host}}/personas

##### Response {#response-32}

```json
{
  "items": [
    {
      "description": "Climate Focused individuals are confident in their understanding of climate change, highly motivated to take action, and actively demonstrate this through their lifestyle choices. This is the only persona knowledge, motivation and lifestyle are aligned.\n\nThey typically have above-average education and average income levels. These users are interested in all types variety of sustainable lifestyle solutions, particularly those with lower adoption rates, such as sustainable transportation options.",
      "id": "1",
      "language": "en",
      "title": "Climate Focused"
    },
    {
      "description": "Climate Initiates are motivated and confident in their understanding of sustainability but struggle to translate that knowledge into climate action. Their stuck on the wrong side of the intention-action gap.\n\nThey represent the wealthiest persona, with access to more resources, but also face numerous opportunities that might lead to unsustainable choices (lavish spending). While their intentions are good, self-restraint might not be their strongest point.",
      "id": "2",
      "language": "en",
      "title": "Climate Initiate"
    },
    {
      "description": "Curious Pragmatists are motivated to take climate action, but lack confidence in their sustainability knowledge. They are eager to learn more about climate change, often seeking general or superficial information.\n\nThese users are highly interested in sustainable lifestyle solutions, particularly those that are easier to adopt, such as sustainable shopping and food choices.",
      "id": "3",
      "language": "en",
      "title": "Curious Pragmatist"
    },
    {
      "description": "Experience Seekers shows little concern for climate change and take little to no action.\n\nThey have above-average income, but exhibit very low trust in banks as partners for climate action. Despite their lack of engagement in climate action, Experience Seekers can still be attracted by financial incentives, high-quality products, and sustainable lifestyle solutions related to shopping.",
      "id": "4",
      "language": "en",
      "title": "Experience Seeker"
    },
    {
      "description": "Green by Accident individuals are not particularly motivated to take climate action but display some sustainable behaviors, likely driven by a desire to save money.\n\nThey have below-average education and income levels and show average interest in sustainable lifestyle solutions compared to the general US population.",
      "id": "5",
      "language": "en",
      "title": "Green by Accident"
    }
  ],
  "language": "en",
  "total": 5
}
```

### Test Case: Fail-Invalid Request parameter {#test-case-fail-invalid-request-parameter-6}

##### Request {#request-23}

    {{host}}/personas?language=abc

##### Response {#response-33}

```json
{
    "Errors": {
        "Error": [
            {
                "Source": "Carbon-Calculator-Engagement-Services",
                "ReasonCode": "INVALID_REQUEST_PARAMETER",
                "Description": "One of the request parameters is invalid, try again with correct request.",
                "Recoverable": false,
                "Details": "Language codes must follow ISO 639-1 format (example: 'en')"
            }
        ]
    }
}
```

## Invoking Insights API using Insomnia {#invoking-insights-api-using-insomnia}

This section provides step-by-step directions to call the `/insights` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request *POST Insights* , select the request method as *POST* , the body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_92.png)

3. Configure the request URL by copying and pasting the text **{{host}}/insights** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_94.png)

4. Configure the request payload by copying and pasting the following JSON payload.

```json
{
  "mainCategory": "shopping",
  "main": "shopping",
  "docc": "30101",
  "spendingAreaId": "30",
  "subCategory": "clothes",
  "branding": "",
  "heading": "true",
  "language": "en",
  "profile": {
    "traits": {
      "knowledge": 0.75,
      "lifestyle": 0.246,
      "motivated": 0.675
    },
    "userAttributes": {
      "demo": 257,
      "diet": 1024,
      "lifestyle": 2,
      "energy": 0,
      "transport": 20517,
      "country": "GB"
    },

    "created": "2024-03-27T09:25:27.539Z",
    "surveys": {
      "viewed": {
        "onboardingVersion": 1
      }
    },
    "persona": "2"
  }
}
```

![Request Payload](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_117.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_116.png)

6. Configure the URL by adding the insight ID as a path parameter to get details of a specific insight.
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_118.png)

7. You have successfully invoked the `/insights` service from the Insomnia tool.  

## Test Cases for Insights API {#test-cases-for-insights-api}

Delivers insights and other suggestions that can inform the consumer about what they can do to reduce their footprint.

### Pre-requisites {#pre-requisites-13}

Refer to the [Insights](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/engagement-services/insights/index.md) use case.


API Reference: `POST /insights`


API Reference: `GET /insights/{id}`

<br />

### Test Case: Success-Insights {#test-case-success-insights}

##### Request {#request-24}

```json
{
  "mainCategory": "shopping",
  "main": "shopping",
  "docc": "",
  "spendingAreaId": "30",
  "subCategory": "clothes",
  "branding": "branding",
  "heading": true,
  "language": "en",
  "profile": {
    "traits": {
      "knowledge": 0.65,
      "lifestyle": 0.445,
      "motivated": 0.683
    },
    "userAttributes": {
      "demo": 66,
      "diet": 256,
      "lifestyle": 4,
      "energy": 12288,
      "transport": 36933,
      "country": "AX"
    },
    "created": "2024-01-31T10:57:36.161Z",
    "surveys": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    },
    "persona": "3",
    "benchmarks": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    }
  }
}
```

##### Response {#response-34}

```json
{
  "language": "en",
  "insights": [
    {
      "id": "T13",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T14",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T2",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T23",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T24",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T6",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T78",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T79",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T92",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T20",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T21",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T75",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T76",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T77",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    },
    {
      "id": "T9",
      "mainCategory": "shopping",
      "subCategory": "clothes",
      "seen": false,
      "spendingAreaId": "30"
    }
  ],
  "total": 15,
  "profile": {
    "traits": {
      "knowledge": 0.65,
      "lifestyle": 0.445,
      "motivated": 0.683
    },
    "userAttributes": {
      "demo": 66,
      "diet": 256,
      "lifestyle": 4,
      "energy": 12288,
      "transport": 36933,
      "country": "AX"
    },
    "created": "2024-01-31T10:57:36.161Z",
    "surveys": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    },
    "persona": "3",
    "benchmarks": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    }
  }
}
```

### Test Case: Success-Insight by ID {#test-case-success-insight-by-id}

##### Request {#request-25}

    {{host}}/insights/{id}

##### Response {#response-35}

```json
{
  "id": "T101",
  "language": "en",
  "heading": "Recycle your e-waste",
  "content": "Voluptate eiusmod culpa incididunt excepteur anim ipsum et ex elit laboris esse. Nostrud proident culpa exercitation eu dolore consectetur sit amet cillum veniam enim duis ut. Qui mollit fugiat tempor deserunt occaecat fugiat adipisicing ex cupidatat duis commodo id ea. Dolor laboris eu commodo ea reprehenderit in nisi proident. Fugiat cupidatat excepteur et ullamco anim. Cillum fugiat commodo ipsum consequat irure proident tempor nisi tempor ad.\nOccaecat est pariatur cillum commodo incididunt exercitation laboris consectetur eu mollit incididunt. Adipisicing quis incididunt mollit esse officia dolore fugiat reprehenderit nisi do velit ea. Id cillum consectetur mollit eu laborum nostrud nulla sint Lorem voluptate id.",
  "notification": "",
  "mainCategory": "home",
  "subCategory": "electronics",
  "spendingAreaId": "10",
  "source": "The Global E-waste Monitor 2020",
  "sourceDescription": "The Global E-waste Monitor 2020",
  "sourceLink": "https://ewastemonitor.info/wp-content/uploads/2020/11/GEM_2020_def_july1_low.pdf",
  "sourceDate": "2020-07-01"
}
```

### Test Case: Fail-Invalid Request parameter-request body {#test-case-fail-invalid-request-parameter-request-body}

##### Request {#request-26}

```json
{
  "mainCategory": "shopping",
  "main": "shopping",
  "docc": "30101",
  "spendingAreaId": "30",
  "subCategory": "clothes",
  "branding": "",
  "heading": "truee",
  "language": "en",
  "profile": {
    "traits": {
      "knowledge": 0.75,
      "lifestyle": 0.246,
      "motivated": 0.675
    },
    "userAttributes": {
      "demo": 257,
      "diet": 1024,
      "lifestyle": 2,
      "energy": 0,
      "transport": 20517,
      "country": "GB"
    },

    "created": "2024-03-27T09:25:27.539Z",
    "surveys": {
      "viewed": {
        "onboardingVersion": 1
      }
    },
    "persona": "2"
  }
}
```

##### Response {#response-36}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Carbon-Calculator-Engagement-Services",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "profile.userAttributes must not be null"
      }
    ]
  }
}
```

### Test Case: Fail-Invalid Request parameter-query parameter {#test-case-fail-invalid-request-parameter-query-parameter}

##### Request {#request-27}

    {{host}}/insights?version=1.0&heading="234"

##### Response {#response-37}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Carbon-Calculator-Engagement-Services",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "heading must be a `boolean` type"
      }
    ]
  }
}
```

### Test Case: Fail-Insight not found {#test-case-fail-insight-not-found}

##### Request {#request-28}

    {{host}}/insights/T1000

##### Response {#response-38}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Carbon-Calculator-Engagement-Services",
        "ReasonCode": "ITEM_NOT_FOUND",
        "Description": "Insight Item not found for the provided id",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

## Invoking Comparisons API using Insomnia {#invoking-comparisons-api-using-insomnia}

This section provides step-by-step directions to call the `/comparisons` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *GET Comparisons* and click the **Rename** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_108.png)

3. Configure the request URL by copying and pasting the text **{{host}}/comparisons** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_109.png)

4. Configure the query parameters.  


   Note: Refer to the [API Reference](https://developer.mastercard.com/carbon-calculator/documentation/api-reference/index.md) section for more details on each parameter. ![Request Query Parameters](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_110.png)

   <br />

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_111.png)

6. You have successfully invoked the `/comparisons` service from the Insomnia tool.  

## Test Cases for Comparisons API {#test-cases-for-comparisons-api}

**Comparisons** provide a comparison of CO2 emissions in tonnes with everyday life examples.

### Pre-requisites {#pre-requisites-14}

Refer to the [Comparisons](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/engagement-services/comparisons/index.md) use case.


API Reference: `GET /comparisons`

<br />

### Test Case: Success-Comparisons {#test-case-success-comparisons}

##### Request {#request-29}

    {{host}}/comparisons

##### Response {#response-39}

```json
{
    "content": "Dolore proident reprehenderit mollit aute tempor anim fugiat voluptate laboris. Nulla cupidatat ex eu aute id tempor pariatur sint ad laboris exercitation qui. Est consectetur excepteur sint nisi velit proident anim nisi ipsum exercitation eiusmod.\nQuis ex anim magna do amet cupidatat ex labore exercitation minim duis consequat occaecat. Officia commodo tempor eiusmod velit id eu pariatur laboris aliqua proident et dolore officia. Tempor laborum ipsum tempor consectetur excepteur ea non ut cillum aliqua. Exercitation mollit proident voluptate aliquip deserunt nisi sit proident minim irure tempor sit velit excepteur. Velit incididunt in dolore minim eiusmod incididunt.",
    "description": "Emissions related to production",
    "id": "9",
    "language": "en",
    "mainCategory": "shopping",
    "source": "ADEME, France, \"Modélisation et évaluation du poids carbone de produits de consommation et biens d'équipement\"",
    "sourceLink": "https://librairie.ademe.fr/consommer-autrement/1190-modelisation-et-evaluation-du-poids-carbone-de-produits-de-consommation-et-biens-d-equipement.html",
    "spendingAreaId": "30",
    "tonne": "1"
}
```

### Test Case: Fail-Invalid request parameter {#test-case-fail-invalid-request-parameter-7}

##### Request {#request-30}

    {{host}}/comparisons?language=abc

##### Response {#response-40}

```json
{
    "Errors": {
        "Error": [
            {
                "Source": "Carbon-Calculator-Engagement-Services",
                "ReasonCode": "INVALID_REQUEST_PARAMETER",
                "Description": "One of the request parameters is invalid, try again with correct request.",
                "Recoverable": false,
                "Details": "Language codes must follow ISO 639-1 format (example: 'en')"
            }
        ]
    }
}
```

### Test Case: Fail-Invalid request parameter-tonne {#test-case-fail-invalid-request-parameter-tonne}

##### Request {#request-31}

    {{host}}/comparisons?tonne=7

##### Response {#response-41}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Carbon-Calculator-Engagement-Services",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "Tonne must be one of the following values: 1, 5, 10"
      }
    ]
  }
}
```

### Test Case: Comparison not found {#test-case-comparison-not-found}

##### Request {#request-32}

    {{host}}/comparisons?main_category=electronics

##### Response {#response-42}

```json
{}
```

## Invoking Benchmarks API using Insomnia {#invoking-benchmarks-api-using-insomnia}

This section provides step-by-step directions to call the `/benchmarks` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request *GET Benchmarks* , select the request method as *GET* , the body type as *JSON* and click the**Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_100.png)

3. Configure the request URL by copying and pasting the text **{{host}}/benchmarks** in the request URL.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_101.png)

4. Configure the query parameters.  


   Note: Refer to the [API Reference](https://developer.mastercard.com/carbon-calculator/documentation/api-reference/index.md) section for more details on each parameter. ![Request Query Parameters](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_102.png)

   <br />

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_119.png)

6. You have successfully invoked the `/benchmarks` service from the Insomnia tool.  

## Test Cases for Benchmarks API {#test-cases-for-benchmarks-api}

Delivers country-based consumption figures based on your country of origin.

### Pre-requisites {#pre-requisites-15}

Refer to the [Benchmarks](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/engagement-services/benchmarks/index.md) use case.


API Reference: `GET /benchmarks`

<br />

### Test Case: Success-Benchmarks {#test-case-success-benchmarks}

##### Request {#request-33}

    {{host}}/benchmarks?country=US&period=year

##### Response {#response-43}

```json
{
  "id": "US",
  "emission": {
    "yearly": 15.471
  },
  "parisAgreement": {
    "yearly": 2.5
  }
}
```

### Test Case: Fail-Invalid period {#test-case-fail-invalid-period}

##### Request {#request-34}

    {{host}}/benchmarks?country=US&period=abc

##### Response {#response-44}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Carbon-Calculator-Engagement-Services",
        "ReasonCode": "INVALID_REQUEST_PARAMETER",
        "Description": "One of the request parameters is invalid, try again with correct request.",
        "Recoverable": false,
        "Details": "Period: Accepted values are 'month' and 'year'"
      }
    ]
  }
}
```

### Invoking Payment Cards Profiles API using Insomnia {#invoking-payment-cards-profiles-api-using-insomnia}

This section provides step-by-step directions to call the `payment-cards profiles` service from the Insomnia tool.

1. Click the **+** dropdown button and select the **New Request** option to create a new request.
   ![New Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_15.png)

2. Name the request as *POST Payment Cards Profile* , select the request method as *POST* , body type as *JSON* and click the **Create** button.
   ![Name Request](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_120.png)

3. Configure the request URL by copying and pasting the text **{{host}}/{payment_card_id}/profiles** in the request URL and adding the payment card id in the path parameter.
   ![Request URL](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_113.png)

4. Configure the request payload by copying and pasting the following JSON payload.

```json
{
    "profile": {
        "traits": {
            "knowledge": 0,
            "lifestyle": 0.683,
            "motivated": 0.3
        },
        "userAttributes": {
            "demo": 34,
            "diet": 16399,
            "lifestyle": 16,
            "energy": 0,
            "transport": 0,
            "country": "AF"
        },
        "created": "2024-01-19T09:31:08.065Z",
        "surveys": {
            "key1": {
                "key2": 1,
                "key3": 2
          }
        },
        "persona": "5",
        "benchmarks": {
            "key1": {
                "key2": 1,
                "key3": 2
            }
        }
    }
}
```

![Request Payload](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_114.png)

5. Click the **Send** button to submit the request. You should see a successful response with **200 OK** .
   ![Successful Response](https://static.developer.mastercard.com/content/carbon-calculator/Images/insomnia/insomnia_115.png)

6. You have successfully invoked the `payment-cards profiles` service from the Insomnia tool.  

## Test Cases for Payment Cards Profiles API {#test-cases-for-payment-cards-profiles-api}

The profile service calculates a climate profile based on the answers from a survey obtained from the surveys service.That profile will store with the provided payment card.

### Pre-requisites {#pre-requisites-16}

Refer to the [Payment Cards Profiles](https://developer.mastercard.com/carbon-calculator/documentation/use-cases/payment_cards_profiles/index.md) use case.


API Reference: `POST /payment-cards/{payment_card_id}/profiles`

<br />

### Test Case: Success-Add Climate Profile {#test-case-success-add-climate-profile}

##### Request {#request-35}

```json
{
  "profile": {
    "traits": {
      "knowledge": 0,
      "lifestyle": 0.683,
      "motivated": 0.3
    },
    "userAttributes": {
      "demo": 34,
      "diet": 16399,
      "lifestyle": 16,
      "energy": 0,
      "transport": 0,
      "country": "AF"
    },
    "created": "2024-01-19T09:31:08.065Z",
    "surveys": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    },
    "persona": "5",
    "benchmarks": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    }
  }
}
```

##### Response {#response-45}

```json

{
  "paymentCardId": "c5d88571-ac15-465a-a0d8-1ad1327b9a06",
  "profile": {
    "traits": {
      "knowledge": 0,
      "lifestyle": 0.683,
      "motivated": 0.3
    },
    "userAttributes": {
      "demo": 34,
      "diet": 16399,
      "lifestyle": 16,
      "energy": 0,
      "transport": 0,
      "country": "AF"
    },
    "created": "2024-01-19T09:31:08.065Z",
    "surveys": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    },
    "persona": "5",
    "benchmarks": {
      "key1": {
        "key2": 1,
        "key3": 2
      }
    }
  }
}
```

### Test Case: Fail-Payment Card Invalid {#test-case-fail-payment-card-invalid}

##### Response {#response-46}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "PAYMENT CARD ID INACTIVE",
        "Description": "Payment card id is - c2c76ec0-4056-44ba-b14f-6654c9ba5722 INACTIVE . Please try again with ACTIVE payment card id.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

### Test Case: Fail-Service Provider Not Found {#test-case-fail-service-provider-not-found-4}

##### Response {#response-47}

```json
{
  "Errors": {
    "Error": [
      {
        "Source": "Service-Provider-Mgmt",
        "ReasonCode": "ACCOUNT_NOT_FOUND",
        "Description": "We cannot find the account which you are using to access this service. Kindly register your account or contact your Mastercard associate if you have already registered with us earlier.",
        "Recoverable": false,
        "Details": ""
      }
    ]
  }
}
```

### Build an end-to-end application {#build-an-end-to-end-application}

This tutorial helps to create a simple Java application that makes an API call to the Carbon Calculator API in the Sandbox environment.
>
> #### What you will learn {#what-you-will-learn-2}
>
> * How to set up the environment to develop a simple Java application.
> * How to generate an API client using the [OpenAPI Generator](https://openapi-generator.tech/).
> * How to perform [payload encryption](https://developer.mastercard.com/platform/documentation/security-and-authentication/securing-sensitive-data-using-payload-encryption/)?
> * How to make an API call?
>
> #### Estimated time to complete this tutorial {#estimated-time-to-complete-this-tutorial-1}
>
> * 15-20 minutes
Tip: You can refer to the [reference app](https://developer.mastercard.com/carbon-calculator/documentation/reference-app/index.md) which we have created for you.

### Environment Set up {#environment-set-up}

#### 1. Pre-requisites {#1-pre-requisites}

To complete this tutorial, you will need:

* [JDK 17](https://www.java.com/en/) or later.
* [IntelliJ IDEA](https://www.jetbrains.com/idea/) (or any other IDE of your choice).
* Mastercard Developers account with access to the Carbon Calculator API.
* Carbon Calculator Open API specification (Retrieved by clicking the 'Open Specification' [here](https://developer.mastercard.com/carbon-calculator/documentation/api-reference/index.md)).

#### 2. Create a Maven Project {#2-create-a-maven-project}

For this tutorial, IntelliJ IDEA as the IDE is used.

* In IntelliJ IDEA, create a new Maven project which sets your directory structure automatically.
* Provide an ArtifactId and a Project name as per your choice.

#### 3. Add Resources {#3-add-resources}

* Add the Carbon Calculator Open API specification to your Maven project resources folder.
* Add the generated Sandbox key (**.p12 file** ) and encryption cert (**.pem file**) to your Maven project resources folder. (This is generated while creating your project on Mastercard Developers)
* Your Maven project directory structure should appear as:

![Directory Structure](https://static.developer.mastercard.com/content/carbon-calculator/Images/ref-app/directory-structure.PNG)

#### 4. Update pom.xml file {#4-update-pomxml-file}

* In your IDE, add the [OpenAPI Generator Maven plugin](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin) to your project **pom.xml** file. Use the Plugin config as shown below: Note: [OpenAPI Generator](https://openapi-generator.tech/) generates API client libraries using OpenAPI Specification. It provides multiple generators and library templates to support multiple languages and frameworks. We will be using the Java generator for this project.

* Plugin

```Plugin
<build>
    <plugins>
    <plugin>
            <groupId>org.openapitools</groupId>
            <artifactId>openapi-generator-maven-plugin</artifactId>
                <version>4.3.1</version>
            <executions>
                <execution>
                    <id>Carbon Calculator REST Client</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>${project.basedir}/src/main/resources/carbon-calculator.yaml</inputSpec>
                        <generatorName>java</generatorName>
                        <generateApiTests>false</generateApiTests>
                        <generateModelTests>false</generateModelTests>
                        <configOptions>
                            <sourceFolder>src/gen/java/main</sourceFolder>
                            <hideGenerationTimestamp>true</hideGenerationTimestamp>
                                <lombok>true</lombok>
                                <interfaceOnly>true</interfaceOnly>
                                <validateSpec>false</validateSpec>
                            <dateLibrary>java8</dateLibrary>
                                <useSpringBoot3>true</useSpringBoot3>
                                <delegatePattern>false</delegatePattern>
                                <generatedConstructorWithRequiredArgs>false</generatedConstructorWithRequiredArgs>
                                <useJakartaEe>true</useJakartaEe>
                        </configOptions>
                        <typeMappings>
                            <typeMapping>Date=LocalDate</typeMapping>
                        </typeMappings>
                    </configuration>
                </execution>
            </executions>
    </plugin>
    </plugins>
</build>
```

* Add the following dependencies to your **pom.xml** file.
  * Dependencies

  ```Dependencies
  <properties>
        <java.version>17</java.version>
          <maven.compiler.source>${java.version}</maven.compiler.source>
          <maven.compiler.target>${java.version}</maven.compiler.target>
        <gson-fire-version>1.8.4</gson-fire-version>
        <jackson-datatype-jsr310.version>2.17.2</jackson-datatype-jsr310.version>
          <swagger-core-version>1.6.2</swagger-core-version>
        <okhttp-version>3.14.7</okhttp-version>
        <gson-version>2.10</gson-version>
          <commons-lang3-version>3.11</commons-lang3-version>
          <threetenbp-version>1.4.3</threetenbp-version>
          <javax-annotation-version>1.3.2</javax-annotation-version>
          <oauth1-signer-version>1.5.0</oauth1-signer-version>
        <client-encryption-version>1.7.0</client-encryption-version>
          <junit-version>4.13.1</junit-version>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
          <dependency>
              <groupId>io.swagger</groupId>
              <artifactId>swagger-annotations</artifactId>
              <version>${swagger-core-version}</version>
          </dependency>
          <dependency>
              <groupId>com.google.code.findbugs</groupId>
              <artifactId>jsr305</artifactId>
              <version>3.0.2</version>
          </dependency>
          <dependency>
          <groupId>com.squareup.okhttp3</groupId>
          <artifactId>logging-interceptor</artifactId>
          <version>${okhttp-version}</version>
          <exclusions>
              <exclusion>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
              </exclusion>
          </exclusions>
          </dependency>
          <dependency>
              <groupId>com.google.code.gson</groupId>
              <artifactId>gson</artifactId>
              <version>${gson-version}</version>
          </dependency>
          <dependency>
              <groupId>io.gsonfire</groupId>
              <artifactId>gson-fire</artifactId>
              <version>${gson-fire-version}</version>
          </dependency>
          <dependency>
              <groupId>org.apache.commons</groupId>
              <artifactId>commons-lang3</artifactId>
              <version>${commons-lang3-version}</version>
          </dependency>
          <dependency>
              <groupId>javax.annotation</groupId>
              <artifactId>javax.annotation-api</artifactId>
              <version>${javax-annotation-version}</version>
          </dependency>
          <dependency>
              <groupId>com.mastercard.developer</groupId>
              <artifactId>oauth1-signer</artifactId>
              <version>${oauth1-signer-version}</version>
          </dependency>
          <dependency>
              <groupId>com.mastercard.developer</groupId>
              <artifactId>client-encryption</artifactId>
              <version>${client-encryption-version}</version>
          </dependency>
      <dependency>
          <groupId>com.squareup.okio</groupId>
          <artifactId>okio</artifactId>
          <version>1.17.6</version>
      </dependency>
      <dependency>
          <groupId>com.squareup.okhttp3</groupId>
          <artifactId>okhttp</artifactId>
          <version>${okhttp-version}</version>
        <exclusions>
            <exclusion>
              <groupId>com.squareup.okio</groupId>
              <artifactId>okio</artifactId>
            </exclusion>
            <exclusion>
              <groupId>org.jetbrains.kotlin</groupId>
              <artifactId>kotlin-stdlib</artifactId>
            </exclusion>
        </exclusions>
      </dependency>
  </dependencies>
  ```

> Refer to the page for more information on [Generating and Configuring a Mastercard API Client](https://developer.mastercard.com/platform/documentation/security-and-authentication/generating-and-configuring-a-mastercard-api-client/#overview).

### Generating the API Client {#generating-the-api-client}

1. Now that you have all the dependencies you need, you can generate the source code. You can navigate to the project root directory within a terminal window and run **mvn clean compile**.


![Maven Command](https://static.developer.mastercard.com/content/carbon-calculator/Images/ref-app/MavenCommand.PNG)

2. A new folder named **target** is created within your root directory which contains classes generated for the schemas and API calls defined within the OpenAPI Specification. The generated classes can be found in the target folder as shown below.


![Generated Sources](https://static.developer.mastercard.com/content/carbon-calculator/Images/ref-app/GeneratedModels.PNG)

### Making an API Call {#making-an-api-call}

1. Under the src/main/java/ folder path, create a Java file named **CarbonCalculatorMain.java**.

2. To make the API call, you need to make your OAuth credentials available to the program to use.

   * Java

   ```java
   String consumerKey = "<Consumer_key from your Mastercard Developers' project>";
     String signingKeyFilePath = "<Path to p12 file>";
     String encryptionCertPath = "Path to pem file";
     String signingKeyAlias = "<key_alias>";
     String signingKeyPassword = "<key_password>";
     PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias, signingKeyPassword);
   ```

   <br />

3. Optional. If the endpoint you are calling requires [payload encryption](https://developer.mastercard.com/platform/documentation/security-and-authentication/securing-sensitive-data-using-payload-encryption/), you need to configure an interceptor to encrypt the request body.

4. To configure the interceptor, load the encryption certificate and create the configuration object.

   * Java

   ```java
   Certificate encryptionCertificate = EncryptionUtils.loadEncryptionCertificate(encryptionCertPath);

     FieldLevelEncryptionConfig config = FieldLevelEncryptionConfigBuilder
     .aFieldLevelEncryptionConfig()
     .withEncryptionCertificate(encryptionCertificate)
     .withEncryptionPath("$", "$")
     .withEncryptedValueFieldName("encryptedData")
     .withEncryptedKeyFieldName("encryptedKey")
     .withOaepPaddingDigestAlgorithmFieldName("oaepHashingAlgorithm")
     .withOaepPaddingDigestAlgorithm("SHA-256")
     .withEncryptionKeyFingerprintFieldName("publicKeyFingerprint")
     .withIvFieldName("iv")
     .withFieldValueEncoding(FieldLevelEncryptionConfig.FieldValueEncoding.HEX)
     .build();
   ```

   <br />

5. Instantiate a client with your authentication credentials and configuration object as interceptors before you can send it.

   * Java

   ```java
   ApiClient client = new ApiClient();
     client.setBasePath("https://sandbox.api.mastercard.com/carbon");
     client.setDebugging(false);
     client.setHttpClient(client.getHttpClient()
     .newBuilder()
     .addInterceptor(new OkHttpFieldLevelEncryptionInterceptor(config))
     .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
     .build());

     PaymentCardApi addCardApi = new PaymentCardApi(client);   
   ```

   <br />

Below is the sample code block of CarbonCalculatorMain.java which you will have after completion of the above steps.
* Java

```java
package com.mastercard.developers.carboncalculator;

import com.mastercard.developer.encryption.FieldLevelEncryptionConfig;
import com.mastercard.developer.encryption.FieldLevelEncryptionConfigBuilder;
import com.mastercard.developer.interceptors.OkHttpFieldLevelEncryptionInterceptor;
import com.mastercard.developer.interceptors.OkHttpOAuth1Interceptor;
import com.mastercard.developer.utils.AuthenticationUtils;
import com.mastercard.developer.utils.EncryptionUtils;
import org.openapitools.client.ApiClient;
import org.openapitools.client.api.EnvironmentalImpactApi;
import org.openapitools.client.api.PaymentCardApi;
import org.openapitools.client.api.ServiceProviderApi;
import org.openapitools.client.api.SupportedParametersApi;
import org.openapitools.client.model.*;

import java.math.BigDecimal;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CarbonCalculatorMain {

    public static void main(String[] args) throws Exception {

        EnvironmentalImpactApi environmentalImpactApi = new EnvironmentalImpactApi(getApiClient(false));

        System.out.println("Calling Calculate Transaction Footprint API");

      List<TransactionData> transactions = new ArrayList<>();
      transactions.add((TransactionData) new TransactionData().cardBrand("MA").transactionId("TX-1").mcc("3000").amount(
        new Amount().currencyCode("USD").value(new BigDecimal(150))));

      List<TransactionFootprintData> transactionFootprints = environmentalImpactApi.footprintsByTransactionData(
        transactions);


        List<TransactionFootprint> transactionFootprints = environmentalImpactApi.footprintsByTransactionData(
                transactions);

        System.out.println("Calculate Transaction Footprint API response : " + transactionFootprints);

        System.out.println("------------------------------------------------------------------");

        SupportedParametersApi supportedParametersApi = new SupportedParametersApi(getApiClient(false));

        System.out.println("Calling Get Supported Currencies API");

        List<Currency> currencies = supportedParametersApi.getSupportedCurrencies();

        System.out.println("Get Supported Currencies API response : " + currencies);


        System.out.println("------------------------------------------------------------------");

        System.out.println("Calling Get Supported Merchant Categories API");

        List<MerchantCategory> mcSupportedMerchantCategories = supportedParametersApi.getSupportedMerchantCategories();

        System.out.println("Get Supported Merchant Categories API response : " + mcSupportedMerchantCategories);

        System.out.println("------------------------------------------------------------------");

        ServiceProviderApi serviceProviderApi = new ServiceProviderApi(getApiClient(false));

        System.out.println("Calling Get Service Provider API");

        ServiceProvider serviceProviderInfo = serviceProviderApi.getServiceProviderById();

        System.out.println("Get Service Provider API response: " + serviceProviderInfo);
       ServiceProviderApi serviceProviderApi = new ServiceProviderApi(getApiClient(false));
       System.out.println("Calling Update Service Provider API");
       ServiceProviderConfig serviceProviderConfig=new ServiceProviderConfig();

      serviceProviderConfig.setCardHolderBase("200");

      ServiceProvider serviceProviderDetails = serviceProviderApi.updateServiceProvider(serviceProviderConfig);


      System.out.println("Update Service Provider API response: " + serviceProviderDetails);


        PaymentCardApi addCardApi = new PaymentCardApi(getApiClient(true));

        System.out.println("------------------------------------------------------------------");

        System.out.println("Calling Add Card API");

        PaymentCard paymentCard = new PaymentCard().fpan("5167567321874451").cardBaseCurrency("USD");

        PaymentCardReference paymentCardReference = addCardApi.registerPaymentCard(paymentCard);

        System.out.println("Add Card API response: " + paymentCardReference);

        System.out.println("------------------------------------------------------------------");

        PaymentCardApi paymentCardApi = new PaymentCardApi(getApiClient(false));

        System.out.println("Calling Aggregate API");

       AggregateSearchCriteria aggregateSearchCriteria = new AggregateSearchCriteria().paymentCardIds(
        Collections.singletonList(paymentCardReference.getPaymentCardId())).aggregateType(2);

      AggregateTransactionFootprints aggregateTransactionFootprintList = paymentCardApi.getPaymentCardAggregateTransactions(serviceProviderDetails.getClientId(),aggregateSearchCriteria,"CC","5e4b7f904d2820f688c67ef9fc0035");
        System.out.println("Aggregate API response: " + aggregateTransactionFootprintList);

        System.out.println("------------------------------------------------------------------");

        System.out.println("Calling Historical Transaction Footprint API");

        HistoricalTransactionFootprints historicalTransactionFootprintList = paymentCardApi.getPaymentCardTransactionHistory(
                paymentCardReference.getPaymentCardId(), "2020-09-19", "2020-10-01",
                0,
                50);

        System.out.println("Historical Transaction Footprint response: " + historicalTransactionFootprintList);

      System.out.println("------------------------------------------------------------------");

      System.out.println("Calling Payment Card Profiles API");

      CardClimateProfile cardClimateProfile = getPaymentCardProfilesRequest();
      PaymentCardProfile paymentCardProfile = serviceProviderApi.addProfileToPaymentCard(paymentCardReference.getPaymentCardId(), cardClimateProfile);

      System.out.println("Payment Card Profiles API response: " + paymentCardProfile);

    }

  private static CardClimateProfile getPaymentCardProfilesRequest() {
    CardClimateProfile cardClimateProfile = new CardClimateProfile();
    ClimateProfile climateProfile = new ClimateProfile();
    ClimateProfileUserAttributes userAttributes = new ClimateProfileUserAttributes();
    ClimateProfileTraits climateProfileTraits = new ClimateProfileTraits();
    userAttributes.setCountry("AX");
    userAttributes.setDemo(new BigDecimal("34"));
    userAttributes.setEnergy(new BigDecimal("34"));
    userAttributes.setDiet(new BigDecimal("34"));
    userAttributes.setTransport(new BigDecimal("34"));
    userAttributes.setLifestyle(new BigDecimal("34"));

    climateProfile.setUserAttributes(userAttributes);
    climateProfile.setBenchmarks(Map.of("Benchmark", "Test"));
    climateProfile.setCreated(OffsetDateTime.parse("2024-05-04T18:45:35.943Z"));
    climateProfileTraits.knowledge(BigDecimal.valueOf(0.575));
    climateProfileTraits.lifestyle(BigDecimal.valueOf(0.324));
    climateProfileTraits.motivated(BigDecimal.valueOf(0.617));
    climateProfile.setTraits(climateProfileTraits);
    climateProfile.setPersona("2");
    climateProfile.setSurveys(new HashMap<String, Object>());

    cardClimateProfile.setProfile(climateProfile);
    return cardClimateProfile;
  }

    private static ApiClient getApiClient(boolean enableEncryption) throws Exception {
        ApiClient client = new ApiClient();

        String consumerKey = "Consumer key";
        String signingKeyFilePath = "Path to p12 file";
        String encryptionCertPath = "Path to pem file";
        String signingKeyAlias = "keyalias";
        String signingKeyPassword = "keystorepassword";
        PrivateKey signingKey = AuthenticationUtils.loadSigningKey(signingKeyFilePath, signingKeyAlias,
                                                                   signingKeyPassword);

        client.setBasePath("https://sandbox.api.mastercard.com/carbon");
        client.setDebugging(false);


        if (enableEncryption) {
            client.setHttpClient(client.getHttpClient()
                                        .newBuilder()
                                        .addInterceptor(new OkHttpFieldLevelEncryptionInterceptor(
                                                        getEncryptionConfig(encryptionCertPath)))
                                        .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
                                        .build());
        } else {
            client.setHttpClient(client.getHttpClient()
                                        .newBuilder()
                                        .addInterceptor(new OkHttpOAuth1Interceptor(consumerKey, signingKey))
                                        .build());
        }

        return client;
    }

    private static FieldLevelEncryptionConfig getEncryptionConfig(String encryptionCertPath) {
        FieldLevelEncryptionConfig config = null;

        try {
            Certificate encryptionCertificate = EncryptionUtils.loadEncryptionCertificate(encryptionCertPath);

            config = FieldLevelEncryptionConfigBuilder
                    .aFieldLevelEncryptionConfig()
                    .withEncryptionCertificate(encryptionCertificate)
                    .withEncryptionPath("$", "$")
                    .withEncryptedValueFieldName("encryptedData")
                    .withEncryptedKeyFieldName("encryptedKey")
                    .withOaepPaddingDigestAlgorithmFieldName("oaepHashingAlgorithm")
                    .withOaepPaddingDigestAlgorithm("SHA-256")
                    .withEncryptionKeyFingerprintFieldName("publicKeyFingerprint")
                    .withIvFieldName("iv")
                    .withFieldValueEncoding(FieldLevelEncryptionConfig.FieldValueEncoding.HEX)
                    .build();

        } catch (Exception e) {
            // Log and resolve this error.
        }
        return config;
    }

}

```

<br />

