# Authentication
Source: https://docs.mattildapayments.com/guides/api/authentication
API authentication basics and best practices.
The API uses **Bearer (Token) Authentication** to authenticate any
request. These tokens are **JSON Web Tokens (JWT)** which need
to be created server side by your application.
## Create an API key
To sign a JWT you will need to create a new API key-pair in your dashboard.
To create a new API key visit the **Integrations** panel in your dashboard and click the **Add API key** button.
You can store the API key with your code or store it in a secure environment accessible to your
application.
## Server-side SDKs
By far the easiest way to create a JWT is with one of our server-side SDKs.
> **[C# SDK](https://github.com/gr4vy/gr4vy-csharp)**
>
> Make server-side calls with our C# SDK.
> **[Go SDK](https://github.com/gr4vy/gr4vy-go)**
>
> Make server-side calls with our Go SDK.
> **[Java SDK](https://github.com/gr4vy/gr4vy-java)**
>
> Make server-side calls with our Java SDK.
> **[PHP SDK](https://github.com/gr4vy/gr4vy-php)**
>
> Make server-side calls with our PHP SDK.
> **[Python SDK](https://github.com/gr4vy/gr4vy-python)**
>
> Make server-side calls with our Python SDK.
> **[TypeScript SDK](https://github.com/gr4vy/gr4vy-typescript)**
>
> Make server and client-side API calls with our TypeScript SDK.
## Development Tools
> **[CLI](/guides/tools/cli)**
>
> Create API tokens and checkout sessions with our command line interface tool.
> **[Postman](/guides/tools/postman)**
>
> Start exploring our API using our official Postman collection.
## Without SDKs
It is also [possible to generate the JWT](./jwts) without our SDKs
using any number of open source JWT libraries.
# Environments
Source: https://docs.mattildapayments.com/guides/api/environments
Sandbox and Production environments within an instance.
Each instance has two environments.
* `production` - The environment intended for use within your live application.
* `sandbox` - The environment intended for use by developers to test
transactions and within your test or quality assurance systems.
These two environments have separate infrastructures so resources such as buyers
and payment services are not shared between them. This also means that there are
different hostnames for `sandbox` and `production` APIs and dashboards.
The hostnames for the APIs are as follows:
| Environment | Hostname |
| - | - |
| `sandbox` | `api.sandbox.mattildapayments.com` |
| `production` | `api.mattildapayments.com` |
You can test payment services, card rules, and other settings in the `sandbox`
environment, before migrating them to the `production` environment.
## Why environments?
Environments are an essential part of any development process. Your developer
might run your application on their development machine, and to try and test
the integration they will want to try and create some payments. To stop your
dashboard from being populated with lots of testing data it would be best
for the developer to create their test transactions against the `sandbox`
environment instead.
Similarly, you might want to run either automated or manual tests against the
API as part of QA and testing. To stop this from interfering with your live
environments you could set these tests to run against the `sandbox` environment.
## Environments and payment service APIs
The environment determines which payment service API environment that
should connect to. For example, Braintree transactions made in the
`sandbox` environment is processed by the Braintree sandbox environment, while
transactions made in the `production` environment are processed by the Braintree
live environment.
Other actions such as registering a digital wallet are also dependent on the
environment. Apple Pay digital wallets registered using the `sandbox`
environment will be registered with Apple Pay's sandbox environment. This wallet
will not be recognized by Apple Pay's live environment and thus cannot be used in
`production`.
In short, the `production` environment always connects to the live API of a
payment service, whereas the `sandbox` environment always connects to its
sandbox API.
# Transaction error codes
Source: https://docs.mattildapayments.com/guides/api/error-codes
A list of all error codes for transactions.
A transaction's `error_code` value can be null (for successful transactions) or one
of the following for failed and declined transactions.
## Core failures
Our system can decline or fail a transaction, in contrast to a connector or payment service rejecting the transaction. When this happens,
one of the following error codes can be set as the `error_code` value.
| `error_code` | Description |
| :- | :- |
| `incomplete_buyer_approval` | Occurs when a buyer approval redirection times out, this normally means the buyer has closed the redirect page/popup without authenticating. This error code can take up to 10 minutes from the time the buyer closes the redirect page / popup to appear |
| `failed_buyer_approval` | Occurs when a buyer fails to authenticate through 3DS. This transaction can be attempted again |
| `missing_redirect_url` | Occurs when a transaction requires a redirect but was created without `payment_method.redirect_url`. Add the `payment_method.redirect_url` and retry |
| `flow_decline` | Occurs when a transaction is declined by a Flow rule. This could be due to fraud or an alternate system configuration declining the transaction |
| `all_attempts_skipped` | Occurs when a transaction fails because no outcome in the matched Flow rule can be used to process the transaction reliably. To avoid this, make sure to define there is a default suitable outcome for each possible transaction scenario |
## Connector declines
When a payment service declines or fails the transaction the following `error_code` values can be set based on the response received
from the payment service. The original values received from the payment service will be available in the `raw_response_*` fields of
a transaction record.
> [!NOTE]
>
> The amount column in the tables below specifies the `amount` that can be used
> to simulate the `error_code` when using the **Card simulator** connector.
| `error_code` | Description | Simulator amount | Retriable? |
| :- | :- | :- | :- |
| `canceled_payment_method` | The payment method reported lost, stolen, or otherwise canceled, request another payment method | 200001 | |
| `expired_authorization` | The authorization has expired, create a new authorization and use the new one | 200004 | |
| `expired_payment_method` | The payment method has expired, use another payment method | 200005 | |
| `incorrect_billing_address` | The billing address does not match the account. Prompt the customer to correct the billing address and retry | 200006 | |
| `incorrect_country` | The country code was rejected by the service or issuer, request another payment method | 200007 | Yes |
| `incorrect_currency` | The currency code was rejected by the service or issuer, request another payment method | 200008 | Yes |
| `incorrect_cvv` | The CVV was incorrect. Prompt the customer to correct the CVV and retry | 200009 | |
| `incorrect_expiry_date` | The expiry date is incorrect or the payment method has expired. Prompt the customer to correct the expiry date and retry or request another payment method | 200010 | |
| `insufficient_funds` | The amount exceeds the available balance on the payment method. Prompt the customer to check their balance | 200011 | |
| `issuer_decline` | The payment was declined by the issuer. Prompt the customer to check with their issuer | 200012 | Yes |
| `other_decline` | The transaction failed for an unknown reason, may succeed if retried | 200013 | Yes |
| `refused_transaction` | The transaction was refused due to legal reasons (e.g. watch list, embargo, sanctions), request another payment method | 200015 | |
| `service_decline` | The payment was declined by service, request another payment method | 200016 | Yes |
| `suspected_fraud` | The service flagged the transaction as suspected fraud. Prompt the customer to check with their issuer | 200017 | |
## Connector failures
| `error_code` | Description | Simulator amount | Retriable? |
| :- | :- | :- | :- |
| `cancelled_buyer_approval` | The transaction was canceled by the customer | 200022 | |
| `disputed_transaction` | The transaction cannot be refunded as a chargeback has been initiated | 200002 | |
| `duplicate_transaction` | The transaction is a duplicate of a previous transaction. Check to ensure the transaction was submitted only once | 200003 | |
| `insufficient_service_permissions` | The service credentials lack permission to perform the requested action, check relevant configuration | 300001 | Yes |
| `invalid_amount` | The amount not supported by service, check relevant configuration | 300002 | Yes |
| `invalid_payment_method` | The payment method is not supported by the service (e.g. card scheme is not supported), request another payment method | 300003 | Yes |
| `invalid_service_configuration` | The service is incorrectly configured, check relevant configuration | 300004 | Yes |
| `invalid_service_credentials` | The service credentials are not valid, check relevant configuration | 300005 | |
| `invalid_service_response` | The service response could not be parsed , check relevant configuration | 300006 | Yes |
| `invalid_tax_identifier` | The tax identifier is invalid (e.g. GB VAT number is in an invalid format, or is of the wrong kind), correct identifier | 300007 | |
| `missing_billing_address` | The billing address is required. Add billing address and retry | 300008 | Yes |
| `missing_cvv` | The CVV is required. Add CVV and retry | 300009 | Yes |
| `missing_shipping_address` | The shipping address is required. Add shipping address and retry | 300010 | Yes |
| `missing_tax_identifier` | The tax identifier is required. Add tax identifier and retry | 300011 | Yes |
| `refund_period_expired` | The refund can not be performed due to the refund period expiring, credit the customer in another way | 300012 | |
| `requires_buyer_authentication` | Additional credentials were requested by the issuer, for example, the security code (CVV). Add these credentials and retry | 200014 | |
| `service_error` | The service reported an internal server error or upstream processing error, check relevant configuration | 300013 | Yes |
| `service_network_error` | The service was unreachable or experienced a timeout, wait before retrying | 300014 | Yes |
| `service_rate_limit` | The service responded with a rate-limiting error, wait before retrying | 300015 | Yes |
| `internal_error` | An internal error has occurred, check relevant configuration | 400001 | |
| `invalid_billing_address` | The billing address is invalid. Correct billing address and retry | 400002 | |
| `invalid_operation` | The service/method is not implemented, and operation is not supported for this request, check relevant configuration | 400003 | Yes |
| `invalid_request_parameters` | The one or more request parameters are invalid, check payload and retry | 400004 | |
| `invalid_service_request` | The service request could not be parsed, check payload and retry | 400005 | Yes |
| `invalid_shipping_address` | The shipping address is invalid. Correct shipping address and retry | 400006 | |
| `service_resource_conflict` | The service could not create a resource due to a conflict, check relevant configuration | 400007 | Yes |
| `unavailable_payment_method` | The payment method is temporarily frozen or otherwise unavailable. Prompt the customer to check with their issuer or request another payment method | 200018 | |
| `unexpected_state` | The service is configured in an unexpected state, check relevant configuration | 400008 | |
| `unknown_error` | An unknown error occurred, check relevant configuration | 400009 | |
| `unknown_payment_method` | The account is unknown, request another payment method | 200019 | Yes |
| `unknown_service_resource` | The resource could not be found by the service, check relevant configuration | 400010 | Yes |
| `unrecognised_country` | The country is not valid, correct the country and retry | 400013 | |
| `unrecognised_currency` | The currency is not valid, correct the currency and retry | 400014 | |
| `unrecognised_payment_method` | The payment method is not valid, request another payment method | 400015 | |
| `unrecognised_scheme` | The payment scheme is not valid, request another payment method | 400016 | |
| `unsupported_country` | The country is not supported by the service, correct country and retry | 400011 | Yes |
| `unsupported_currency` | The currency is not supported by the service, correct currency and retry | 400012 | Yes |
| `unsupported_payment_method` | The payment method is not supported by the service (e.g. card scheme is not supported), request another payment method | 200021 | |
| `unsupported_scheme` | The payment scheme is not supported by the service, request another payment method | 400017 | |
| `unsupported_transaction` | The payment method does not support this type of purchase (e.g. gambling is restricted), request another payment method | 200020 | |
## Connector Capture / Void / Refund
| `error_code` | Description | Simulator amount | Retriable? |
| :- | :- | :- | :- |
| `service_network_error` | \[Capture] The service was unreachable or experienced a timeout, wait before retrying | 500001 | |
| `refused_transaction` | \[Capture] The transaction was refused | 500002 | |
| `service_network_error` | \[Void] The service was unreachable or experienced a timeout, wait before retrying | 510001 | |
| `issuer_decline` | \[Void] The payment was declined by the issuer. Prompt the customer to check with their issuer | 510002 | |
| `disputed_transaction` | \[Refund] The transaction cannot be refunded as a chargeback has been initiated | 520001 | |
| `issuer_decline` | \[Refund] The payment was declined by the issuer. Prompt the customer to check with their issuer | 520002 | |
| `service_error` | \[Refund] The service reported an internal server error or upstream processing error | 520003 | |
| `service_decline` | \[Capture] The service declined the transaction | 530001 | |
| `service_error` | \[Capture] The service reported an internal server error or upstream processing error | 530002 | |
# Error handling
Source: https://docs.mattildapayments.com/guides/api/errors
Best practices on handling errors and other exceptions.
In some situations, the API may return an error. In general, errors can be classified as either server-side or client-side errors.
## Client errors
Our [API reference](/reference/errors/client-errors) has more detail on the format of client errors. The [List 4XX errors](/reference/logs/list-api-error-logs) API can be used to see the latest client errors and the associated requests.
## Server errors
Our [API reference](/reference/errors/server-errors) has more detail on the format of server errors.
# Idempotent Requests
Source: https://docs.mattildapayments.com/guides/api/idempotent-requests
Best practices on handling retries in an idempotent way.
The API supports idempotent requests allowing the safe retrying of
requests without accidentally performing the same operation again. When making an
idempotent request, if an error occurs in the request to the API (such as
a timeout or loss of connection), you can safely retry the request without the
risk of creating a second resource or performing the update twice.
Idempotency works by storing the status code and body of the first
response for a given idempotency key, regardless of whether the request
succeeded or failed. Subsequent requests with the same idempotency key will
return the same response.
An idempotency key is a unique key generated by you that the API uses to
identify subsequent retries of the same request. We recommend using V4 UUIDs,
or another random string with enough entropy to avoid collisions. Idempotency
keys can be up to 255 characters long, and remain valid for 24 hours, after
which the idempotency key may be reused for another request.
The response of an idempotent request is only saved if the API started
executing. If your request fails validation or the request conflicts with
another that was performed concurrently, no response is saved. It is safe to
retry these requests.
> [!WARNING]
>
> Currently, only the `POST /transactions` endpoint supports idempotent requests.
## Making an idempotent request
To make an idempotent request, specify the `Idempotency-Key` header in the
request.
```bash theme={"dark"}
curl -i -X POST "https://api.mattildapayments.com/transactions" \
-H "Authorization: Bearer [JWT]" \
-H "Idempotency-Key: bffa9ce6-7a8a-449c-889a-65bd2ee86903" \
-d "{...}"
```
> [!NOTE]
>
> Most of [our SDKs](./authentication) support passing through this header on the `POST transactions` call.
## Concurrent requests
When making an idempotent request using the same `Idemoptency-Key` as a previous
request, and the original request is still being processed, you will receive an
error. You can safely retry this request. We recommend applying an exponential
back-off when retrying transactions.
```json theme={"dark"}
{
"type": "error",
"code": "concurrent_request",
"status": 409,
"message": "A request with this idempotency key is still being processed. Retry later.",
"details": []
}
```
## Conflicting requests
When making an idempotent request using the same `Idempotency-Key` as a previous
request, and the request is not the same (for example, the request body is
different), you will receive an error. Retrying this request will not change the
error response. You should check your request.
```json theme={"dark"}
{
"type": "error",
"code": "bad_request",
"status": 400,
"message": "Idempotency key already in use.",
"details": []
}
```
# IP Address Forwarding
Source: https://docs.mattildapayments.com/guides/api/ip-address-forwarding
Best practices on handling the original IP address for a transaction.
Some payment service providers will require the IP address of the buyer to be
sent to them for anti fraud purposes.
## Embed
By default, when using [Embed](/guides/payments/embed/options) the IP address of the buyer will
be passed to the payment service automatically by us where needed.
## Server-to-server
When you are creating transactions on behalf of a buyer via your own server
without the use of Embed, you can pass the IP address of the buyer to us via
the `X-Forwarded-For` header.
```sh theme={"dark"}
curl --header "X-Forwarded-For: 192.168.0.2" https://api.mattildapayments.com/...
```
> [!NOTE]
>
> Most of [our SDKs](./authentication) support passing through this header on the `POST transactions` call.
We will automatically accept this header and pass it to the payment service
where needed.
> [!WARNING]
>
> Not all endpoints pass the IP address to a connector. It is recommended
> to send the IP address whenever it is available.
# Authentication with JWTs
Source: https://docs.mattildapayments.com/guides/api/jwts
The API uses **Bearer (Token) Authentication** to authenticate any
request. These tokens are **JSON Web Tokens (JWT)** which need
to be created server side by your application. By far the easiest way to create a JWT
is with one of our [server-side SDKs](./authentication) but it is also
possible to generate the JWT without our SDKs using any number of open source JWT libraries.
This document defines our API specification for authentication, JWT claims, and signature mechanisms.
## Authenticate an API call
Every API endpoint that requires authentication expects an `authorization` HTTP-header
with a signed JWT token as its value (prefixed with `bearer`).
```bash theme={"dark"}
curl -i -X GET "https://api.mattildapayments.com/transactions" \
-H "authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
```
## Create an API key
To sign a JWT you will need to create a new API key-pair in your dashboard.
To create a new API key visit the **Integrations** panel in your dashboard and click the **Add API key** button.
You can store the API key with your code or store it in a secure environment accessible to your
application.

### Merchants access
When selecting an API key, if your instance has **Multi Merchant** enabled then you can select whether the API key can
access **All merchants** or only one. We recommend you restrict an API key to only one merchant account when integrating
into Embed, our SDKs, or our e-commerce platforms like Magento, Salesforce Commerce Cloud, and Commerce Tools.
### Permissions
When selecting an API key, you can select whether to generate a key that has access to all APIs within the merchants it has access to (**Full access**)
or only to APIs used for processing payments (**Processing only**). We recommend you use the **Processing only** for any API keys with our e-commerce platforms
like Magento, Salesforce Commerce Cloud, and Commerce Tools.
> [!NOTE]
>
> API access can be further reduced by setting a restrictive set of
> [scopes](#scopes) on the JWT.
### Algorithm
Our API supports 2 algorithms for signing JWTs: ECDSA and RSA. We recommend you use ECDSA unless your environment
does not support this stronger and newer algorithm. The RSA algorithm is available for those environments
that do not support ECDSA. RSA keys provide considerably less security for the same key size and are currently not
supported by our SDKs.
## Generate JWT
You might not want to use one of our SDKs, or an SDK in your
language might not be available. In those cases you can construct, and sign the
JWT with one of the many libraries available on [`jwt.io`](https://jwt.io).
At the high level a JWT is build up out of 3 pieces:
* A **header** defining the algorithm and key used to create the JWT.
* A set of **claims** that define the token's scope and other permissions.
* A cryptographic **signature** based on the header and the claims, signed using
your private key.
Combine, these 3 pieces make up the JSON Web Token (JWT). See
[`jwt.io`](https://jwt.io) for more details on the specification and available
libraries for generating JWTs.
### JWT header
The JWT header defines the type of encryption algorithm as well as the private
key used to generate the signature.
```json theme={"dark"}
{
"typ": "JWT",
"alg": "ES512", // OR RS512 depending on your key
"kid": "d757c76acbd74b56"
}
```
> [!NOTE]
>
> The `typ` and `alg` are fixed and do not allow for other values. The `kid` is
> the ID of your private key, which you can find in the **Integrations** panel of
> your dashboard.
### JWT claims
The claims define when the token was created and what access it has.
```json theme={"dark"}
{
"iss": "My JWT Generation Tool",
"nbf": 1607976645,
"exp": 1607977245,
"jti": "0fe1fb1b-2f7e-4c8d-b0eb-aae5d0ec98f7",
"scopes": ["transactions.read"],
"embed": {
"amount": "200",
"currency": "MXN",
"buyer_id": "d757c76a-cbd7-4b56-95a3-40125b51b29c",
"metadata": { "key": "value" },
"cart_items": [
{
"name": "Joust Duffle Bag",
"quantity": "1",
"unit_amount": "9000",
"tax_amount": "0"
}
]
}
}
```
### Claims
The API supports the following JWT claims.
| | Description | Required |
| - | :- | :- |
| `iss` | A unique ID that represents your code making this call. This helps identify what library made an API call to mattilda Pay. | Yes |
| `nbf` | The UNIX timestamp (in seconds) that this token was created at. | Yes |
| `exp` | The UNIX timestamp (in seconds) that this token expires at. | Yes |
| `iat` | An optional UNIX timestamp (in seconds) for your internal use to indicate when the token was issued. | No |
| `jti` | A random unique ID used for cryptographic entropy. This needs to be unique for each JWT. | Yes |
| `scopes` | A list of scopes that give this token access to the API. | Yes |
| `embed` | A dictionary of key-value pairs used to pin the amount, currency, and buyer info for use in Embed. | No |
| `checkout_session_id` | The ID of a checkout session. This can be used to tie multiple transactions together as having originated from the same session. | No |
> [!NOTE]
>
> **Timestamps**
>
> Please be aware that the `nbf`, `exp`, and `iat` values are UNIX timestamps defined as seconds since January 1st, 1970 (UTC). Some programming languages will return UNIX timestamps as milliseconds,
> requiring the removal of the last 3 digits.
### Scopes
The API supports the following values for the `scopes` claims.
| Scope | Description |
| :- | :- |
| `*.read` | Allows read-access to any resource. This is used by default in the SDKs |
| `*.write` | Allows write-access to any resource. This is used by default in the SDKs. This does not also allow read access. |
| `{resource_name}.read` | Allows read-access to a type or resource. For example, `payment-services.read` enabled read-access for buyers data. |
| `{resource_name}.write` | Allows write-access to a type or resource. For example, `payment-services.write` enabled write-access for buyers data. This does not also allow read access. |
| `embed` | A scope that represents all the access needed by Embed. |
The following resource names are recognized. Please see the reference documentation for more details as to what scope
is required per endpoint.
* `anti-fraud-services`
* `api-logs`
* `buyers`
* `buyers.billing-details`
* `card-scheme-definitions`
* `checkout-sessions`
* `digital-wallets`
* `flows`
* `payment-methods`
* `payment-method-definitions`
* `payment-options`
* `payment-service-definitions`
* `payment-services`
* `reports`
* `transactions`
### Signature & assembly
Finally, the JWT signature is generated by appending the Base64 encoded header
and claims (separated with a `.`) and run it through the key's algorithm.
```bash ECDSA theme={"dark"}
ECDSASHA512(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
public_key,
private_key
)
```
```bash RSA theme={"dark"}
RSASHA512(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
public_key,
private_key
)
```
The assembled JWT is then formed by appending the Base64 encoded header, claims,
and signature separated by a full stop.
```
base64UrlEncode(header) + "." + base64UrlEncode(payload) + "." + base64UrlEncode(signature)
```
# Pagination
Source: https://docs.mattildapayments.com/guides/api/pagination
Best practices on handling pagination in the API.
Many of the API endpoints support cursor-based pagination. When a page is
requested, the response will include cursors for the next and previous page of
results.
```json Response theme={"dark"}
{
"items": [
{
"id": "42074b2a-d2fa-417a-b7cf-5776b069689d",
"type": "buyer",
"display_name": "Gerry Vine",
"external_identifier": null,
"created_at": "2021-03-12T15:05:27.199271+00:00",
"updated_at": "2021-03-12T15:05:27.199271+00:00"
},
{
"id": "9e2e7380-5177-4b8e-8677-3854bf94d6c3",
"type": "buyer",
"display_name": "Retha Palm",
"external_identifier": null,
"created_at": "2021-03-12T10:47:51.989637+00:00",
"updated_at": "2021-03-12T10:47:51.989637+00:00"
},
...
],
"limit": 20,
"next_cursor": "eQA2M2E2ZmQwZS1lYzhkLTQ3ZWItYjI0Yy0zMDlhYzg0OTViNTMAMjAyMS0wMi0yN1QyMjoyNDo1MS4wMTIxNTA",
"previous_cursor": null
}
```
> [!NOTE]
>
> All of [our SDKs](./authentication) have built-in pagination support. Please see the individual GitHub documentation for your preferred SDK for more details.
## Using cursors
If present, the `next_cursor` and `previous_cursor` values can be used to
request the next and previous page of results by passing the `cursor` query
parameter with the value of either cursor.
```bash theme={"dark"}
curl -i -X GET "https://api.mattildapayments.com/buyers?cursor=eQA2M2E2ZmQwZS1lYzhkLTQ3ZWItYjI0Yy0zMDlhYzg0OTViNTMAMjAyMS0wMi0yN1QyMjoyNDo1MS4wMTIxNTA" \
-H "Authorization: Bearer [JWT_TOKEN]"
```
## Page limits
Any of the APIs that support cursor pagination also support the `limit` query
parameter to control the number of items returned. Check the reference
documentation for each endpoint for the range of limit values allowed.
```bash theme={"dark"}
curl -i -X GET "https://api.mattildapayments.com/buyers?limit=1" \
-H "Authorization: Bearer [JWT_TOKEN]"
```
```json theme={"dark"}
{
"items": [
{
"id": "42074b2a-d2fa-417a-b7cf-5776b069689d",
"type": "buyer",
"display_name": "Gerry Vine",
"external_identifier": null,
"created_at": "2021-03-12T15:05:27.199271+00:00",
"updated_at": "2021-03-12T15:05:27.199271+00:00"
}
],
"limit": 1,
"next_cursor": "cAA5ZTJlNzM4MC01MTc3LTRiOGUtODY3Ny0zODU0YmY5NGQ2YzMAMjAyMS0wMy0xMlQxMDo0Nzo1MS45ODk2Mzc",
"previous_cursor": null
}
```
# Rate limiting
Source: https://docs.mattildapayments.com/guides/api/rate-limiting
Rate limits and enumeration prevention
Our system does not apply any rate limits for server-to-server API calls. Instead,
we aim to grow your system with you to handle the throughput needs of your business.
That said, we do apply certain rate limits on browser/app-to-server API calls in order
to prevent enumeration attacks, preventing a malicious party from enumerating credit, debit,
or scheme cards to check their validity.
## Enumeration prevention
In order to prevent enumeration attacks, the following limits are applied.
| Token & Endpoints | Limit |
| - | - |
| A [Checkout Session ID](/reference/checkout-sessions/new-checkout-session) used with the following endpoint. [`POST /checkout/sessions/:id/fields`](/reference/checkout-sessions/update-checkout-session-fields) | This endpoint is used by Secure Fields for storing scheme card details and prevents the over-use of the session ID to store and validate card details. |
> [!WARNING]
>
> **Rate limit**
>
> The current rate limit for these endpoints is set to approximately 50 requests per minute across all endpoints, per token. This value may be adjusted downward in time to adjust for enumeration attacks.
>
> We recommend generating a new checkout session ID or JWT token for every checkout, to prevent a user from being rate-limited.
# Payment method statuses
Source: https://docs.mattildapayments.com/guides/api/statuses/payment-methods
A list of all statuses for payment methods.
A payment method's `status` value can be one of the following depending on the
state within the system and the status within the used payment service.
| `status` | Description |
| :- | :- |
| `processing` | The payment method record has been created in the system and is now ready to be used with your payment services. The status is still `processing` because the payment method has not been validated through a transaction. The `id` method can now be used to create new transactions. |
| `failed` | The payment method could not be processed with any payment service due to technical issues. |
| `buyer_approval_required` | The payment method was correctly created but needs approval from the buyer. |
| `succeeded` | The payment method was successfully used in any payment service. |
# State diagram
The following state diagram serves as an overview of all the different `status`
values and how they relate to each other.
```mermaid theme={"dark"}
flowchart LR
start(( )) --> processing
processing --> buyer_approval_required
processing --> failed
buyer_approval_required --> failed
buyer_approval_required --> succeeded
processing --> succeeded
```
# Transaction statuses
Source: https://docs.mattildapayments.com/guides/api/statuses/transactions
A list of all statuses for transactions.
A transaction's `status` value can be one of the following depending on the
state within the system and the status within the used payment service.
| `status` | Description |
| :- | :- |
| `processing` | The transaction record has been created in the system and is now being processed with your payment services. |
| `buyer_approval_pending` | The transaction was created but needs approval from the buyer either by redirecting them to a hosted page or their bank for 3DS. |
| `authorization_succeeded` | The transaction has been successfully authorized but not yet captured. |
| `authorization_failed` | The transaction could not be authorized with any payment service due to technical issues or limitations of the payment service. |
| `authorization_declined` | The transaction was declined by the payment service. |
| `capture_pending` | The transaction has successfully been submitted for capture with a payment service and is now pending with them. |
| `capture_succeeded` | The transaction has been successfully authorized and captured. |
| `authorization_void_pending` | The transaction authorized transaction is in the process of being voided. |
| `authorization_voided` | The transaction was successfully authorized but has since been voided before it was captured. |
## State diagram
The following state diagram serves as an overview of all the different `status`
values and how they relate to each other.
### Separate authorization and capture
Transactions where the original `intent` is `authorize`.
```mermaid theme={"dark"}
flowchart LR
start(( )) --> processing
processing --> buyer_approval_pending
processing --> authorization_succeeded
processing --> authorization_failed
buyer_approval_pending --> authorization_declined
processing --> authorization_declined
buyer_approval_pending --> authorization_failed
buyer_approval_pending --> processing
authorization_succeeded --> capture_pending
authorization_succeeded --> authorization_void_pending
capture_pending --> capture_succeeded
capture_pending --> authorization_succeeded
capture_pending --> authorization_declined
authorization_void_pending --> authorization_voided
authorization_void_pending --> authorization_succeeded
```
### Direct capture
Transactions where the original `intent` is `capture`.
```mermaid theme={"dark"}
flowchart LR
start(( )) --> processing
processing --> capture_succeeded
processing --> authorization_failed
buyer_approval_pending --> authorization_declined
processing --> buyer_approval_pending
buyer_approval_pending --> processing
processing --> authorization_declined
```
# Best practice
Source: https://docs.mattildapayments.com/guides/best-practice
A list of best practices for integrating mattilda Pay into your checkout.
In no particular order, here are some useful recommendations when integrating the API, Embed or Secure Fields.
## Associate transactions with a Buyer
A Buyer allows you to link transactions with your customer as well as send buyer-specific information such as `name`, `email`, `address` and `tax ID`, etc.
See [Buyers](/reference/buyers) for further details.
## Set a unique reference ID for each transaction
A unique transaction reference ID helps you to link transactions to your order (see step 2). A unique reference ID can either be set as an external identifier or metadata on the transaction. This is available if you are using Embed, Secure Fields, or our API directly.
We are aware that Embed is sometimes displayed at checkout before an order is created by your system. After all, you would not want to create an order every time a customer loads a checkout page. We have introduced an `onBeforeTransaction` callback in Embed that can be used to set the `externalIdentifier` or metadata right before a transaction is created. This will allow you to create a unique reference ID just-in-time before a transaction is created by Embed.
```js Update the external identifier theme={"dark"}
embed.setup({
onBeforeTransaction: async () => {
// Merchant could make a call to a server here to get an order ID.
// let { orderId } = await client.getOrder()
return {
externalIdentifier: orderId,
}
}
})
```
Metadata can be updated in a similar way. In the case that the metadata has been pinned you will also need to update your JWT token because the metadata may be pinned in the token.
```js Update the metadata theme={"dark"}
embed.setup({
onBeforeTransaction: async ({ metadata }) => {
// Merchant could make a call to a server here to get an order ID.
// let { orderId, newToken } = client.getOrder()
return {
token: newToken,
metadata: {
...metadata,
orderId: orderId
}
}
}
})
```
## Use webhooks to listen for transaction updates
We recommend you listen for updates to transactions by using [webhooks](/guides/features/webhooks/overview). As you have set a unique reference ID (see above) you can use this to listen to webhook events, which will notify you of a transaction completing, failing, or being declined.
Please reach out to our team to set up your webhook URL.
> [!WARNING]
>
> We highly recommend you use webhooks and do not exclusively rely on any in-browser events like Embed's `transactionCreated` event or `onComplete` callback. Because browsers are an unreliable environment this message between Embed and your system could get lost for many reasons, and so listening to webhook updates is generally considered the only fully reliable option when dealing with transaction updates.
## Use idempotent requests
Sometimes transactions fail, either because of bad input or because of some kind of network or other system error. In the case of an error where the response was not received by the buyer's browser (or your system), a transaction can be retried using a special header.
```sh theme={"dark"}
curl -i -X POST "https://api.mattildapayments.com/transactions" \
-H "Authorization: Bearer {jwtToken}" \
-H "Idempotency-Key: bffa9ce6-7a8a-449c-889a-65bd2ee86903" \
-d "{...}"
```
The `Idempotency-Key` header is used to uniquely identify a transaction when retrying the same transaction after a network error or some kind of timeout. The second request will be matched using this key against the original request, and rather than creating a new transaction the original response is returned.
See [Idempotent Requests](/guides/api/idempotent-requests) for further details.
> [!NOTE]
>
> If you are using Embed then you are already using idempotent requests.
## Transaction request information
Some payment methods require specific 'non-standard' information to process. For example, some Buy Now Pay Later (BNPL) methods require cart items to successfully process payments. Therefore to future-proof your integration we recommend integrating as much information in the transaction request as possible. This will allow you to add new additional methods of payment without having to update your integration.
Here are a few examples of optional request information to include.
* `buyer` information
* `cart_items`
* `shipping` information
* `payment_source`
* `is_subsequent_payment`
* `merchant_initiated`
# Authorization Insights
Source: https://docs.mattildapayments.com/guides/dashboard/insights/authorizations
A data dashboard that allows you to deep dive into your payments data
The insights dashboard provides merchants with all the tools to deep dive into their payments data. With the use of cross-filters it's
possible to analyze volume, auth rate, and uncover both opportunities and issues.
## Control
The top controller allows you to control the metric for which data is shown on the dashboard.
All visible data will be filtered on the basis of this selection. Once selected, all date on the
page will use this configured filter.

The **metric selector** lets you switch between **volume**, **transactions**, and **auth rate**.
* **Volume** is calculated by accumulated **transaction value** for processed transactions.
* **Transactions** are calculated as total count of processed transactions
* **Auth rate** is calculated as the number of successfully authorized transactions, divided by the number of transactions sent to the PSP for processing that did not resulting in a failure.
* `auth_rate` = `num_authorized` / `num_processed`
* `num_authorized` = `sum(status in ["authorization_succeeded", "capture_succeeded"])`
* `num_processed` = `sum(status in ["authorization_succeeded", "capture_succeeded", "authorization_declined"])` - `flow_decline`
* `flow_declines` = `sum(error_code starts with flow_*)`
> [!WARNING]
>
> The only transactions represented in this dashboard are those that were sent to a payment service and reached an `authorization_succeeded`, `capture_succeeded` or `authorization_declined` state.
> Transactions that were declined by Flow, resulted in a `authorization_failed` status, or are still in some pending status are not included as they either did not reach the service, or were rejected for technical reasons.
The **currency selector** is only available for the **volume** filter and switches between the currencies used in a time frame. Only currencies processed in the selected time range are shown.
The **period selector** allows you to change the period for which the data on the dashboard is shown. It's currently only possible to show the data for **today**, the **last 7 days**, and the **last 30 days**.
Once selected, the page will show data for the selected period as well as the previous period of the same length. For example, the **last 7 days** period will be compared against the previous 7 days before.
### Rolling window
The period selector uses a rolling time window. For the daily and weekly window, the data is
shown in hourly slots. For the 30 day period, the rolling window uses 24 hour slots. Slots are always shown up until the most recent hour. In other words,
for a 30 day window, the most recent 24 hour slot ends at the most recent hour.
## Line chart
The line chart provides an overview of the metrics over the given period, compared to the previous period.

The data in the line chart is shown hourly for every completed hour and updated every hour. For the 24 hour and 7 day period each data point represents an hour. For the 30 days selection each period in the line chart represents a time range of 24 hours.
The chart displays the data with all the same filters applied from the **controller**. This means it will either show the volume, transaction
count, or the auth rate. And it will only show transactions for the period and currency selected. The chart provides a delta with the previous period, comparing the current period with the previous fixed period, and providing
a relative increase or decrease in the measured metric.
> [!WARNING]
>
> When filtering by the last 30 days, the data will be displayed in 24 hour slots while still using a rolling window. This means that the count for a day may change every hour as the 24 hour window changes over time.
## Modules
The real power of our dashboard comes from the ability to cross-filter modules. Selecting one module will filter down the rest of the modules on the dashboard. This allows you to effectively drill down into your data and find opportunities, and potential issues.
For authorizations, we have divided the dashboard into three sections.
### Requests
The request section gives insight into the request and response data.
* **Error codes:** This module shows the mattilda Pay standardized `error_code` values for decline payments. These error codes are mapped from your payment service's response codes to a set of standardized mattilda Pay error codes.
* **Methods:** This module shows the `method` used for the transaction. To see the scheme used for card payments see the **Schemes** module in the **Card details** section..
* **Metadata:** The key/value pair provided in the `metadata` field in the payment request. This module only shows the top 25 of metadata key:value pairs in descending order.
* **Country:** The `country` code provided by the merchant in the payment request. If no country code is provided this will be counted towards the **Unknown country code** value.
* **Connector:** The configured payment service that was used for routing the payment.
* **Flow rule applied:** This module shows which flow rule was applied to route the transaction.
* **Currency:** The `currency` the transaction was processed in.
* **Authorization:** This module allows you to filter between successful and declined transactions.
* **Payment service response codes:** This module shows the response codes received from the payment services, corresponding to the `raw_response_code` transaction field.
### Card Details
This section gives insight in the card details used in the authorizations. From BINs to issuers to card types.
* **Issuer name:** The issuer of the card used in the transaction. This module only provides the top 25 issuers in descending order.
* **BIN:** The BIN of the card that was used in the transaction. This module only provides the top 25 BINs in descending order.
* **Issuer country:** The issuing country of the card used in the transaction.
* **Card type:** The card type of the transaction, providing insight in credit, debit or prepaid.
* **Schemes:** The card scheme that processed the transaction.
### Recurring
This section gives insight in the data regarding recurring, card on-file, CIT and MIT transactions.
* **Transaction type:** The transaction type refers to the `payment_source` of the transaction. Whether the transaction was e-commerce, card-on-file, moto, installment or recurring.
* **Initiator:** This module provides insight in whether the transaction was a customer initiated transaction (CIT) or merchant initiated transaction (MIT).
* **Subsequent payment:** This module shows whether a transaction was a subsequent payment.
# Insights
Source: https://docs.mattildapayments.com/guides/dashboard/insights/homepage
High level transaction insights with a daily, weekly, or monthly view.
mattilda Pay provides off-the-shelf insights for transaction over the last 24 hours, 7 days, or 30 days.
## Controller
The top controller allow you to control the variables for which data is shown on the dashboard.
All visible data will be filtered on the basis of this selection.
* The first select lets you switch between volume (accumulated transaction value) and transactions (transaction count).
* The currency selector allows you to filter for any used currency over 60+ days.
* The time selector allows you to change the time range for which the data on the dashboard is shown. It’s possible to show the data
for today, last 7 days, and last 30 days.
The data will be shown with a comparison to the same time span prior to the selected time frame. For the daily
time filter that means that the last 24 hour’s data will be shown, in comparison to the 24 hours
before that. For the last 7 days that means that the data will be shown for the last 7 days as
compared to the 7 days before that, and for 30 days as compared to the 30 days before that.
> [!WARNING]
>
> **Rolling window**
>
> The time selector applies on the basis of a rolling time window. For the daily and weekly window the data is
> shown hourly. A rolling window means that the data shown will cover the last 24 completed hours (daily), or last completed
> 168 hours (last 7 days).
>
> When you filter on the last 30 days the data will be displayed per day, still using the rolling window.
## Line chart
The data in the line chart is shown hourly for every completed hour, as measured in the UTC timezone. This chart will update hourly.
The chart shows the data as with the filters from the \**controller* applies. This means it will either show the volume or the transaction
count. And it will only show transactions for the period and currency selected.
It’s possible to switch the line chart to show the auth rate, as well as any refunds for the selected time frame. A delta is
shown as an overall comparison between the selected time frame and the previous time frame. The auth rate provided in this module is the mattilda Pay level auth rate. Transactions in mattilda Pay can have multiple attempts via the same or via multiple payment services, depending on whether this has been set up in flow. This means that the auth rate given in this module doesn't reflect the connector level auth rate but rather the success of transactions via mattilda Pay as a whole. The auth rate is calculated as number of `authorized count / number of processed` , where `processed` doesn’t include failures nor in-progress transactions.
> [!NOTE]
>
> **Deltas:** In other words, given a time frame selected of 7 days with a 5% increase in the auth rate means that the auth rate is 5% better for the last 7 days than the 7 days before that.
## Connections
This module shows a list of configured connectors that have processed transactions for the timeframe as set in the top controller (24 hours, 7 days, or 30 days). Differently than the count on the top module here we count the number or volume of attempts via the connector, as a transaction could have multiple attempts. Also the auth rate is calculated by using the same calculation `authorized count / number of processed` however this is only taking into consideration the attempts via the connector minus the failed attempts.
The reason we don't count failed attempts is because failures are technical issues that don't reflect actual transaction behavior. The auth rate therefore is only counted when an actual attempt was made to authorize at the issuer. It is also important to note that transactions that are no longer authorized, for example because they’re voided, are still counted as authorized.
This is different than the auth rate in the top module which takes the mattilda Pay transaction level auth rate. As mentioned, a transaction can have multiple attempts on a connector level it could therefore mean that the count of declines is higher in this module, than the count of declines for overall transactions.
The recovered column refers to transactions that were succeeded but not via the first attempt. It could mean that a connector will show authorized transactions as well as recovered transactions. This depends on how the connector is set up in your Flow configuration. If you use the same connector to perform authorizations, as well as retries, this module will show both authorized and recovered transactions or volume.
The connections module only shows connections that had activity during the configured timeframe. Configured but idle connections are left out of the view.
## Transactions
This is a list of the latest transactions in our system for the respective selected merchant account. In the near future this module will be swapped out for a funnel, showing how transactions and volumes flow through our system.
# Setup a report
Source: https://docs.mattildapayments.com/guides/dashboard/reports/how-to
Learn how to create a report via the dashboard.
There are two ways to setup a report, either via the dashboard or via the API.
## Using Dashboard
1. Go to Reports in the top bar
2. Choose the type of report you want to generate
3. Follow the creation steps
4. Check the report's executions in "Generated" tab
5. Download report
## Using API
### 1. Create a report
Use the [`POST {url}/reports/`](/reference/reports/new-report) API to create a report.
```json Request theme={"dark"}
{
"name": "Successful captures",
"spec": {
"params": {
"fields": ["id", "captured_at", "amount"],
"sort": [
{
"field": "created_at",
"order": "asc"
}
],
"filters": {
"status": ["capture_succeeded"]
}
}
}
}
```
```json Response theme={"dark"}
{
"type": "report",
"id": "71aa8d49-5ec7-43aa-b13c-9b16fdae0f9b",
"name": "Successful captures",
"created_at": "2022-10-28T10:15:36.547789+00:00",
"updated_at": "2022-10-28T10:15:36.547789+00:00",
"next_execution_at": null,
"description": null,
"schedule": "once",
"schedule_enabled": false,
"schedule_timezone": "Etc/UTC",
"spec": {
"model": "transactions",
"params": {
"sort": [
{
"field": "created_at",
"order": "asc"
}
],
"fields": ["id", "captured_at", "amount"],
"filters": {
"method": null,
"scheme": null,
"status": ["capture_succeeded"],
"currency": null,
"metadata": null,
"voided_at": null,
"created_at": null,
"captured_at": null,
"authorized_at": null
}
}
},
"latest_execution": {
"type": "report-execution",
"id": "0848ef01-f44a-4564-abdb-52a1344bac63",
"created_at": "2022-10-28T10:15:36.571232+00:00",
"updated_at": "2022-10-28T10:15:36.611495+00:00",
"status": "dispatched",
"context": {
"reference_timestamp": "2022-10-28T10:15:36.571232+00:00",
"reference_timezone": "Etc/UTC"
}
}
}
```
### 2. Check report's executions (optional)
Next, you can [list all the executions for a report](reference/reports/list-executions-for-report).
```json Response theme={"dark"}
{
"items": [
{
"type": "report-execution",
"id": "0848ef01-f44a-4564-abdb-52a1344bac63",
"created_at": "2022-10-28T10:15:36.571232+00:00",
"updated_at": "2022-10-28T10:15:36.611495+00:00",
"status": "dispatched",
"context": {
"reference_timestamp": "2022-10-28T10:15:36.571232+00:00",
"reference_timezone": "Etc/UTC"
},
"report": {
"type": "report",
"id": "71aa8d49-5ec7-43aa-b13c-9b16fdae0f9b",
"name": "Successful captures"
}
}
],
"limit": 20,
"next_cursor": null,
"previous_cursor": null
}
```
### 3. Generate report's execution URL
To download the file for an execution, [check the status of the execution](/reference/reports/get-report-execution) is `succeeded`, and
then [request the download URL](/reference/reports/generate-download-url).
```json Response theme={"dark"}
{
"url": "https://url/to/report/file",
"expires_at": "2022-10-28T10:21:33.345947+00:00"
}
```
The report can be downloaded from the `url` until it expires at `expires_at`.
# Available report models
Source: https://docs.mattildapayments.com/guides/dashboard/reports/models
The list of available models for which reports can be generated.
Below is a list of the available models for which reports can be created.
| Model | Description | |
| - | - | - |
| `transactions` | Report about individual transactions | [Read more](/guides/dashboard/reports/models-transactions) |
| `transaction_retries` | Report about transaction retries | [Read more](/guides/dashboard/reports/models-transaction-retries) |
# Transactions retries
Source: https://docs.mattildapayments.com/guides/dashboard/reports/models-transaction-retries
Learn how to report on transaction retries via the dashboard.
The `transaction_retries` model allows setting one parameter.
1. `filters`: a dictionary of filters
> [!TIP]
>
> Note that the output fields are predefined and cannot be changed. Also the order of the output data
> is sorted based on the occurrence time of the transactions and then by the attempt number.
## `filters`
Filters allow you to filter the transaction retries' data to be exported.
| Value | Type | Validation |
| - | - | - |
| `created_at` | `dict[str, str] ` | See **date-time filter** below |
> [!TIP]
>
> **No filters**
>
> If no filters should be applied, just set `filters` as `null`
### Date-time filter
A date-time filter could be defined as follows.
```json theme={"dark"}
{
"start": str
"end": str
}
```
`start` and `end` allow three types of values:
1. Valid ISO 8601 timestamp with or without timezone. UTC is assumed if the time zone is not specified.
2. Date-time placeholder to be set dynamically
3. `null`: this represents an open range
#### Validations
The validations below are checked:
1. `start <= end`, only when both are timestamps
2. `start` and `end` cannot be null at the same time
## Example
Example of report creation using the `transaction_retries` model.
```json theme={"dark"}
{
"name": "Test report",
"spec": {
"model": "transaction_retries",
"params": {
"filters": {
"created_at": {
"start": "2023-01-01T00:00:00"
}
}
}
}
}
```
# Transactions
Source: https://docs.mattildapayments.com/guides/dashboard/reports/models-transactions
The list of available fields that can be included in a report for transactions.
The `transactions` model allows setting three parameters.
1. `fields`: a list of fields
2. `filters`: a dictionary of filters
3. `sort`: a list of sorting fields
## `fields`
Fields allow you to select which columns to export in the report.
| Field |
| - |
| `id` |
| `external_identifier` |
| `status` |
| `created_at` |
| `updated_at` |
| `authorized_at` |
| `captured_at` |
| `voided_at` |
| `amount` |
| `currency` |
| `captured_amount` |
| `refunded_amount` |
| `method` |
| `scheme` |
| `payment_service_transaction_id` |
| `payment_service_id` |
| `payment_service_definition_id` |
| `payment_service_display_name` |
| `auth_response_code` |
| `raw_response_code` |
| `raw_response_description` |
| `metadata` |
| `is_subsequent_payment` |
| `merchant_initiated` |
| `payment_source` |
| `three_d_secure_status` |
| `three_d_secure_eci` |
| `three_d_secure_auth_resp` |
| `three_d_secure_method` |
| `buyer_external_identifier` |
| `billing_details_first_name` |
| `billing_details_last_name` |
| `billing_details_email_address` |
| `billing_details_phone_number` |
| `billing_details_address_city` |
| `billing_details_address_country` |
| `billing_details_address_postal_code` |
| `billing_details_address_state` |
| `billing_details_address_state_code` |
| `billing_details_address_house_number_or_name` |
| `billing_details_address_line1` |
| `billing_details_address_line2` |
| `billing_details_address_organization` |
| `billing_details_tax_id` |
| `billing_details_tax_id_kind` |
| `authorized_amount` |
| `intent_outcome` |
> [!TIP]
>
> **All fields**
>
> If all fields should be included in a report, just set `fields` as `null`
## `filters`
Filters allow you to filter the transactions' data to be exported.
| Value | Type | Validation |
| - | - | - |
| `authorized_at` | `dict[str, str]` | See **Date-time filter** below for more details |
| `captured_at` | `dict[str, str]` | See **Date-time filter** below for more details |
| `created_at` | `dict[str, str]` | See **Date-time filter** below for more details |
| `currency` | `str` | Valid ISO 4217 currency code |
| `metadata` | `list[dict[str, str]]` | List of string-to-string dictionaries |
| `method` | `list[str]` | List of valid methods |
| `scheme` | `list[str]` | List of valid schemes |
| `status` | `list[str]` | This should be a list |
| `is_subsequent_payment` | `bool` | Boolean indicating transactions with subsequent payments |
| `merchant_initiated` | `bool` | Boolean indicating transactions initiated by the merchant |
| `payment_source` | `list[str]` | List of valid transaction sources |
| `three_d_secure_status` | `list[str]` | List of valid 3DS statuses |
| `three_d_secure_eci` | `list[str]` | This should be a list |
| `three_d_secure_auth_resp` | `list[str]` | This should be a list |
| `updated_at` | `dict[str, str]` | See **Date-time filter** below for more details |
| `voided_at` | `dict[str, str]` | See **Date-time filter** below for more details |
> [!TIP]
>
> **No filters**
>
> If no filters should be applied, just set `filters` as `null`
### Date-time filter
A date-time filter could be defined as follows.
```json theme={"dark"}
{
"start": str
"end": str
}
```
`start` and `end` allow three types of values:
1. Valid ISO 8601 timestamp with or without timezone. UTC is assumed if the time zone is not specified.
2. Date-time placeholder to be set dynamically
3. `null`: this represents an open range
The available placeholders for dynamic timestamps are:
* `day_start`: replaced with the first instant of the day, for the period of time the execution is reading data from.
* `day_end`: replaced with the last instant of the day, for the period of time the execution is reading data from.
* `week_start`: replaced with the first instant of the week (i.e. Monday at 00:00), for the period of time the execution is reading data from.
* `week_end`: replaced with the last instant of the week (i.e. Sunday at 23:59), for the period of time the execution is reading data from.
* `month_start`: replaced with the first instant of the month, for the period of time the execution is reading data from.
* `month_end`: replaced with the last instant of the month, for the period of time the execution is reading data from.
#### Validations
The validations below are checked:
1. `start <= end`, only when both are timestamps
2. `start` and `end` cannot be null at the same time
## `sort`
The sort parameter allows you to choose how to sort the data exported. This allows you to use multiple columns for sorting.
A sort parameter should have the format:
```json theme={"dark"}
{
"field": str
"order": str
}
```
`field` can be:
1. `authorized_at`
2. `captured_at`
3. `created_at`
4. `updated_at`
5. `voided_at`
`order` can be:
1. `asc`: ascending order
2. `desc`: descending order
> [!TIP]
>
> **No sorting**
>
> If no sorting should be applied, just set `sort` as `null`
## Example
Example of report creation using the `transactions` model.
```json theme={"dark"}
{
"name": "Test report",
"spec": {
"model": "transactions",
"params": {
"fields": ["id", "created_at"],
"filters": {
"status": ["capture_succeeded"]
},
"sort": [
{
"field": "created_at",
"order": "desc"
}
]
}
}
}
```
# Reports
Source: https://docs.mattildapayments.com/guides/dashboard/reports/overview
Generate and schedule transactions via the dashboard.
Reporting enables the creation of custom or templated reports through mattilda Pay
Dashboard and API.
The objective of this guide is to give more details about report creation
and to explain which report models are available, as well as to detail how
they should be defined to be created through the API.
## Concepts
### Reports
A report is a resource that defines how a report should be
created defining several things like schedule, filters, fields and sorting.
### Reports executions
Where the report is the overarching concept of the report being created,
report executions are the output of the system after the API has received
the request to create the report. Each report will have at least one execution.
For example, if a one-off report is created via the dashboard this will result
in a new report with a single execution. However if a report is scheduled,
this requested report will be reused as a concept for the sequence of reports
and the same report will have many executions over time.
### Report specification
A report specification or spec is the detailed definition of a report to be created.
What can or should be set in a report spec depends on the report model.
### Custom reports
A custom report is a report that is manually generated specifying all the
details to create it.
The required parameters for the report creation depend on the report's model.
### Templated reports
A templated report is just a custom report with predefined parameters.
These reports can only be created through the Dashboard.
### One-off reports
One-off reports are reports that have a single execution. This means, that the
report is generated only once.
### Scheduled reports
Scheduled reports are reports that are scheduled and will be automatically
generated on a specific date depending on the report's schedule frequency.
The following frequencies are currently supported:
* `daily`: generates a report every day.
* `weekly`: generates a report every Monday.
* `monthly`: generates a report on the first day of every month.
# Report specification
Source: https://docs.mattildapayments.com/guides/dashboard/reports/spec
The specification of a report as defined by the API.
This is defined by a set of attributes as detailed below.
| Attribute | Description |
| - | - |
| `model` | Name of the report model to be used |
| `params` | Parameters to be used for the chosen report model |
The specification is defined in the `spec` attribute of the request body
when a new report is created through the
[API endpoint to create a report](/reference/reports/new-report).
Below is an example of what a specification would look like:
```json theme={"dark"}
{
"model": "transactions",
"params": {
"fields": [ "id", "created_at"],
"filters": {
"status": ["capture_succeeded"]
},
"sort": [
{
"field": "created_at",
"order": "desc"
}
]
}
}
```
# 3-D Secure in Embed
Source: https://docs.mattildapayments.com/guides/features/3ds/embed
Any merchant using Embed will automatically benefit from **Universal 3-D
Secure** once it has been [set up](/guides/features/3ds/setup) for a payment service.

Additionally, **Dynamic 3-D Secure** can be set up using Flow rules, allowing you to dynamically
skip or force 3-D Secure based on anti-fraud decisions, cart items, or any other transaction data.
## Buyers & Billing Details
To optimize 3-D Secure it is highly recommended to provide a buyer with billing details attached to Embed.
A buyer can be set up via our [`POST /buyers`](/reference/buyers/new-buyer)
API. The buyer can then be attached to Embed by using the `buyerId` or
`buyerExternalIdentifier` property. The buyer's name, email address, and billing
address will be used to help reduce buyers being asked to complete a 3-D Secure
challenge.
```js React theme={"dark"}
```
```js Node theme={"dark"}
gr4vy.setup({
gr4vyId: "mattilda",
amount: 1299,
currency: "MXN",
country: "MX",
buyerExternalIdentifier: "user-1234",
...
});
```
We will use these billing details when contacting payment services, 3-D Secure Server, anti-fraud services, and more.
## Features
For every transaction, we will handle the following steps.
1. Detect if any Flow rule explicitly requires or skips 3-D Secure
2. Detect if the selected payment service for this transaction has 3-D Secure
enabled
3. Detect if the card used in the transaction is enrolled for 3-D Secure
4. Handle the seamless frictionless 3-D Secure flow including the device finger
printing
5. Handle the 3-D Secure challenge flow, where a buyer is directed in-page to
their bank to approve the transaction
## Usage
All you need to do to use 3-D Secure in Embed is to [set up](/guides/features/3ds/setup)
3-D Secure on any of your enabled payment services. Once configured, Embed will
handle all the user interactions.
# External 3-D Secure server
Source: https://docs.mattildapayments.com/guides/features/3ds/external
Our **Universal 3-D Secure** can also be used with your own, external, 3-D
Secure server.
To use 3-D Secure with your own 3DS server, we assume you have handled the 3-D Secure
on your end and have collected the relevant data received at the end of the
flow.
The `POST /transactions` API supports directly passing 3-D Secure data as part
of the transaction request. We will pass this data along to the payment service
assuming it this data via their API.
```bash cURL theme={"dark"}
curl -i -X POST "https://api.mattildapayments.com/transactions" \
-H "Authorization: Bearer [JWT_TOKEN]" \
-H "Content-Type: application/json" \
-d '{
"amount": 1299,
"currency": "MXN",
"payment_method": {
"method": "card",
"number": "4111111111111111",
"expiration_date": "11/25",
"security_code": "123",
"redirect_url": "https://example.com/callback"
},
"three_d_secure_data": {
"cavv": "3q2+78r+ur7erb7vyv66vv8=",
"eci": "05",
"version": "2.1.0",
"directory_response": "C",
"caav_algorithm": "1",
"xid": "ODgxNDc2MDg2MDExODk5MAAAAAA=",
"authentication_response": "Y"
}
}'
```
```js Node theme={"dark"}
var fetch = require("node-fetch");
fetch("https://api.mattildapayments.com/transactions", {
method: "POST",
headers: {
Authorization: "Bearer [JWT_TOKEN]",
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: 1299,
currency: "MXN",
payment_method: {
method: "card",
number: "4111111111111111",
expiration_date: "11/21",
security_code: "123",
redirect_url: "https://example.com/callback",
},
three_d_secure_data: {
cavv: "3q2+78r+ur7erb7vyv66vv8=",
eci: "05",
version: "2.1.0",
directory_response: "C",
caav_algorithm: "1",
xid: "ODgxNDc2MDg2MDExODk5MAAAAAA=",
authentication_response: "Y",
},
}),
});
```
> [!WARNING]
>
> **Payment service compatibility**
>
> Not all payment services support external 3-D Secure data, and therefore even
> when this data is provided we still expect a `redirect_url` as well. If none of
> the selected payment services support the pass-through of 3-D Secure data the
> API might [return a pending transaction](./hosted) with an `approval_url` in
> the response.
# Hosted 3-D Secure
Source: https://docs.mattildapayments.com/guides/features/3ds/hosted
**Universal 3-D Secure** is also available without Embed as long as any payment
service has been [set up](./setup) for 3-D Secure. This integration equally supports
**Dynamic 3-D Secure** which can be set up using Flow rules, allowing you to dynamically
skip or force 3-D Secure based on anti-fraud decisions, cart items, or any other
transaction data.
## Usage
All you need to do to use 3-D Secure via the API is to [set up](./setup) 3-D
Secure on any of the enabled payment services and pass a `redirect_url` when
creating the transaction.
```bash cURL theme={"dark"}
curl -i -X POST "https://api.mattildapayments.com/transactions" \
-H "Authorization: Bearer [JWT_TOKEN]" \
-H "Content-Type: application/json" \
-d '{
"amount": 1299,
"currency": "MXN",
"buyer_external_identifier": "user-1234",
"payment_method": {
"method": "card",
"number": "4111111111111111",
"expiration_date": "11/25",
"security_code": "123",
"redirect_url": "https://example.com/callback",
}
}'
```
```js Node theme={"dark"}
var fetch = require("node-fetch");
fetch("https://api.mattildapayments.com/transactions", {
method: "POST",
headers: {
Authorization: "Bearer [JWT_TOKEN]",
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: 1299,
currency: "MXN",
buyer_external_identifier: "user-1234",
payment_method: {
method: "card",
number: "4111111111111111",
expiration_date: "11/21",
security_code: "123",
redirect_url: "https://example.com/callback",
},
}),
});
```
With 3-D Secure configured for a payment service, we will automatically detect
if it is required to get the buyer's approval for a transaction. If it is
required the API will return a transaction with the status
`buyer_approval_pending` and an `approval_url` that the buyer can be sent to.
```json theme={"dark"}
{
"type": "transaction",
"id": "869df4fc-a3db-43db-806a-14464d9e6920",
"status": "buyer_approval_pending",
"payment_method": {
"approval_url": "https://embed.mattildapayments.com/...",
...
},
...
}
```
You can then redirect the buyer to the `approval_url` and we will handle all
the intricacies of 3-D Secure. Once the buyer has approved (or rejected) the
transaction the browser is redirected back to the `redirect_url` that was set
when the transaction was created.
The `redirect_url` will be appended with both a transaction ID and status.
```
https://example.com/callback?transaction_id=123&transaction_status=capture_succeeded
```
We strongly recommend confirming the actual transaction status by fetching the
updated transaction by its `id`.
## Buyers & Billing Details
To optimize 3-D Secure it is highly recommended to provide a buyer with billing
details attached to Embed.
A buyer can be set up via our [`POST /buyers`](/reference/buyers/new-buyer)
API. The buyer can then be attached to Embed by using the `buyerId` or
`buyerExternalIdentifier` property. The buyer's name, email address, and billing
address will be used to help reduce buyers being requested to complete a 3-D
Secure challenge.
## Features
For every transaction, we will handle the following steps.
1. Detect if any Flow rule explicitly requires or skips 3-D Secure
2. Detect if the selected payment service for this transaction has 3-D Secure
enabled
3. Detect if the card used in the transaction is enrolled for 3-D Secure
4. Handle the seamless frictionless 3-D Secure flow including the device finger
printing once the user is redirected to the `approval_url`.
5. Handle the 3-D Secure challenge flow, where a buyer is directed to their bank
to approve the transaction.
# 3-D Secure
Source: https://docs.mattildapayments.com/guides/features/3ds/overview
Our system has a **Universal 3-D Secure** solution that provides merchants with a
flexible way to integrate 3-D Secure with various levels of complexity.
Universal 3-D Secure will automatically handle the device fingerprinting,
redirecting the buyer, as well as handling the different 3-D Secure nuances
between the different payment services.
Additionally, our system supports **Dynamic 3-D Secure**, allowing you to dynamically
skip or force 3-D Secure based on anti-fraud decisions, cart items, or any other transaction data.
There are currently 3 ways to integrate 3-D Secure.
* [Embed](/guides/features/3ds/embed) will automatically detect 3-D Secure for a
transaction and handle all the user interactions to complete the transaction.
* [Hosted 3-D Secure](/guides/features/3ds/hosted) offers 3-D Secure via our API, allowing
you to capture your own card data but then rely on our hosted 3-D Secure
to handle the user interaction.
* [External](/guides/features/3ds/external) 3-D Secure data can be passed to us if you
want to create your own card checkout experience including your own 3-D Secure
integration.
# Setup 3-D Secure
Source: https://docs.mattildapayments.com/guides/features/3ds/setup
To set up 3-D Secure for a payment service, head over to your dashboard
and switch to the **Connections** tab. Then select one of your active card connections
and switch to the **3-D Secure** tab.
## 3-D Secure with 3rd-party server
Configuring 3-D Secure is only required when using 3-D Secure via [Embed](./embed)
or as a [hosted option via the API](./hosted). Configuration is not required when
you intend to use your own 3-D Secure server.
## Configuration
Configuring 3-D Secure requires the following details per scheme that you support through your connection.
| Field | Description |
| - | - |
| **Acquirer BIN** | The acquirer BIN for the supported card scheme. |
| **Acquirer Merchant ID** | The merchant ID provided by the acquirer used by your payment service. |
| **Merchant Name** | Your merchant name. This will be sent on to our 3-D Secure provider. |
| **Merchant Country Code** | ISO 3166-1 numeric three-digit country code for this merchant account. |
| **Merchant Category Code** | The merchant category code or `mcc` for the merchant account. This describes the type of business, product or service offered. |
| **Merchant URL** | The URL on which the payments are processed. |
> [!NOTE]
>
> **Where do I find these details?**
>
> You can find most of these identifiers either in your payment service's
> dashboard or through their support channels. Please see the details for each of
> the **connectors** for more information.
# 3-D Secure Testing
Source: https://docs.mattildapayments.com/guides/features/3ds/testing
Before testing 3DS in `sandbox` there is some configuration required:
* Configure 3DS for each of the schemes that you want test with against your primary card connector
* Ensure Flow rules do not `skip` 3DS for your specific test scenarios
Our 3DS server uses different card numbers to simulate various responses. You can use the following test cards.
> [!NOTE]
>
> Each connector handles sandbox testing and test PANs differently, so it may or may not be possible to use these PANs to test end-to-end in sandbox. Please reach out should you have
> any questions about testing different 3DS scenarios end-to-end.
### Frictionless flow - Successful - status 'Y' (ECI 05)
| Test PAN | Scheme | Expiry | Security Code |
| - | - | - | - |
| `5200000000001203` | `mastercard` | 03/30 | 100 |
| `4111111111101203` | `visa` | 03/30 | 100 |
| `340000000022003` | `amex` | 03/30 | 1000 |
| `3558111111121203` | `jcb` | 03/30 | 100 |
| `8171998927611203` | `unionpay` | 03/30 | 100 |
### Challenge flow - Successful or Declined - status 'Y' (ECI 05) or 'N'
| Test PAN | Scheme | Expiry | Security Code |
| - | - | - | - |
| `5240000000001072` | `mastercard` | 03/30 | 100 |
| `4111111111181072` | `visa` | 03/30 | 100 |
| `340000000082072` | `amex` | 03/30 | 1000 |
| `3558111111121872` | `jcb` | 03/30 | 100 |
| `8171998927611872` | `unionpay` | 03/30 | 100 |
> [!NOTE]
>
> `status` in the above table refers to the transaction API response field `three_d_secure.response_data.authentication_response`
# Manual account updates
Source: https://docs.mattildapayments.com/guides/features/account-updater/integration
Our batch account updater is provided as an on-demand and asynchronous service, available via API. Currently we support
Visa, Mastercard, American Express, and Discover.
## Setup
To have the batch account updater enabled on your instance please fill out \[this form]\[form]. The enrollment happens directly with the card schemes and may take up to two weeks. Our customer support team may reach out with more questions if needed.
If you're already enrolled for this service with the schemes, filling out the form is still required to set up
the necessary data points in our systems as well as our downstream partner's system.
## Request an update check
Once enabled it is possible to call the account updater service using the [`POST /account-updater/jobs` endpoint][endpoint].
The request can contain any set of stored card IDs. The set of cards is then submitted to the schemes to
receive any updates on their account details. This process can take up to 7 days.
Any updates to the card are done automatically. Therefore there is no need to handle the response of the account
updater service. If the payment method is made unavailable, either because the card has been canceled or the buyer
has indicated to stop recurring payments by this merchant, then the card does not get updated but transactions will be declined.
At this point, we recommend you delete the stored card via our API.
> [!WARNING]
>
> **Scheme enrollment limitations**
>
> Account updates are enabled individually per card scheme and per merchant ID (MID). It is important to be aware of
> which schemes your MID has been enrolled in. If an update job is submitted for a card in a scheme for which you are not enrolled,
> then your update may remain stuck in a pending state for up to 7 days.
## Handling updated details
When the results are ready, the new account details are stored on the payment method but left in a “standby” mode. This means the details
have been received but will not be used immediately.
The reason for this is that it can happen that details have been updated, for example, a new card
with a new expiry date has been issued, but these details are pending activation of the cardholder. The old card might still be
in use in the meantime.
Card details are eventually updated when it is determined that the old details are no longer valid. After the card details have been
updated the payment method ID remains the same but the `last_replaced_at` field on the payment method will be updated.
This way, as a merchant, you can keep using the same identifier to trigger recurring payments using up-to-date details.
There are three scenarios in which the actual replacement occurs.
* When the card has an expiry date in the past
* When we received an update that only changes the expiration date
* When a transaction using this card is declined with any of the following codes
* `canceled_payment_method`
* `expired_payment_method`
* `unavailable_payment_method`
* `unknown_payment_method`
## Webhooks
Once a payment method has been updated a webhook will be sent out for the payment method to notify you of the change. You can use
this webhook to pull in the latest expiry date, last 4 digits, or BIN for use in your own UI.
[endpoint]: /reference/account-updater/new-account-updater-job
# Account Updater
Source: https://docs.mattildapayments.com/guides/features/account-updater/overview
To keep card details up to date most card schemes have created services to inform customers
about changes to card and account details, for example, when the expiry date of a card changes.
Using an account updater, it is possible to update the details of stored card details automatically. This
way it is possible to keep all information fresh and up to date and maintain continuity in your payment cycle,
without the buyer having to re-fill their card details after they have changed.
Card details are automatically updated when the following events occur.
* A new expiry date is available
* A new card is issued, replacing the old card
* A card is reported as stolen or lost
* The buyer has no longer authorized the merchant to automatically charge the card
## Enable account updater
To enable an account updater on your instance, please [contact support](https://support.gr4vy.com).
If you're already enrolled for this service with the schemes, filling out the form is still required to set up
the necessary data points in our systems as well as our downstream partner's system.
# Scheduled account updates
Source: https://docs.mattildapayments.com/guides/features/account-updater/scheduler
Our batch account updater supports automatic scheduling of an entire vault for updates every 12 days.
This will allow your entire vault to stay up to date on a monthly basis, without the need to manually submit cards
to the account updater.
## Setup
To use the account updater service you need to have the service enabled. To have the batch account updater enabled
on your instance please fill out \[this form]\[form]. The enrollment happens directly with the card schemes
and may take up to two weeks. Our customer support team may reach out with more questions if needed.
If you're already enrolled for this service with the schemes, filling out the form is still required to set up
the necessary data points in our systems as well as our downstream partner's system.
Next, we need to set up the scheduler which requires a change to be made on your instance. When you fill in the form, please
select if you want to use the scheduler or not.
## Usage & Limitations
* The entire content of the vault will be updated every 12 days, allowing for 2 full updates within 1 calendar month
* You will only be charged for cards that are updated
* Any card already submitted to the account updater in some other way will not get submitted as part of the scheduler
* Any card already updated but pending its first use in our vault will not get updated until the new card has been automatically used. This may happen when a card is updated, but the old card is still in use.
* Only Visa, Mastercard, American Express, and Discover cards are supported by the account updater, and any others are ignored by the scheduler
* Any cards previously marked as dead (`LCA`) are ignored
# Automatic anti-fraud device fingerprinting
Source: https://docs.mattildapayments.com/guides/features/anti-fraud/fingerprint
Enabling automatic device fingerprinting
A device fingerprint uniquely identifies the device a customer is using
at checkout. Anti-fraud connections use this to determine whether
this device or user has been flagged for fraudulent behavior in the past, allowing
it to reject the transaction and protecting you from fraud.
Each anti-fraud service will have a different way of collecting the device fingerprint,
and therefore we've introduced our own `f.js` library that wraps around each of
these, allowing you to focus on using your preferred anti-fraud service.
> [!NOTE]
>
> If you are using Embed or one of our e-commerce plugins, then you will not
> need to perform any of the steps below. Embed will automatically load the
> right library for you and ensure the device fingerprint is collected.
## Usage without Embed
To create a device fingerprint, load the `f.js` library into your checkout page. This
can be the page on which you render your checkout using Secure Fields, or any other integration.
```html theme={"dark"}
```
> [!NOTE]
>
> In a sandbox environment make sure you use `api.sandbox.mattildapayments
> .com/f.js`.
This will automatically load the fingerprinting library for your configured anti-fraud service and
attach the fingerprint value to `window.gr4vyAntiFraud.f`. This `fingerprint` can then be sent
as the [`anti_fraud_fingerprint`](/reference/transactions/new-transaction#body-anti-fraud-fingerprint) property when creating a transaction.
## Embed, E-commerce, and custom
When you are using Embed, or one of the e-commerce plugins like Magento, then the device fingerprint is automatically created for you
and sent along when creating a transaction. You can override this behavior by sending in a custom fingerprint to Embed.
For example, if you know what anti-fraud service is in use,
and you've already loaded that service's fingerprint script, then you can pass in the fingerprint created by that service directly
to Embed or our API. When the `antiFraudFingerprint` value is set we will not load any of the device fingerprint libraries and, instead,
we will pass along the fingerprint provided as-is when creating a transaction.
```js React theme={"dark"}
```
```js Node / CDN theme={"dark"}
setup({
gr4vyId: "mattilda",
antiFraudFingerprint: "my-fingerprint-id",
...
});
```
> [!NOTE]
>
> For most anti-fraud services the `fingerprint` represents either the session
> ID or device fingerprint ID defined by that service's anti-fraud library.
> Please refer to the documentation of your anti-fraud service for more details.
## Custom & native fingerprints
In the event you are unable to use the automated solution to generate the device fingerprint,
you will need to use the anti-fraud fingerprint libraries yourself and you can then pass the fingerprint
to us by using the [`anti_fraud_fingerprint`](/reference/transactions/new-transaction#body-anti-fraud-fingerprint) when creating a new transaction.
## Merchant accounts
In an environment with multiple merchant accounts it's important to add the `merchant_account_id` as a query
parameter to the fingerprint script. This will ensure the script is loaded for the configured anti-fraud service for
that specific merchant account.
```html theme={"dark"}
```
Please note that when using an Integration API key with Embed or one of our ecommerce platforms, then the `merchantAccountId` needs to be set
explicitly for Embed to load the anti-fraud scripts for that merchant account.
```js React theme={"dark"}
```
```js Node / CDN theme={"dark"}
setup({
gr4vyId: "mattilda",
merchantAccountId: "my-merchant-id"
...
});
```
# Anti-fraud
Source: https://docs.mattildapayments.com/guides/features/anti-fraud/overview
Managing risk in your transaction flow
As part of [Flow](/guides/dashboard/flow) our system allows you to build rules
which use decisions and scores from anti-fraud services.

You can use these scores and decisions for [card transactions](/guides/dashboard/flow/card-transactions)
to evaluate the risk of a transaction and take
appropriate actions to, for example, force 3-D Secure, decline a transaction, or route to
a specific payment service.
## How does it work?
For every transaction, your anti-fraud service will only be called **once**.
When a request is made for a transaction, your active anti-fraud provider will only be called
once, assuming a rule is triggered for which an anti-fraud score or decision is the condition.
This feature will prevent incurring any extra cost by calling your anti-fraud service multiple times,
or calling your service unnecessarily if the rule is not triggered.
# Anti-fraud reviews
Source: https://docs.mattildapayments.com/guides/features/anti-fraud/reviews
Manually reviewing anti-fraud decisions
Some anti-fraud services may hold a transaction in review. If your chosen anti-fraud service supports this feature then you
can enable manual reviews as part of the payment flow. This will pause a transaction and wait for the result of the
review before proceeding.

When a transaction is marked for review the following steps will be performed.
* We accept the transaction request
* We call out to the anti-fraud service to fetch a decision
* When the service requires a manual review we will mark the transaction as pending review
* We proceed to authorize the transaction but do not continue to capture
* When a support agent reviews the transaction we receive a webhook
* We remove the pending review status from the transaction
* We either proceed to capture if that was the original intent, or we will void the transaction if it was rejected
## Supported connections
The following anti-fraud services currently support manual reviews.
* Cybersource Decision Manager
## Set up webhooks
To enable manual review you will need to set up webhooks from your anti-fraud service to our system. This webhook is used
to notify us when a review has had a decision.
To get the webhook URL, head over to your connection by going to **Connections** -> **\[Anti-Fraud connection]** -> **Synchronization** and copying the webhook URL.
Then follow the guide for your chosen anti-fraud service to set up the webhook in their dashboard.
# Decrypted Apple Pay tokens
Source: https://docs.mattildapayments.com/guides/features/apple-pay/decrypted-tokens
Some merchants and platforms may have the option to decrypt an Apple Pay token themselves. For this scenario, we
support direct pass through of these decrypted Apple Pay tokens to our API using the \[]`network-token` method]\(/reference/transactions/new-transaction#network-token-payment-method-create).
```json Payment method theme={"dark"}
{
"method": "network-token",
"token": "4111111111111111",
"expiration_date": "02/30",
"cryptogram": "AAEBAwQjSQAAXX...",
"eci": "05",
"card_suffix": "1234",
"card_scheme": "visa",
"card_source": "apple-pay",
"cardholder_name": "John Smith"
}
```
# Apple Pay on iOS with the SDK
Source: https://docs.mattildapayments.com/guides/features/apple-pay/ios
Both our native iOS SDK and React Native SDKs support native Apple Pay out of the box.
## About this integration
Our SDK requires you to perform the following steps to get set up.
* Enable Apple Pay in your merchant dashboard.
* Sign up for an Apple Pay Developer account and [register a payment processing certificate](/guides/features/apple-pay/ios#register-a-certificate).
* [Add the merchant ID](/guides/features/apple-pay/ios#add-the-certificate-to-your-app) and its processing certificate to your app.
* Pass the merchant ID to the constructor of the SDK.
## Enable Apple Pay
To enable Apple Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Apple Pay**.
Next, complete and submit the form to create a new Apple Pay service.
### Register a certificate
To process Apple Pay in a mobile application you will need to register for an
Apple Pay developer account and join the [Apple developer program](https://developer.apple.com/programs/).
Once set up, you can generate a new Apple Pay processing certificate using the Gr4vy dashboard.
Go to
**Connections** -> **Apple Pay** -> **Certificates** and click on **Add certificate**
to start the process.

You will be prompted to provide a name and download a **Certificate Signing Request** (CSR).
Next, visit the [Apple developer dashboard](https://developer.apple.com/account/resources/identifiers/list/merchant)
to generate a payment processing certificate.
* Create or select a **Merchant ID** to associate a payment processing certificate with.
* In the **Apple Pay Payment Processing Certificate** section click on **Create Certificate**.
* Select **Choose File** to upload the CSR you downloaded from the dashboard, and then Continue.
* Verify the certificate details and **Download** the signed certificate from Apple.
Next, go back to our dashboard and upload the signed certificate.
### Add the certificate to your app
In order for your app to accept Apple Pay, you must set the same Apple **Merchant ID** in your application.
In your Xcode project find the **Signing & Capabilities** in your project editor.
Select the same **Merchant ID** you used to register your payment certificate. Please ensure your provisioning profiles
and signing certificates are updated to contain this ID.
## Integrate Apple Pay
### Update SDK initialization
Because the Xcode project can be configured with more than one merchant ID, update the initialization of
our SDK to pass the `applePayMerchantId` to the constructor.
```swift Swift theme={"dark"}
import gr4vy_ios
let result = Gr4vy.init(
gr4vyId: "mattilda",
token: "[TOKEN]",
amount: 1299,
currency: "MXN",
country: "MX",
buyerId: nil,
environment: Gr4vyEnvironment.sandbox,
applePayMerchantId: "[MERCHANT_ID]"
)
```
```swift React Native theme={"dark"}
import EmbedReactNative from '@gr4vy/embed-react-native';
const handleCheckout = () => {
EmbedReactNative.showPaymentSheet({
gr4vyId: 'mattilda',
environment: 'sandbox',
token: '[TOKEN]',
amount: 1299,
currency: 'AUD',
country: 'AU',
applePayMerchantId: "[MERCHANT_ID]"
...
})
}
```
### Create sandbox transaction
To make an Apple Pay sandbox transaction the following are required.
* An Apple device with a Sandbox Tester account on it
* An app with an Apple merchant ID associated with it
* A merchant ID with a signed payment processing certificate associated with it
* Apple Pay enabled in the dashboard
* The payment processing certificate registered in the dashboard
* A card processor enabled that can process Apple Pay in the given currency.
For a currency that has a card processor that supports Apple Pay, you
should see the payment option in your app. Select Apple Pay and continue
with the payment. You should see the Apple Pay sheet appear.
### Create production transaction
To make an Apple Pay transaction in production replace the Sandbox Tester account
with a regular Apple account with real cards.
# Apple Pay on iOS without the SDK
Source: https://docs.mattildapayments.com/guides/features/apple-pay/ios-without-sdk
It is possible to use Apple Pay in an iOS app without our SDK. To learn how to integrate
Apple Pay we recommend following Apple's [documentation][documentation].
The steps below will highlight the basics and focus on the interaction with our API. A full [sample
app][documentation] is available in Apple's developer documentation.
## About this integration
Similar to our SDK integration this setup requires you to perform the following steps.
* Enable Apple Pay in your merchant dashboard.
* Sign up for an Apple Pay Developer account and [register a payment processing certificate](/guides/features/apple-pay/ios#register-a-certificate).
* [Add the merchant ID](/guides/features/apple-pay/ios#add-the-certificate-to-your-app) and its processing certificate to your app.
Additionally, you will then need to implement the following.
* Render your own Apple Pay button.
* Create a session with the right merchant ID.
* Catch the Apple Pay token and pass it to our API for processing.
## Enable Apple Pay
To enable Apple Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Apple Pay**.
Next, complete and submit the form to create a new Apple Pay service.
### Register a certificate
To process Apple Pay in a mobile application you will need to register for an
Apple Pay developer account and join the [Apple developer program](https://developer.apple.com/programs/).
Once set up, you can generate a new Apple Pay processing certificate using the Gr4vy dashboard.
Go to
**Connections** -> **Apple Pay** -> **Certificates** and click on **Add certificate**
to start the process.

You will be prompted to provide a name and download a **Certificate Signing Request** (CSR).
Next, visit the [Apple developer dashboard](https://developer.apple.com/account/resources/identifiers/list/merchant)
to generate a payment processing certificate.
* Create or select a **Merchant ID** to associate a payment processing certificate with.
* In the **Apple Pay Payment Processing Certificate** section click on **Create Certificate**.
* Select **Choose File** to upload the CSR you downloaded from the dashboard, and then Continue.
* Verify the certificate details and **Download** the signed certificate from Apple.
Next, go back to our dashboard and upload the signed certificate.
### Add the certificate to your app
In order for your app to accept Apple Pay, you must set the same Apple **Merchant ID** in your application.
In your Xcode project find the **Signing & Capabilities** in your project editor.
Select the same **Merchant ID** you used to register your payment certificate. Please ensure your provisioning profiles
and signing certificates are updated to contain this ID.
## Integrate Apple Pay
**Swift**
### Display an Apple Pay button
An Apple Pay button can be displayed in a few different ways. [Apple's guide](https://developer.apple.com/documentation/passkit/apple_pay/offering_apple_pay_in_your_app#3846467)
shows a code sample that checks if Apple Pay is enabled on the device and then adds the button directly to a view with code.
```swift theme={"dark"}
if let applePayButton = button {
let constraints = [
applePayButton.centerXAnchor.constraint(equalTo: applePayView.centerXAnchor),
applePayButton.centerYAnchor.constraint(equalTo: applePayView.centerYAnchor)
]
applePayButton.translatesAutoresizingMaskIntoConstraints = false
applePayView.addSubview(applePayButton)
NSLayoutConstraint.activate(constraints)
}
```
> [!WARNING]
>
> The sample app doesn't display the add button if a device can't accept
> payments due to hardware limitations, parental controls, or any other reasons.
### Set the merchant ID
Once the button is clicked the guide requires you to set up a new payment request. In this step, set the
`merchantIdentifier` to the merchant ID for the Apple Pay certificate you've [registered in our merchant dashboard](/guides/features/apple-pay/ios#enabling-apple-pay).
For example, if you registered a certificate for merchant ID `merchant.com.example.demo` in the dashboard then set this same ID in your application code.
```swift theme={"dark"}
let paymentRequest = PKPaymentRequest()
paymentRequest.paymentSummaryItems = paymentSummaryItems
paymentRequest.merchantIdentifier = "merchant.com.example.demo"
...
```
> [!TIP]
>
> Apple's documentation has an [extensive
> guide](https://developer.apple.com/documentation/passkit/apple_pay/setting_up_apple_pay)
> on setting up your iOS app to accept Apple Pay.
### Create a transaction
Finally, once the Apple Pay transaction has been authorized by Apple, create a transaction with our API.
> [!NOTE]
>
> This API call could be made in your frontend code in Swift or Objective C, or
> the token could be sent to your backend for processing.
```sh theme={"dark"}
curl -X POST https://api.mattildapayments.com/transactions \
-H "Authorization: bearer [JWT]"
-d '{
amount: 1299,
currency: "MX",
currency: "MXN",
payment_method: {
method: "applepay",
token: "[TOKEN]"
}
}'
```
> [!NOTE]
>
> In this example, the `[TOKEN]` value is the token from the [PKPayment](https://developer.apple.com/documentation/passkit/pkpayment) object as returned by Apple Pay
> in the `paymentAuthorizationController(_:didAuthorizePayment:handler:)` method.
**React Native**
In React Native you can use any Apple Pay integration, together with your merchant identifier.
One of the easiest solutions is to use a library like [React Native Payments](https://github.com/appfolio/react-native-payments) to get
an Apple Pay token.
On initialization, any of these libraries will require you to set the Apple merchant identifier that
you created in the Apple developer dashboard earlier.
```js theme={"dark"}
const METHOD_DATA = [{
supportedMethods: ['apple-pay'],
data: {
merchantIdentifier: 'merchant.com.your-app.namespace',
supportedNetworks: ['visa', 'mastercard', 'amex'],
countryCode: 'AU',
currencyCode: 'AUD'
}
}];
```
Once the user has approved the payment, your application will receive an Apple Pay token from the library.
You can pass this library to our server for processing.
```js theme={"dark"}
paymentRequest.show()
.then(paymentResponse => {
const { paymentData } = paymentResponse.details;
return fetch('https://api.mattildapayments.com/transactions', {
method: 'POST',
headers: {
"Authorization": "Bearer [TOKEN]"
},
body: {
amount: 1299,
currency: "MX",
currency: "MXN",
payment_method: {
method: "applepay",
token: paymentData
}
}
})
.then(res => res.json())
.then(successHandler)
.catch(errorHandler)
});
```
[documentation]: https://developer.apple.com/documentation/passkit/apple_pay/offering_apple_pay_in_your_app
# Apple Pay
Source: https://docs.mattildapayments.com/guides/features/apple-pay/overview
Apple Pay is supported both on the web and in iOS applications. In both environments, Apple Pay can be
integrated using our SDK and without our SDK.
## Prerequisites
To enable Apple Pay transactions, our system is directly integrated with Apple. As a result,
it transmits decoded device tokens to payment services instead of encrypted gateway tokens.
Please note that not all payment services support decoded Apple Pay tokens, and they
may require this feature to be activated.
We recommend contacting your payment service provider to enable this feature.
## Web (Embed)
On the web, Apple Pay can be easily integrated both with and without Embed. In both offerings, we have removed
the need for you to sign up for an Apple Developer account, reducing additional financial and maintenance costs.
| | [Using SDK (Embed)][web] | [Without SDK][web-without] |
| - | - | - |
| Apple Developer account required? | No | No |
| Apple merchant account required? | No | No |
| Customization & Theming? | Limited | Full |
| Domain association required? | Yes | Yes |
| Integrated with Checkout Flow? | Yes | Optional |
## Mobile (iOS)
On mobile apps, Apple Pay can be easily integrated both with and without our SDK. In both offerings, there will
be the need for you to sign up for an Apple Developer account and create your own Apple merchant ID and
processing certificate.
| | [Using SDK][mobile] | [Without SDK][mobile-without] |
| - | - | - |
| Apple Developer account required? | Yes | Yes |
| Apple merchant account required? | Yes | Yes |
| Customization & Theming? | Limited | Full |
| Domain association required? | No | No |
| Integrated with Checkout Flow? | Yes | Optional |
## Recurring payments
Recurring payments are supported on Apple Pay in a similar way to how
[recurring payments][recurring-payments] are supported regular card payments.
> [!WARNING]
>
> To facilitate recurring Apple Pay payments, your payment service provider needs to
> support decoded Apple Pay tokens as well as recurring payment flags. Please contact your
> payment service provider to enable this feature.
[web]: /guides/features/apple-pay/web
[web-without]: /guides/features/apple-pay/web-without-sdk
[mobile]: /guides/features/apple-pay/ios
[mobile-without]: /guides/features/apple-pay/ios-without-sdk
[recurring-payments]: /guides/features/recurring-payments
# Apple Pay on web with Embed
Source: https://docs.mattildapayments.com/guides/features/apple-pay/web
Apple Pay is the faster, more secure way to pay online using cards saved
on your customer's Apple device.
We support Apple Pay out of the box in Embed with minimal configuration.
## About this integration
Embed requires minimal configuration to get set up to process Apple Pay. Unlike
some other integrations it does not require you to sign up for an Apple Pay Developer account.
* Upload our **Domain Association File** to your website.
* Enable Apple Pay in your merchant dashboard.
## Enable Apple Pay
To enable Apple Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Apple Pay**.
Next, complete and submit the form to create a new Apple Pay service.
### Registering a domain
To process Apple Pay via the web you will need to register all the domains where the buyer can
checkout. In order to do this, navigate to your Apple Pay service via the dashboard, **Connections** -> **Apple Pay** -> **Domains** -> **Add domain name**.
> [!WARNING]
>
> **Domain Association File**
>
> Before submitting a domain name, please download the Domain Association File from
> the dashboard and upload it to every domain you wish to support.
>
> The file needs to be added to every domain in a predefined location.
>
> ```
> https://{domain}/.well-known/apple-developer-merchantid-domain-association
> ```
>
> This file is checked by Apple in the production environment
> to verify that you have granted us permission to perform
> Apple Pay transactions on your dashboard.

### Create sandbox transaction
To make an Apple Pay sandbox transaction the following are required.
* An Apple Pay compatible device with a Sandbox Tester account on it
* One or more test cards added to the Sandbox Tester account on that device
* Embed loaded on an HTTPS site in an Apple Pay compatible browser
* Apple Pay enabled in the dashboard
* A card processor enabled that can process Apple Pay in the given currency.
For a currency that has a card processor that supports Apple Pay, you
should see the payment option in your app. Select Apple Pay and continue
with the payment. You should see the Apple Pay sheet appear.

### Create production transaction
To make an Apple Pay transaction in production replace the Sandbox Tester account
with a regular Apple account with real cards.
# Apple Pay on web without Embed
Source: https://docs.mattildapayments.com/guides/features/apple-pay/web-without-sdk
It is possible to use Apple Pay on the web without our SDK. To learn how to integrate
Apple Pay we recommend following Apple's [documentation][documentation].
The steps below will highlight the basics and focus on the interaction with our API.
A full [code sample is available](https://github.com/gr4vy/sample-standalone-apple-pay) that shows this integration in action.
## About this integration
Similar to our standard Embed integration, there is minimal configuration to get set up to
process Apple Pay on the web. There is no need to sign up for an Apple Developer account
with this integration.
* Upload our **Domain Association File** to your website.
* Enable Apple Pay in your merchant dashboard.
Additionally, you will then need to implement the following.
* Load the Apple Pay JS SDK.
* Render an Apple Pay button.
* Handle the click of the button.
* Verify the Apple Pay session.
* Catch the Apple Pay token and pass it to our API for processing.
## Enable Apple Pay
To enable Apple Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Apple Pay**.
Next, complete and submit the form to create a new Apple Pay service.
### Registering a domain
To process Apple Pay via the web you will need to register all the domains where the buyer can
checkout. In order to do this, navigate to your Apple Pay service via the dashboard, **Connections** -> **Apple Pay** -> **Domains** -> **Add domain name**.
> [!WARNING]
>
> **Domain Association File**
>
> Before submitting a domain name, please download the Domain Association File from
> the dashboard and upload it to every domain you wish to support.
>
> The file needs to be added to every domain in a predefined location.
>
> ```
> https://{domain}/.well-known/apple-developer-merchantid-domain-association
> ```
>
> This file is checked by Apple in the production environment
> to verify that you have granted us permission to perform
> Apple Pay transactions on your dashboard.
## Integrate Apple Pay
### Load the Apple Pay JS SDK
Since iOS 18, users can shop with Apple Pay on devices other than Macs and non-Safari browsers. On submit, a popup will display asking users to scan a code with their iOS 18+ device and complete the payment there.

To enable Apple Pay in browsers besides Safari you will need to load the Apple Pay JS SDK into your application. It is safe to load this same library in Safari as well.
```html theme={"dark"}
```
#### Content Security Policy
Make sure to allow the Apple Pay JS SDK domain in your CSP if you're using one, otherwise the script won't load and the Apple Pay option will not show in third-party browsers.
```
default-src 'self' applepay.cdn-apple.com ...; script-src 'self' applepay.cdn-apple.com ...
```
Please see the [Pay with Apple Pay in third-party browsers documentation](https://support.apple.com/en-jo/guide/safari/ibrw9b779bd3/mac) for more information.
### Render an Apple Pay button
An Apple Pay button can be displayed and customized [with Apple specific CSS](https://developer.apple.com/documentation/apple_pay_on_the_web/displaying_apple_pay_buttons_using_css).
```html theme={"dark"}
```
### Handle button click
When a button is clicked, start an [Apple Pay Session](https://developer.apple.com/documentation/apple_pay_on_the_web/apple_pay_js_api/creating_an_apple_pay_session).
```js theme={"dark"}
const onClick = async () => {
const session = new ApplePaySession(3, {
countryCode: 'AU',
currencyCode: 'AUD',
merchantCapabilities: ["supports3DS"],
supportedNetworks: ["visa", "masterCard", "amex", "discover"],
total: {
label: "Demo (Card is not charged)",
type: "final",
amount: '12.99',
},
});
...
session.begin();
};
```
### Verify session
Next, this is the bit that's specific to our API. Make an API call to our Apple Pay session endpoint to verify the Apple Pay session for
your domain. This checks if we are allowed to accept Apple Pay on your domain.
> [!NOTE]
>
> For this to work it's important to [register the domain](/guides/features/apple-pay/web#enabling-apple-pay)
> your domain for use with Apple Pay in our dashboard.
```js theme={"dark"}
...
session.onvalidatemerchant = async (event) => {
const response = await fetch(`http://api.sandbox.mattildapayments.com/digital-wallets/apple/session`, {
method: "POST",
headers: {
"Authorization": `bearer [JWT]`,
"Content-Type": "application/json",
},
body: JSON.stringify({
validation_url: event.validationURL,
domain_name: document.location.hostname,
}),
});
const merchantSession = await response.json();
session.completeMerchantValidation(merchantSession);
};
session.begin();
```
> [!WARNING]
>
> When using a real card in a sandbox environment the validation URL will be rejected by the
> [`POST /digital-wallets/apple/session`](/reference/digital-wallets/get-apple-pay-session) endpoint. Please only use test cards in the sandbox environment.
### Create a transaction
Finally, once the Apple Pay transaction has been authorized by Apple, create a transaction with our API.
> [!NOTE]
>
> This API call could be made in your frontend code, or the token could be sent to your backend for processing.
```js theme={"dark"}
session.onpaymentauthorized = (event) => {
await fetch(`http://api.sandbox.mattildapayments.com/transactions`, {
method: "POST",
headers: {
"Authorization": `bearer [JWT]`,
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: 1299,
currency: "MXN",
country: "MX",
payment_method: {
method: "applepay",
token: event.payment.token,
},
}),
});
session.completePayment({
status: ApplePaySession.STATUS_SUCCESS,
});
};
session.begin();
```
[documentation]: https://developer.apple.com/documentation/apple_pay_on_the_web/
# Card fingerprints
Source: https://docs.mattildapayments.com/guides/features/cards/fingerprints
A unique hash for every card in our vault
A card fingerprint can be used to seamlessly identify card numbers stored in your vault without the burden of PCI compliance.
Key features of card fingerprints.
* Secure and irreversible fingerprint generation for every card received by our system
* Inclusion of fingerprint values in API responses wherever payment methods are returned, ensuring seamless integration with your system
## Use-cases
There are a few use cases for card fingerprints.
1. Identifying fraud: Because our API does not return the original raw card number back via our API, it's hard to know if a card
has been used previously in a fraudulent transaction. For example, two transactions with the same masked card number of
`4111 11** **** 1111` could be the same number or two different numbers.
2. Identifying duplicate cards: Similarly, you could use the card fingerprint to determine if the same card is stored twice for a user
without needing to see the original number.
## Availability & limitations
A card `fingerprint` is returned for every `payment_method` returned by our API. Fingerprints will be the same for every unique card number used.
Because of this, payments made with Apple Pay, Click to Pay, and some Google Pay will have a different fingerprint than cards filled in by hand by your
customers.
# Decrypted Google Pay tokens
Source: https://docs.mattildapayments.com/guides/features/google-pay/decrypted-tokens
Some merchants and platforms may have the option to decrypt a Google Pay token themselves. For this scenario, we
support direct pass through of these decrypted Google Pay tokens to our API using the [`network-token` method](/reference/transactions/new-transaction#network-token-payment-method-create).
```json Payment method theme={"dark"}
{
"method": "network-token",
"token": "4111111111111111",
"expiration_date": "02/30",
"cryptogram": "AAEBAwQjSQAAXX...",
"eci": "05",
"card_suffix": "1234",
"card_scheme": "visa",
"card_source": "google-pay",
"cardholder_name": "John Smith"
}
```
# Google Pay on Android with the SDK
Source: https://docs.mattildapayments.com/guides/features/google-pay/mobile
The Android SDK supports native Google Pay out of the box.
## About this integration
The Android SDK requires minimal configuration to get set up to process Google Pay. Unlike
some other integrations it does not require you to sign up for a Google Developer account.
## Enable Google Pay
To enable Google Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Google Pay**.
Next, fill in your merchant name and the domain name(s) where you want to
use Google Pay.

## Test Google Pay
To test Google Pay follow our [quick start guide](/guides/payments/android/quick-start/overview) to install the SDK into your app. Google Pay should
automatically be displayed as a payment option. Please follow the Google Pay documentation with further guides on how
to add [test cards](https://developers.google.com/pay/api/android/guides/resources/test-card-suite) for use in
a sandbox environment.
# Google Pay on Android without the SDK
Source: https://docs.mattildapayments.com/guides/features/google-pay/mobile-without-sdk
It is possible to use Google Pay without the SDK.
## About this integration
Even without the Android SDK, there is only minimal configuration required to get set up to process Google Pay. Unlike
some other integrations it does not require you to sign up for a Google Developer account.
## Enable Google Pay
To enable Google Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Google Pay**.
Next, fill in your merchant name and the domain name(s) where you want to
use Google Pay.
## Integrate Google Pay
**Java**
To learn how to integrate Google Pay we recommend
following Google's [tutorial][tutorial]. The steps below will highlight any differences
and specifics for our API.
### Set gateway and merchant ID
In step 2 of [Google's tutorial][tutorial] you are instructed to request a payment token for your provider.
In our case, the value for `gateway` needs to be set to `gr4vy`, and the value of `gatewayMerchantId` needs
to be set to `app.gr4vy.sandbox.mattilda.[merchant_account_id]` for your sandbox environment, and
`app.gr4vy.mattilda.[merchant_account_id]` in production.
```java Java theme={"dark"}
private static JSONObject getGatewayTokenizationSpecification() throws JSONException {
return new JSONObject() {{
put("type", "PAYMENT_GATEWAY");
put("parameters", new JSONObject() {{
put("gateway", "gr4vy");
put("gatewayMerchantId", "app.gr4vy.sandbox.example.default");
}});
}};
}
```
```kotlin Kotlin theme={"dark"}
private fun gatewayTokenizationSpecification(): JSONObject {
return JSONObject().apply {
put("type", "PAYMENT_GATEWAY")
put("parameters", JSONObject(mapOf(
"gateway" to "gr4vy",
"gatewayMerchantId" to "app.gr4vy.sandbox.example.default")))
}
}
```
### Create a transaction
In step 9 of Google's tutorial, you will have a `paymentData` that needs to be
sent to the gateway. You can send this object to our [`POST /transactions`](/reference/transactions/new-transaction#google-pay-payment-method-create)
endpoint either directly or via your server.
The payment method used needs to contain the data from the Google Pay payload.
```json Payment method data theme={"dark"}
{
"amount": 1299,
"currency": "MXN",
"country": "MX",
"payment_method": {
"method": "googlepay",
"token": "[paymentData.paymentMethodData.tokenizationData.token]",
"card_suffix": "[paymentData.paymentMethodData.info.cardDetails]",
"card_scheme": "[paymentData.paymentMethodData.info.cardNetwork]",
"redirect_url": "https://example.com/callback"
}
}
```
> [!NOTE]
>
> We strongly recommend always providing a `redirect_url`, just in case any connection
> is configured to use 3-D Secure.
>
> This URL will be appended with both a transaction ID
> and status (e.g. `https://example.com/callback?transaction_id=123
> &transaction_status=capture_succeeded`) after 3-D Secure has been completed.
**React Native**
In React Native you can use any Google Pay integration, together with your merchant identifier.
One of the easiest solutions is to use a library like [React Native Google Pay](https://www.npmjs.com/package/react-native-google-pay) to get
a Google Pay token.
On initialization, any of these libraries will require you to set the Google Pay merchant identifier
and our gateway ID. You should set the gateway value to `gr4vy` and the `gatewayMerchantId` to your
environment, e.g. `app.gr4vy.sandbox.mattilda.[merchant_account_id]`.
```js theme={"dark"}
import { GooglePay } from 'react-native-google-pay';
const allowedCardNetworks = ['VISA', 'MASTERCARD'];
const allowedCardAuthMethods = ['PAN_ONLY', 'CRYPTOGRAM_3DS'];
const requestData = {
cardPaymentMethod: {
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
gateway: 'gr4vy',
gatewayMerchantId: 'app.gr4vy.sandbox.example.default',
},
allowedCardNetworks,
allowedCardAuthMethods,
},
transaction: {
totalPrice: '10',
totalPriceStatus: 'FINAL',
currencyCode: 'AUD',
},
merchantName: 'Example Merchant',
};
// Set the environment before the payment request
GooglePay.setEnvironment(GooglePay.ENVIRONMENT_TEST);
```
Once the user has approved the payment, your application will receive a Google Pay token from the library.
You can pass this library to our server for processing.
```js theme={"dark"}
GooglePay.requestPayment(requestData)
.then((token: string) => {
return fetch('https://api.mattildapayments.com/transactions', {
method: 'POST',
headers: {
"Authorization": "Bearer [TOKEN]"
},
body: {
amount: 1299,
currency: "MXN",
payment_method: {
method: "googlepay",
token: token,
redirect_url: 'https://example.com/callbacl'
}
}
})
.then(res => res.json())
.then(successHandler)
.catch(errorHandler)
})
.catch((error) => console.log(error.code, error.message));
```
> [!NOTE]
>
> We strongly recommend always providing a `redirect_url`, just in case any connection
> is configured to use 3-D Secure. This can be set to an application URL or URN if needed.
>
> This URL will be appended with both a transaction ID
> and status (e.g. `https://example.com/callback?transaction_id=123
> &transaction_status=capture_succeeded`) after 3-D Secure has been completed.
## Test Google Pay
Please follow the Google Pay documentation with further guides on how
to add [test cards](https://developers.google.com/pay/api/android/guides/resources/test-card-suite) for use in
a sandbox environment.
[tutorial]: https://developers.google.com/pay/api/android/guides/tutorial
# Google Pay
Source: https://docs.mattildapayments.com/guides/features/google-pay/overview
Google Pay is supported both on the web and in Android applications. In both environments, Google Pay can be
integrated using our SDK and without our SDK.
## Prerequisites
To enable Google Pay transactions, our system is directly integrated with Google. As a result,
it transmits decoded device tokens to payment services instead of encrypted gateway tokens.
Please note that not all payment services support decoded Google Pay tokens, and they
may require this feature to be activated.
We recommend contacting your payment service provider to enable this feature.
## Web (Embed)
On the web, Google Pay can be easily integrated both with and without Embed. In both offerings, we have removed
the need for you to sign up for a Google Developer account, reducing additional financial and maintenance costs.
| | [Using SDK (Embed)][web] | [Without SDK][web-without] |
| - | - | - |
| Google Developer account required? | No | No |
| Customization & Theming? | Limited | Full |
| Integrated with Checkout Flow? | Yes | Optional |
## Mobile (Android)
On Android, Google Pay can be easily integrated both with and without the SDK. In both offerings, we have removed
the need for you to sign up for a Google Developer account, reducing additional financial and maintenance costs.
| | [Using SDK][mobile] | [Without SDK][mobile-without] |
| - | - | - |
| Google Developer account required? | No | No |
| Customization & Theming? | Limited | Full |
| Integrated with Checkout Flow? | Yes | Optional |
## Recurring payments
Recurring payments are supported on Google Pay in a similar way to how
[recurring payments][recurring-payments] are supported regular card payments.
> [!WARNING]
>
> To facilitate recurring Google Pay payments, your payment service provider needs to
> support decoded Google Pay tokens as well as recurring payment flags. Please contact your
> payment service provider to enable this feature.
[web]: /guides/features/google-pay/web
[web-without]: /guides/features/google-pay/web-without-sdk
[mobile]: /guides/features/google-pay/mobile
[mobile-without]: /guides/features/google-pay/mobile-without-sdk
[recurring-payments]: /guides/features/recurring-payments
# Google Pay on web with Embed
Source: https://docs.mattildapayments.com/guides/features/google-pay/web
Google Pay is the faster, more secure way to pay online using cards saved
in your customer's Google Account.
We support Google Pay out of the box in Embed with minimal configuration.
## About this integration
Embed requires minimal configuration to get set up to process Google Pay. Unlike
some other integrations it does not require you to sign up for a Google Developer account.
## Enable Google Pay
To enable Google Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Google Pay**.
Next, fill in your merchant name and the domain name(s) where you want to
use Google Pay.

## Test Google Pay
To test Google Pay visit the site that has Embed loaded on it. Google Pay should
automatically be displayed. Please follow the Google Pay documentation with further guides on how
to add [test cards](https://developers.google.com/pay/api/android/guides/resources/test-card-suite) for use in
a sandbox environment.
# Google Pay on web without Embed
Source: https://docs.mattildapayments.com/guides/features/google-pay/web-without-sdk
It is possible to use Google Pay on the web without our SDK. To learn how to integrate
Google Pay we recommend following Google's [tutorial][tutorial].
The steps below will highlight any differences and specifics for our API.
## About this integration
Even without Embed, there is only minimal configuration required to get set up to process Google Pay.
There is no need to sign up for a Google Developer account with this integration.
> [!NOTE]
>
> For Android apps which use this option with `WebViews`, please note that platform specific
> Android Google Pay APIs must be invoked.
> Please refer to [Google's FAQ](https://developers.google.com/pay/api/web/support/faq) for more
> information.
## Enable Google Pay
To enable Google Pay, head over to your dashboard and then go to
**Connections** -> **Catalog** -> **Google Pay**.
Next, fill in your merchant name and the domain name(s) where you want to
use Google Pay.

## Integrate Google Pay
The following steps highlight the integration points with our system using
Google's [tutorial][tutorial] for Google Pay.
### Fetch a Google Pay session
First, before you can render a Google Pay button, you will need to call our API to get a token and your Gr4vy gateway ID.
Call the [`POST /digital-wallets/google/session`](/reference/digital-wallets/get-google-pay-session) API with the domain you want to host Google Pay on. This needs to be the full domain including any subdomains like `www.`.
```json Request theme={"dark"}
{ "origin_domain": "www.example.com" }
```
This will return your gateway merchant ID as well as a JWT that authorized Gr4vy to run on your domain.
```json Response theme={"dark"}
{
"gateway_merchant_id": "app.gr4vy.sandbox.example.default",
"token": "eyJhbGciOiJFUzI1NiIsInR5cCI....NwRL9ZZg0N--ZyP6I0dDfHHoWhVkrHpQ"
}
```
### Set gateway and merchant ID
Next, in step 2 of [Google's tutorial][tutorial] you are instructed to request a payment token for your provider.
In our case, the value for `gateway` needs to be set to `gr4vy`, and the value of `gatewayMerchantId` needs
to be set to the value you received from our session API in the previous step.
```js theme={"dark"}
const tokenizationSpecification = {
type: "PAYMENT_GATEWAY",
parameters: {
gateway: "gr4vy",
gatewayMerchantId: "app.gr4vy.sandbox.example.default",
},
};
```
### Set the merchant info
Next, in step 8, you will need to set a `merchantInfo` object. This authorized Gr4vy to accept Google Pay on your domain.
When setting the `merchantInfo` object, make sure to set the `token` returned from our session API, your merchant name, our Gr4vy merchant ID, and the full domain you passed to our session API (including any subdomains like `www.`)
```js theme={"dark"}
const merchantInfo = {
authJwt: "eyJhbGciOiJFUzI1NiIsInR5cCI....NwRL9ZZg0N--ZyP6I0dDfHHoWhVkrHpQ",
merchantId: "BCR2DN4T7C3KX6DY", // This identifies Gr4vy
merchantName: "Example App",
merchantOrigin: "www.example.com",
};
```
> [!WARNING]
>
> **`OR_BIBED_11`** / **`OR_BIBED_6`** - If you were to encounter any kind of
> `OR_BIBED` error you likely did not pass the right domain to our API, or you
> did not pass the same domain to our session API and the `merchantInfo` object.
### Create a transaction
In step 10 of Google's tutorial, within the `onPaymentAuthorized` function
you will have a `paymentData` that needs to be sent to the gateway. You can send
this object to our [`POST /transactions`](/reference/transactions/new-transaction#google-pay-payment-method-create) endpoint either directly or via your server.
The payment method used needs to contain the data from the Google Pay payload.
```json Payment method data theme={"dark"}
{
"amount": 1299,
"currency": "MXN",
"country": "MX",
"payment_method": {
"method": "googlepay",
"token": "[paymentData.paymentMethodData.tokenizationData.token]",
"card_suffix": "[paymentData.paymentMethodData.info.cardDetails]",
"card_scheme": "[paymentData.paymentMethodData.info.cardNetwork]",
"redirect_url": "https://example.com/callback"
}
}
```
> [!NOTE]
>
> We strongly recommend always providing a `redirect_url`, just in case any
> connection is configured to use 3-D Secure. This URL will be appended with
> both a transaction ID and status (e.g.
> `https://example.com/callback?transaction_id=123
> &transaction_status=capture_succeeded`) after 3-D Secure has been completed.
## Test Google Pay
To test Google Pay visit the site that has your integration loaded on it. Please follow the Google Pay documentation with further guides on how
to add [test cards](https://developers.google.com/pay/api/android/guides/resources/test-card-suite) for use in
a sandbox environment.
[tutorial]: https://developers.google.com/pay/api/web/guides/tutorial
# Linking guests buyer details
Source: https://docs.mattildapayments.com/guides/features/guest-checkout/linking
Use guest buyer details in combination with stored buyer records and their payment methods
In some situations you may want to use guest buyer details but also use a stored buyer's payment methods.
For example, you may manage all the buyer billing and shipping details in your ecommerce platform and do not want to have to keep this in sync with our API. Yet, you
also would like to offer a card-on-file experience at checkout where a buyer can use their stored payment methods.
In these situations it makes sense to create a buyer record via our API with little to no details, passing all billing and shipping details as guest details,
while using the buyer record just to link payment methods and transactions. Once created, you can use the buyer's ID or external identifier to link a payment to that buyer,
while only the guest details are passed to the payment services.
```json API theme={"dark"}
{
"amount": 1299,
"currency": "MXN",
"payment_method": {
// This works with any payment method,
// as well as checkout sessions
...
},
// The buyer to link the payment (and any to-be-stored payment method) to
"buyer_id": "e84fbc2a-3ee9-4ed5-9fc3-00c8e61fd8c5",
// Alternatively use the buyer external identifier
"buyer_external_identifier": "buyer-12345",
// The buyer information used for this transaction.
"buyer": {...}
}
```
```js Embed (Node) theme={"dark"}
setup({
...
// The buyer to link the payment (and any to-be-stored payment method) to.
// This will also be used to load any stored payment methods.
buyerId: "e84fbc2a-3ee9-4ed5-9fc3-00c8e61fd8c5",
// Alternatively use the buyer external identifier
buyerExternalIdentifier: "buyer-12345",
// The buyer information used for this transaction.
buyer: {...}
})
```
```jsx Embed (React) theme={"dark"}
```
```swift iOS theme={"dark"}
Gr4vy.init(
...
// The buyer to link the payment (and any to-be-stored payment method) to.
// This will also be used to load any stored payment methods.
buyerId: "e84fbc2a-3ee9-4ed5-9fc3-00c8e61fd8c5"
// Alternatively use the buyer external identifier
buyerExternalIdentifier: "buyer-12345"
// The buyer information used for this transaction.
buyer: Gr4vyBuyer(...)
)
```
```java Android theme={"dark"}
gr4vySDK.launch(
...
// The buyer to link the payment (and any to-be-stored payment method) to.
// This will also be used to load any stored payment methods.
buyerId="e84fbc2a-3ee9-4ed5-9fc3-00c8e61fd8c5"
// Alternatively use the buyer external identifier
buyerExternalIdentifier="buyer-12345"
// The buyer information used for this transaction.
buyer = Gr4vyBuyer(...)
)
```
```js React Native theme={"dark"}
EmbedReactNative.showPaymentSheet({
...
// The buyer to link the payment (and any to-be-stored payment method) to.
// This will also be used to load any stored payment methods.
buyerId="e84fbc2a-3ee9-4ed5-9fc3-00c8e61fd8c5",
// Alternatively use the buyer external identifier
buyerExternalIdentifier="buyer-12345",
// The buyer information used for this transaction.
buyer: {...},
})
```
## Limitations
There are a few limitations to linking in-line buyer details to a stored buyer.
* Any buyer ID and buyer external identifier provided need to match the same buyer record or they may be ignored
* Any stored buyer details (name, email, addresses, etc) will be ignored when guest checkout is provided. Guest data is not merged into any existing data, instead the guest data will be the only data used.
# Guest checkout
Source: https://docs.mattildapayments.com/guides/features/guest-checkout/overview
Create transactions without a creating a buyer first
It is possible to provide buyer details, including the shipping and billing details, without the need
to [create a buyer resource](/reference/buyers/new-buyer). You can send the buyer details directly when the transaction is requested, either
to our API, Embed, or Secure Fields.
```json API theme={"dark"}
{
"amount": 1299,
"currency": "MXN",
"payment_method": {
// This works with any payment method,
// as well as checkout sessions
...
},
"buyer": {
"external_identifier": "my-unique-identifier",
"billing_details": {
"first_name": "John",
"last_name": "Smith",
"address": {
"postal_code": "789123"
}
},
"shipping_details": {
"first_name": "John",
"last_name": "Smith",
"address": {
"postal_code": "789123"
}
}
}
}
```
```js Embed (Node) theme={"dark"}
setup({
...
buyer: {
externalIdentifier: 'my-unique-identifier',
billingDetails: {
firstName: 'John',
lastName: 'Smith',
address: {
postalCode: '789123',
},
taxId: {
value: '123456',
kind: 'mx.rfc',
},
},
shippingDetails: {
firstName: 'John',
lastName: 'Smith',
address: {
postalCode: '789123',
},
},
}
})
```
```jsx Embed (React) theme={"dark"}
```
```swift iOS theme={"dark"}
Gr4vy.init(
...
buyer: Gr4vyBuyer(
externalIdentifier: "my-unique-identifier",
billingDetails: Gr4vyBillingDetails(
firstName: "John",
lastName: "Smith",
address: Gr4vyAddress(
postalCode: "789123"
),
taxId: Gr4vyTaxId(
value: "123456",
kind: "mx.rfc"
)
),
shippingDetails: Gr4vyShippingDetails(
firstName: "John",
lastName: "Smith",
address: Gr4vyAddress(
postalCode: "789123"
),
)
)
)
```
```java Android theme={"dark"}
gr4vySDK.launch(
...
buyer = Gr4vyBuyer(
externalIdentifier = "my-unique-identifier",
billingDetails = Gr4vyBillingDetails(
firstName = "John",
lastName = "Smith",
address = Gr4vyAddress(
postalCode = "789123"
),
taxId = Gr4vyTaxId(
value = "123456",
kind = "mx.rfc"
)
),
shippingDetails = Gr4vyShippingDetails(
firstName = "John",
lastName = "Smith",
address = Gr4vyAddress(
postalCode = "789123"
),
)
)
)
```
```js React Native theme={"dark"}
EmbedReactNative.showPaymentSheet({
...
buyer: {
externalIdentifier: 'my-unique-identifier',
billingDetails: {
firstName: 'John',
lastName: 'Smith',
address: {
postalCode: '789123',
},
taxId: {
value: '123456',
kind: 'mx.rfc',
},
},
shippingDetails: {
firstName: 'John',
lastName: 'Smith',
address: {
postalCode: '789123',
},
},
},
})
```
## Limitations
There are a few limitations to using in-line buyer details like this, rather than using a stored buyer record.
* A guest buyer cannot use a payment method which is assigned to another buyer resource.
* A buyer resource can not be created when using in-line buyer data. Please use the [new buyers endpoint](/reference/buyers/new-buyer) instead.
> [!NOTE]
>
> The buyer ID and buyer external identifier properties can be passed to our API and SDKs to apply guest buyer details while also using stored
> payment methods. Please see our documentation on [linking](./linking) for more details.
# Network token implementation
Source: https://docs.mattildapayments.com/guides/features/network-tokens/implementation
How to use scheme tokens with or without payment orchestration
To process payments with network tokens you can choose between either of the following options.
* Our **automatic provisioning of tokens** for use with our orchestration platform.
* Our **standalone tokenization endpoints** for using the network tokens directly with the PSPs.
> [!NOTE]
>
> Before you start processing payments with network tokens, make sure you have
> enabled processing with network tokens. Please contact the support team to get set up.
## Automatic provisioning of network tokens
Although network tokens are agnostic tokens, not every payment service or acquirer support
the usage of network tokens that were provisioned outside of their own environment.
When you use our system to orchestrate your payment, we will optimize the routing
behavior to take into consideration the limitations of the payment services you're connecting to.
A payment service that supports externally obtained data is generally considered an **open loop connection**,
while one that doesn't is considered **closed loop**.
In our orchestration platform, we can support network tokens across any open-loop
payment services. You don't have to perform any additional integrations to use network
tokens besides storing the original card data (PAN) in our Cloud Vault.
You can follow the regular flow of card integrations, and we will automatically swap out
the original card details with the network token when possible.
For each first time use of the token a cryptogram is provisioned. Subsequent merchant initiated
transactions (MIT) will not need a cryptogram (these are optional), unless the transaction is done
with a newly provisioned token. For example if you have migrated an already running billing
sequence for a card to our systems and for these cards you’re provisioning tokens for the first time,
the first transaction done with that token will have a cryptogram provisioned automatically by mattilda Pay.
The token and cryptogram will be provisioned as “on file” and therefore the buyer does not have
to be present for the provisioning of either the token or the cryptogram.
We have optimized the usage of network tokens by implementing scheme best practices
regarding cryptogram usage, as well as the correct payment flagging towards the payment services.
Using Flow, it will be possible to choose the instrument (PAN or Network token) in your
routing rules, allowing you to optimize your routing behavior.
For best practices and advice on routing optimizations, please reach out to our support team.
## Standalone tokenization endpoints
Our API allows you to provision network tokens and cryptograms for use in your own system.
Please note that network tokens can be considered PCI sensitive data depending on your
interpretation of PCI guidelines, and therefore these API's are not enabled in production by default.
You can use the [network token endpoints][endpoints] to obtain network tokens and their cryptograms
for use in your own system.
> [!WARNING]
>
> Network token provisioning via the API is not enabled by default in production.
> Please contact support for further guidance.
[endpoints]: /reference/network-tokens/
# Network token lifecycle management
Source: https://docs.mattildapayments.com/guides/features/network-tokens/lifecycle
Managing the full lifecycle of network tokens
Our system has been set up to automatically keep your network tokens up to date.
We will automatically receive updates when the underlying card receives any updates, and we will
apply this to the stored card details in our system.
The cardholder can interact with their card in multiple ways which can result in these
lifecycle events.
* The contract with the issuer is terminated rendering all cards and related tokens
invalid. In this case, all the associated network tokens are terminated and deleted.
* A user reports a card lost or stolen or damaged. In this case, the issuer issues a new card and all
the associated tokens stay active but any data related to the underlying card number may
change, for example, the last four digits of the card may change.
* The card expires. In this case, the issuer issues a new card and all
the associated tokens stay active but any data related to the underlying card number may
change, for example, the expiration date of the card may change.
* The user triggers a token revocation from the issuer side, for example from the issuer's
mobile banking application. In this case, any of the associated network tokens may be
terminated and deleted.
All of these events are automatically managed when you use our Cloud Vault.
## Usage data
Using different instruments per transaction attempt
is possible. We provide insight as to which instrument was used per
transaction attempt via the **retry event report**. This report can be fetched via the API or
via the dashboard. In the report, the used instrument is listed per transaction attempt.
If the first attempt was done using the original card, and a retry was done using a
network token, then the transaction will show as having used a “network token” in the dashboard.
## Manual lifecycle management
Using the following endpoints it is possible to manually manage the token lifecycle for
a stored token. Using these endpoints will change the status at the respective scheme
token service and will notify the issuer.
* [Suspend token endpoint][suspend] - Used to temporarily disable a provisioned token. The token will be temporarily suspended.
The token can be resumed by using the `/resume` API. This API is only supported for Visa cards.
* [Resume token endpoint][resume] - Used to re-enable a provisioned token. The token status will
change from its previously suspended state into the active state. This API is only supported for Visa cards.
* [Delete token endpoint][delete] - Used to permanently remove a provisioned token. The token will be deleted and will need to
be re-provisioned.
[suspend]: /reference/network-tokens/suspend-network-token
[resume]: /reference/network-tokens/resume-network-token
[delete]: /reference/network-tokens/delete-network-token
# Network tokens
Source: https://docs.mattildapayments.com/guides/features/network-tokens/overview
Using scheme tokens with payment orchestration
Network tokens are a technology created by [EMVCo][emvco] to make the payment ecosystem safer and
more robust.
## EMV Payment Tokenization
The **primary account number** (PAN) – the number printed on your card - is a particularly
sensitive piece of data. EMV Payment Tokenization (or network tokenization) provides a
technology solution for protecting the PAN and securing digital and online payments.
Tokenization is achieved by taking the PAN and replacing it with a unique alternative value,
a payment token. This token is limited to the merchant it's been created for, which limits
the use of the token in case it's ever compromised. Unlike a PAN, a network token can not be used
to process a transaction with another merchant.
Network tokens comply with industry-standardized EMVCo specifications that not only
adhere to PCI standards but are also identifiable across the entire transaction lifecycle.
This enables significant ecosystem benefits for merchants using network tokens.
* **Higher authorization rates** - Once a stored PAN has been securely replaced with a
network token, any changes to the underlying card details get automatically applied
to the associated network token. For example, if a customer's card expires the
network would automatically update any associated network token(s) directly so that
the stored card remains current and usable with that token. This reduces the number
of charges declined due to outdated data, and increases the authorization rates -
particularly cards used for recurring and subscription payments.
* **Lower costs** - In general the card schemes maintain a lower fee for
tokenized transactions. The exact value of this will depend on your PSP, but this can
be up to 10 bps per transaction.
* **Improved security** - Network tokens can only be unlocked by the associated
payment network. Therefore if it is lost or stolen, criminals cannot
access the underlying card data at any point in the transaction lifecycle.\
In addition, each token is bound to a specific merchant and each transaction
is protected with a one-time use cryptogram. This means that the token
by itself cannot be used to initiate a transaction.
## Network tokens versus Acquirer/PSP tokens
Network tokenization is very different from acquirer tokenization or PSP tokenization, especially
when you consider the data portability benefits.
* **An acquirer or PSP token** swaps a customer's card details with a token
that can only be used by the service that generated the token. This restricts the re-use
and introduces considerable friction when using another service for failover, redundancy, or
migration.
* **A network token** swaps a customer's card details with a token that is tied to the scheme
of the card (also called the networks) and can be used by any acquirer or PSP
that can transact for that scheme. This provides ultimate flexibility to use this token with
any service, whether that is for failover or redundancy purposes, or when migrating to another service.
We recommend that you use the full range of tokenization features with our system. You can store the original
card number (PAN) in our Cloud Vault and additionally use Network Tokens for transactions. With this, you can limit
your PCI scope and optimize your payments using network tokens in an agnostic way across the payment ecosystem.
[emvco]: https://www.emvco.com/
# Network token pass through
Source: https://docs.mattildapayments.com/guides/features/network-tokens/passthrough
Fully PCI certified customers may want to provision their own network tokens rather than relying on our network token provisioning. To allow for this,
we've enabled support for network token pass through via our API, either with or without cryptogram, straight through to a connector.
* Any network token can be passed through, though acceptance (especially in sandbox) will vary by connector used
* Network tokens can benefit from our BIN insights, though in the sandbox environment the number of cards that will result in a valid BIN insights is limited
* Storing externally provisioned network tokens in our vault is currently not supported
## Usage
To pass through a network token, set the `method` value to `network-token` when [creating a transaction](reference/transactions/new-transaction#network-token-payment-method-create). The `cryptogram` value can be set as well, but is optional
in our API. Acceptance of network tokens downstream will vary per connector.
```json Payment method theme={"dark"}
{
"method": "network-token",
"number": "4111111111111111",
"expiration_date": "11/25",
"cryptogram": "..."
}
```
# Network Token Testing
Source: https://docs.mattildapayments.com/guides/features/network-tokens/testing
To test Network Tokens in `sandbox` please make sure the following applies.
* Network Tokens have been configured for your merchant account by our team
* Transactions are sent with `store: true` or with a stored card.
* A test card number from the list below is sent in the request
### Successful Network Token
| Test PAN | Scheme |
| - | - |
| `5204731600014784` | `mastercard` |
| `5204731600013711` | `mastercard` |
| `5204731600014636` | `mastercard` |
| `5204731600012804` | `mastercard` |
| `5204731600014792` | `mastercard` |
| `5204731600013729` | `mastercard` |
| `5204731600014644` | `mastercard` |
| `5204731600012812` | `mastercard` |
| `5204731600013737` | `mastercard` |
| `5186009200935811` | `mastercard` |
| `2222690420064590` | `mastercard` |
| `2222690420064574` | `mastercard` |
| `2222690420064582` | `mastercard` |
| `5120342233150747` | `mastercard` |
| `5120343287499758` | `mastercard` |
| `4622943120000600` | `visa` |
| `4895379980001778` | `visa` |
| `4622943120000618` | `visa` |
| `4622943120000626` | `visa` |
| `4895379980001802` | `visa` |
| `4622943120000634` | `visa` |
| `4622943120000642` | `visa` |
### Testing error scenarios
| Test PAN | Scheme | Error |
| - | - | - |
| `2223001850064564` | `mastercard` | `PAN_INELIGIBLE` |
| `5462970394839348` | `mastercard` | `PAN_INELIGIBLE` |
| `2223520127577835` | `mastercard` | `PAN_INELIGIBLE` |
| `5460126128200800` | `mastercard` | `PAN_INELIGIBLE` |
| `5207980000000102` | `mastercard` | `PAN_INELIGIBLE` |
| `5204731601950473` | `mastercard` | `INVALID_PAN` |
| `5204731601950473` | `mastercard` | `INVALID_PAN` |
| `5204731940398145` | `mastercard` | Declined by Issuer |
| `5204731600000239` | `mastercard` | Declined by Issuer |
| `5120340000000392` | `mastercard` | Declined by Issuer |
| `5120340000000293` | `mastercard` | Declined by Issuer |
> [!WARNING]
>
> Any other card number will be processed as ineligible and therefore
> will not be processed as a network token transaction.
# Payment links
Source: https://docs.mattildapayments.com/guides/features/payment-links/overview
Set up payment links to accept payments from your customers.
Payment links allows you to generate a link, send it to a customer via email/sms/etc,
and then have the customer pay without the need for you to host your own checkout.
## Creating a payment link
You can use the payment links endpoint to create a payment link with the data that will be
displayed on the mattilda Pay hosted page. The [payment links API endpoint](/reference/payment-links/new-payment-link) makes it
easy to get create a new payment link.
```json Request theme={"dark"}
{
"currency":"MXN",
"country":"MX",
"amount":1000,
"metadata":{
"TypeOfPayment":"purchase",
"Carbon_FootPrint":"10"
},
"cart_items":[
{
"name":"Aloe",
"unit_amount":1000,
"quantity":1,
"sku":"aloe"
}
],
"merchant_banner_url":"https://susies.store/logo.svg",
"merchant_color":"#cf6b6b",
"merchant_name":"Susie's Store",
"merchant_message":"Thanks for your purchase at Susie's Store!",
"merchant_terms_and_conditions_url":"https://susies.store/terms-and-conditions",
"return_url":"https://susies.store/success"
}
```
The payment link will include the `expires_at`, `status`, and other useful information
that will be used by the mattilda Pay hosted page. Make note of the returned `id` as it will be used in the next step.
```json Response theme={"dark"}
{
"id": "09e90ace-a746-41f5-88d2-8b16335ded97",
"type": "payment-link",
"expires_at": "2025-01-28T14:45:45.929102+00:00",
"amount": 1000,
"currency": "MXN",
"country": "MX",
"status": "active",
...
}
```
On top of the `merchant_*` specific values, this API supports values that are going to be displayed by the mattilda Pay hosted page
and also passed to [Embed](/guides/payments/embed/options#options) to process the transaction.
* `amount`
* `currency`
* `country`
* `metadata`
* `cart_items`
* `buyer`
* `externalIdentifier`
* `intent`
* `paymentSource`
By creating a payment link you're ready to send it to your customer to complete the payment.
# Sharing the payment link
Source: https://docs.mattildapayments.com/guides/features/payment-links/sharing
With the payment link created, you can now share it with your customer.
mattilda Pay by default hosts a payment link page with the data you created at the following URL.
```
https://checkout.mattildapayments.com/link/{payment_link_id}
```
* `{payment_link_id}` is the `id` of the payment link you created in the previous step
For example, in production.
```
https://checkout.mattildapayments.com/link/954289d7-d701-45ff-a67c-445e60f6e5af
```
Or in sandbox.
```
https://checkout.sandbox.mattildapayments.com/link/daf08adb-39bb-4038-b1f1-c52c791e75b6
```
# Payment link expiration and statuses
Source: https://docs.mattildapayments.com/guides/features/payment-links/statuses
Your customer will use the payment link to create the payment. If the transaction is successful, the customer
will be redirected to the `return_url` you specified or an internal success screen otherwise.
## Statuses
The page will display different content based on the status of the payment link.
### Generic error
Either the payment link id provided is invalid or some other error occurred when loading the page (e.g. network error).

### Payment Link Not Found
The payment link id provided is valid but the resource associated with it could not be found.

### Redirecting
Embed has successfully processed the transaction and the page is redirecting the customer to the `return_url` or the internal success screen.

### Payment Successful (internal)
The payment was successful and a `return_url` was not specified. Also displays if the payment link has already been used.

## Expiration
By default, payment link expires in 24 hours. This can be configured separately by setting the `expires_at` field in the API.
Once expired, a payment link will no longer load and instead show the following screen.

# Recurring transactions with Embed
Source: https://docs.mattildapayments.com/guides/features/recurring-payments/embed
Embed will automatically try to apply the right flags based on the situation, mainly using the provided `paymentSource` property and whether a stored card is used for the transaction.
By default, the flags from the [E-commerce](./scenarios#e-commerce)
scenario are used for a regular card payment. For transactions where the card is stored,
Embed applies the properties from the [Fast checkout](./scenarios#fast-checkout) scenario.
A `paymentSource` prop can be set when initializing Embed and it can be set to
either `installment` or `recurring`. In those cases, the card will always be
stored (forcing `store=true`) and every transaction is marked as being the first
in a series (`is_subsequent_payment=false`).
As a result, with `paymentSource` set to `installment` or `recurring` you will
be provided with a payment method that can be re-used to create
subsequent merchant-initiated subsequent transactions.
# Recurring payments with network tokens
Source: https://docs.mattildapayments.com/guides/features/recurring-payments/network-tokens
To process transactions with [open-loop](./open-loop) providers our system
can use both a conventional PAN (the number found on your card) or a network token.
Network tokens are a replacement for the actual card data that unlike proprietary PSP
tokens are issued by the schemes and interchangeable between different
open-loop providers.
Network tokens are linked to a concrete merchant and buyer combination. This reduces
PCI scope for you while at the same time providing an authorization
uplift on the issuer side because of increased issuer trust in the underlying
funding source.
As a merchant, to start using network tokens you'll need to contact our support team to be
set up. As part of the setup, we can accept any existing **Requestor ID** or if you're not
already enrolled in the schemes we will help you set one up as part of onboarding.
# Open-loop versus closed-loop
Source: https://docs.mattildapayments.com/guides/features/recurring-payments/open-loop
Card processors can be either classified as open or closed-loop processors.
We define a processor as being open-loop when it allows us to process a subsequent transaction that had its initial transaction with a different processor. Additionally, open-loop processors generally support network tokens as well.
A closed-loop processor on the other can only be used to make subsequent transactions that were originally started with the same processor. For these processors, subsequent transactions can only ever be created using the same proprietary PSP token, limiting its re-use.
## Merchant-initiated transactions
As a consequence of the above, in the subsequent merchant-initiated transaction (MIT) scenario we are limited as to what connection we can use to process the transaction, regardless of what the [flow routing rules](/guides/dashboard/flow/card-transactions#action-route-to-connection)
may define.
Our logic for filtering subsequent MIT transactions is as follows.
* If the original initial transaction went through an open-loop connection, only connections from open-loop processes will be used for a subsequent MIT.
* If the original initial transaction went through a closed-loop connection, only that specific connection can be used for a subsequent MIT.
From our current connections, the main closed-loop processor is [Stripe](/connections/payments/stripe-card). Stripe does support open-loop processing for some select merchants. If this has been enabled for you then Stripe can be toggled to behave as an open-loop processor from the dashboard.
# Recurring payments
Source: https://docs.mattildapayments.com/guides/features/recurring-payments/overview
To support recurring billing some connections (mainly card processors)
require transactions to be marked accordingly to properly indicate if a transaction
is part of a recurring sequence of transactions. It is important to set these
indicators correctly to ensure a successful authorization for subsequent transactions.
Recurring transactions can generally be categorized as scheduled payments,
unscheduled payments, subscriptions, or installments.
## Recurring payment flags
To facilitate recurring payments we support three properties that can be set
[when creating a new card transaction](/reference/transactions/new-transaction).
* `payment_source` - The source of the transaction. This defaults to `ecommerce` and
can be set to `recurring`, `installment`, or `card_on_file`.
* `merchant_initiated` - Indicates whether the transaction was initiated by the
merchant (`true`) or if the customer was present (`false`).
* `is_subsequent_payment` - Indicates whether the transaction represents a
subsequent payment. Please note this flag is only compatible when the
`payment_source` is set to `recurring`, `installment`, or `card_on_file` and
will be ignored for other values or if `payment_source` is not present.
We will automatically map these 3 properties to your downstream payment
service's properties, where they apply. Currently, these mostly only apply to card
processors.
> [!WARNING]
>
> When performing an subsequent MIT transaction without storing the card data in our vault, it's recommended to provide the
> `previous_scheme_transaction_id` where possible. This should represent the `scheme_transaction_id` returned in the initial
> transaction.
>
> If you use a stored payment method we will handle this logic for you automatically.
## Best practices
Please follow the following best practices when creating recurring payments.
* When created a customer-initiated transaction (CIT), with
`merchant_initiated=false`, providing the `security_code` (CVV) is highly
recommended. Not doing so could result in declined transactions.
* Before creating a merchant-initiated transaction (MIT), with
`merchant_initiated=true`, it's highly recommended to make an initial CIT first so the
customer gives their authorization. Any subsequent transaction will then be identified as being authorized by this first transaction.
* When performing a subsequent MIT transaction without storing the card data in our vault, it's recommended to provide the
`previous_scheme_transaction_id` where possible. This should represent the `scheme_transaction_id` returned in the initial
transaction. If you use a stored payment method we will handle this logic for you automatically.
# Common scenarios
Source: https://docs.mattildapayments.com/guides/features/recurring-payments/scenarios
The following is a list of common scenarios that merchants use when creating
transactions. Your use case will really depend on how your checkout is handled.
## E-commerce
A customer provides their payment details for a one-off payment and the payment
method is not stored. The transaction is created directly after the payment
details are provided.
* `payment_source=ecommerce`
* `merchant_initiated=false`
* `is_subsequent_payment=false`
This is the end of this scenario. There is no merchant-initiated part.
## Fast checkout
A customer at checkout agrees to store their card for quicker checkouts in the
future.
* `payment_source=card_on_file`
* `merchant_initiated=false`
* `is_subsequent_payment=false`
The same customer then returns to the checkout at a later point and decides to
checkout with this stored card.
* `payment_source=card_on_file`
* `merchant_initiated=false`
* `is_subsequent_payment=true`
> [!NOTE]
>
> Embed automatically applies the properties in this scenario for new and stored
> payment methods when the `paymentSource` prop is left to its default value.
## Unscheduled payments
A customer at checkout agrees to store their card for future transactions, and
allows the merchant to initiate an unscheduled transaction in the case that there
are any additional charges they incur on their account.
* `payment_source=card_on_file`
* `merchant_initiated=false`
* `is_subsequent_payment=false`
At a later point, this same customer might incur some extra charges on their
account. The merchant can then charge the card while the customer is not
present.
* `payment_source=card_on_file`
* `merchant_initiated=true`
* `is_subsequent_payment=true`
The key difference between this scenario and a subscription is that a
subscription is generally handled as a scheduled payment with a predictable
amount and recurrence, where an unscheduled payment can occur outside of a
schedule and for any amount.
> [!WARNING]
>
> When doing a subsequent MIT transaction without storing the card data in our vault, it's recommended to provide the
> `previous_scheme_transaction_id` where possible. This should represent the `scheme_transaction_id` returned in the initial
> transaction.
>
> If you use a stored payment method we will handle this logic for you automatically.
## Installments
A customer at checkout agrees to pay for goods over a certain amount of
installments.
* `payment_source=installment`
* `merchant_initiated=false`
* `is_subsequent_payment=false`
A customer is then charged for each subsequent installment by the merchant when
the payment is due. The customer is not present for this transaction.
* `payment_source=installment`
* `merchant_initiated=true`
* `is_subsequent_payment=true`
The key difference between this scenario and a subscription is that an
installment has a finite number of transactions, where a subscription is
generally recurring until the subscription is canceled.
> [!WARNING]
>
> When doing an subsequent MIT transaction without storing the card data in our vault, it's recommended to provide the
> `previous_scheme_transaction_id` where possible. This should represent the `scheme_transaction_id` returned in the initial
> transaction.
>
> If you use a stored payment method we will handle this logic for you automatically.
## Subscriptions
A customer at checkout agrees to pay for a regular recurring subscription for a
certain amount, paid at a fixed interval.
* `payment_source=recurring`
* `merchant_initiated=false`
* `is_subsequent_payment=false`
This customer is then charged for each subsequent payment when the payment is
due. The customer is not present for this transaction.
* `payment_source=recurring`
* `merchant_initiated=true`
* `is_subsequent_payment=true`
> [!WARNING]
>
> When doing an subsequent MIT transaction without storing the card data in our vault, it's recommended to provide the
> `previous_scheme_transaction_id` where possible. This should represent the `scheme_transaction_id` returned in the initial
> transaction.
>
> If you use a stored payment method we will handle this logic for you automatically.
## MOTO
Customer's card data is collected via mail (Mail Order) or telephone (Telephone Order) and typed in by a support
agent or an automated scanning process.
* `payment_source=moto`
* `merchant_initiated=false`
* `is_subsequent_payment=false`
Optionally, a merchant can then charge the customer when a recurring payment is due.
The customer is not present for this and so the transaction should be created as a MIT transaction.
* `payment_source=recurring`, `installment`, or `card_on_file`
* `merchant_initiated=true`
* `is_subsequent_payment=true`
> [!WARNING]
>
> When doing an subsequent MIT transaction without storing the card data in our vault, it's recommended to provide the
> `previous_scheme_transaction_id` where possible. This should represent the `scheme_transaction_id` returned in the initial
> transaction.
>
> If you use a stored payment method we will handle this logic for you automatically.
# Transaction simulators
Source: https://docs.mattildapayments.com/guides/features/simulators/overview
We provide a payment simulators for card payments, allowing you
to test card payments, redirect payments, and push payments respectively.
These simulators do not connect to any PSP and instead provide mocked responses
based on the amounts or other values passed in.
> [!NOTE]
>
> We also provide a way to [simulate real-time account
> updates](/guides/features/account-updater/real-time#simulator).
## Setup
To set up a simulator, head over to your sandbox dashboard.
Once there, each simulator will be available to set up with a custom merchant ID. This ID does
not serve any purpose.
Please note that simulators are not available in production environments.
## Test values
### Payments
When creating a payment, the following test values can be used to simulate various error codes.
| Simulator amount | `error_code` |
| :- | :- |
| 200001 | `canceled_payment_method` |
| 200002 | `disputed_transaction` |
| 200003 | `duplicate_transaction` |
| 200004 | `expired_authorization` |
| 200005 | `expired_payment_method` |
| 200006 | `incorrect_billing_address` |
| 200007 | `incorrect_country` |
| 200008 | `incorrect_currency` |
| 200009 | `incorrect_cvv` |
| 200010 | `incorrect_expiry_date` |
| 200011 | `insufficient_funds` |
| 200012 | `issuer_decline` |
| 200013 | `other_decline` |
| 200014 | `requires_buyer_authentication` |
| 200015 | `refused_transaction` |
| 200016 | `service_decline` |
| 200017 | `suspected_fraud` |
| 200018 | `unavailable_payment_method` |
| 200019 | `unknown_payment_method` |
| 200020 | `unsupported_transaction` |
| 200021 | `unsupported_payment_method` |
| 200022 | `cancelled_buyer_approval` |
| 300001 | `insufficient_service_permissions` |
| 300002 | `invalid_amount` |
| 300003 | `invalid_payment_method` |
| 300004 | `invalid_service_configuration` |
| 300005 | `invalid_service_credentials` |
| 300006 | `invalid_service_response` |
| 300007 | `invalid_tax_identifier` |
| 300008 | `missing_billing_address` |
| 300009 | `missing_cvv` |
| 300010 | `missing_shipping_address` |
| 300011 | `missing_tax_identifier` |
| 300012 | `refund_period_expired` |
| 300013 | `service_error` |
| 300014 | `service_network_error` |
| 300015 | `service_rate_limit` |
| 400001 | `internal_error` |
| 400002 | `invalid_billing_address` |
| 400003 | `invalid_operation` |
| 400004 | `invalid_request_parameters` |
| 400005 | `invalid_service_request` |
| 400006 | `invalid_shipping_address` |
| 400007 | `service_resource_conflict` |
| 400008 | `unexpected_state` |
| 400009 | `unknown_error` |
| 400010 | `unknown_service_resource` |
| 400011 | `unsupported_country` |
| 400012 | `unsupported_currency` |
| 400013 | `unrecognised_country` |
| 400014 | `unrecognised_currency` |
| 400015 | `unrecognised_payment_method` |
| 400016 | `unrecognised_scheme` |
| 400017 | `unsupported_scheme` |
### Captures
When capturing an authorized payment, the following responses can be simulated.
When creating a payment, the following test values can be used to simulate various error codes.
| Simulator amount | `status` |
| :- | :- |
| 10 | `authorization_succeeded` |
| 20 | `capture_pending` |
| 30 | `authorization_succeeded` |
| 40 | `authorization_succeeded` |
Our API does not currently return error codes for failed captures in the API,
but the values 10, 30, and 40 will provide different error codes in a future
release.
> [!WARNING]
>
> Transactions in a `capture_pending` state can be moved to the next state using [webhooks](./webhooks).
### Refunds
When refunding a card payment, the following responses can be simulated.
When creating a payment, the following test values can be used to simulate various error codes.
| Simulator amount | `status` |
| :- | :- |
| 1 | `declined` |
| 2 | `processing` |
| 3 | `failed` |
| 4 | `failed` |
Our API does not currently return error codes for failed refunds in the API,
but values 3, and 4 will provide different error codes in a future release.
# SPEI bank transfers
Source: https://docs.mattildapayments.com/guides/features/spei/overview
Accept payments by SPEI bank transfer in Mexico.
SPEI (Sistema de Pagos Electrónicos Interbancarios) lets your buyers pay with a bank transfer from
any bank in Mexico. When you create a SPEI transaction, mattilda Pay generates a CLABE (an 18-digit
bank account number) for that charge. The buyer transfers the amount to that CLABE from their banking
app, and the transaction is confirmed automatically once the deposit arrives.
| Property | Value |
| :- | :- |
| `method` | `spei` |
| Country | `MX` |
| Currency | `MXN` |
| Payment flow | Asynchronous (push payment) |
## How it works
1. You create a transaction with `method` set to `spei`.
2. mattilda Pay generates a CLABE for the charge and returns an `approval_url` with the payment
instructions.
3. You redirect the buyer to the `approval_url`, or show the payment instructions in your own
checkout.
4. The buyer transfers the **exact amount** to the CLABE from their bank.
5. When the deposit is received, the transaction moves to `capture_succeeded` and you receive a
`transaction.captured` [webhook](/guides/features/webhooks/overview).
## Create a SPEI transaction
Create a transaction using the [`POST /transactions`](/reference/transactions/new-transaction) endpoint
with a redirect payment method.
```bash theme={"dark"}
curl -X POST https://api.mattildapayments.com/transactions \
-H "Authorization: Bearer [JWT]" \
-H "Content-Type: application/json" \
-d '{
"amount": 129900,
"currency": "MXN",
"country": "MX",
"external_identifier": "order-1234",
"buyer_external_identifier": "user-1234",
"payment_method": {
"method": "spei",
"redirect_url": "https://example.com/callback"
}
}'
```
* `amount` - The amount to charge, in the smallest currency unit (cents). `129900` is \$1,299.00 MXN.
* `external_identifier` - Your own reference for the order. We recommend always sending it, as it is
returned in every webhook and helps you reconcile the payment.
* `payment_method.redirect_url` - Where to send the buyer back to after they see the payment
instructions.
The response is a transaction that is pending payment. It includes:
* `approval_url` - A page hosted by mattilda Pay with the payment instructions for the buyer.
* `payment_service_transaction_id` - The CLABE generated for this charge.
> [!WARNING]
>
> Don't send `store: true` and don't reuse a stored payment method for SPEI transactions. Every
> charge must get its own CLABE so that the deposit can be matched to it automatically.
## Show the payment instructions
Redirect the buyer to the `approval_url`. The page shows the information the buyer needs to make the
transfer from their banking app:
* **Total a pagar**: the amount to transfer.
* **Banco**: the receiving bank.
* **CLABE**: the account number to transfer to.
* **Beneficiario**: your business name.
Once the payment is confirmed, the same page shows a success message.
If you prefer to show the instructions in your own checkout, use the CLABE in
`payment_service_transaction_id` and the transaction amount.
## Payment confirmation
SPEI transfers are usually confirmed within **30 minutes**, depending on the buyer's bank.
When the deposit is received, the transaction status changes to `capture_succeeded` and a
`transaction.captured` webhook is sent to your endpoint. Use the webhook to fulfill the order, and
[verify its signature](/guides/features/webhooks/signatures) before trusting its content.
You can also check the status at any time with the
[`GET /transactions/{transaction_id}`](/reference/transactions/get-transaction) endpoint.
## Amount rules
The buyer must transfer the **exact amount** of the transaction. Deposits that differ from the
transaction amount by more than \$1.00 MXN can't be matched to the charge and are **returned to the
buyer's account** automatically.
Partial payments are not supported: a charge can't be paid with several transfers.
> [!NOTE]
>
> Ask your buyers to copy the CLABE and the amount exactly as shown in the payment instructions.
> Most failed SPEI payments are caused by a typo in the CLABE or an amount that doesn't match.
## Best practices
* Create a new transaction for every charge. Don't ask buyers to reuse a CLABE from a previous
payment.
* Always send an `external_identifier` so you can reconcile the payment with your order.
* Rely on webhooks to confirm the payment instead of the buyer returning to your `redirect_url`: the
buyer may close the page before the transfer is confirmed.
* Process webhooks idempotently: you may receive the same event more than once.
# Creating buyers & payment methods on import
Source: https://docs.mattildapayments.com/guides/features/token-import/buyer-payment-creation
For each unique buyer ID in the token import file, we will create a new buyer record in your instance. All fields that are passed in for the buyer will be linked to the respective fields of a [buyer record](/reference/buyers).
Similarly, for each payment method in the token import file, a new payment method record will be created in your instance. Additionally, if a buyer is present the payment method will be linked to the created buyer.
The buyer's `external_identifier` field will retain the value you passed in the import file we will produce a unique internal ID field as a part of the import process.
## Merchant Advice File
Once all tokens, buyer, and payment methods were imported we will provide you with a **Merchant Advice File** ([example](https://gist.githubusercontent.com/phillipgr4vy/f9ca91d6d4163842bd52e5fb1a3858d9/raw/b37d10c95215be9cf07d4afa82004abcfea202c0/merchant_advice_file.csv))
which will log the successful and unsuccessful imports of all resources as part of this process.
* For each row attempted, a corresponding log item will be shown with an audit reference tag
* The ID for each created buyer record created will be outputted
* The ID for each created payment method created will be outputted
* A list of failures and validation errors will be outputted
# Vault token import
Source: https://docs.mattildapayments.com/guides/features/token-import/overview
A token import allows you to migrate your card data from your current payment provider into our vault.
We support both raw card data (PAN) as well as PSP token imports into our vault. To get this process started please contact our team to get started.
This guide will help you understand the basic principles of the token import process. This process may not be supported by all providers in which case
we will work with you to establish a custom process.
The token import process is comprised of the following steps and involves you (the merchant), your original payment service (the PSP), either of which
can be the **Token holder**.
* Token holder creates a token file using our file template and definitions.
* Token holder encrypts the token file created using our [public PGP encryption key](https://gr4vy.com/.well-known/security-pgp-key.asc).
* Token holder uploads the encrypted token file to a cloud-signed storage URL provided by us.
* We process and import all the tokens into your instance. Additionally, we will create new buyers and payment methods from the token import file.
* We will provide you with a **Merchant Advice file** that provides you with a log of all the succeeded and failed imports.
# Token import file upload
Source: https://docs.mattildapayments.com/guides/features/token-import/token-file-transmission
To successfully import your tokens, please encrypt the import file using our PGP public key and send it to the provided GCP signed URL.
## Encryption
Merchants **must** encrypt the token file before sending it to us. A suggested approach to encryption is using [GnuPG](https://www.gnupg.org) interface that can be used to encrypt files using PGP public keys.
Please refer to the GnuPG documentation to learn how to [add our public key to your keyring](https://www.gnupg.org/gph/en/manual/x56.html) and how
to [encrypt your token file](https://www.gnupg.org/gph/en/manual/x110.html) with our [key](https://gr4vy.com/.well-known/security-pgp-key.asc).
## File Transfer
When you request a token import we will provide you with a Google Cloud Storage signed URL. This will allow you to upload files to us directly via HTTPS.
Sending to this Google Cloud Storage signed URL can be accomplished in a variety of ways described in [this Google Cloud storage guide](https://cloud.google.com/storage/docs/uploading-objects).
For example, using cURL this request would look something like this.
```sh theme={"dark"}
curl -X PUT -H 'Content-Type: text/plain' --upload-file tokens.csv.gpg google_signed_cloud_storage_url
```
> [!NOTE]
>
> In this example, `google_signed_cloud_storage_url` is the URL we would have provided you, and `tokens.csv.gpg` is the name of the encrypted token file.
# Token import file creation
Source: https://docs.mattildapayments.com/guides/features/token-import/token-import-file
To allow for a smooth import, we have created a template that can be used for a generic token import from your current payment service to our system,
These templates: [card template](https://raw.githubusercontent.com/gr4vy/token-import-templates/main/token_import_template.csv) [non-card tokens](https://raw.githubusercontent.com/gr4vy/token-import-templates/main/token_import_template_non_card.csv) ([https://raw.githubusercontent.com/gr4vy/token-import-templates/main/token\_import\_template\_gift\_card.csv](https://raw.githubusercontent.com/gr4vy/token-import-templates/main/token_import_template_gift_card.csv)) can be downloaded and saved as a `.csv` file. Not all fields are required for minimum import,
but we recommend sending as many fields as are available. [This sample file](https://raw.githubusercontent.com/gr4vy/token-import-templates/main/token_import_sample.csv) provides an example of how this file can be populated.
> [!NOTE]
>
> Our import process will not modify your token file, if column data is not truncated the record will be treated as a failure.
### Column Definitions
| Column | Restrictions | Minimum Length | Maximum Length | Definition |
| - | - | - | - | - |
| `audit_reference_id` | Required, unique | | 200 | An ID for this row that we can use for logging and audit purposes. |
| `merchant_account_id` | | | 22 | The merchant account ID that resources should be created for. This defaults to `default`. |
| `buyer.external_identifier` | Required, unique | | 200 | An external identifier that can be used to match the buyer against your own records. This value needs to be unique for all buyers. See [Buyer creation](./buyer-payment-creation) for more details. Must be unique. |
| `buyer.display_name` | | | 200 | A unique name for this buyer which is used in the dashboard to give a buyer a human-readable name. |
| `buyer.billing_details.email_address` | | | 320 | The email address for the buyer. |
| `buyer.billing_details.first_name` | | | 255 | The first name(s) or given name for the buyer. |
| `buyer.billing_details.last_name` | | | 255 | The last name, or family name, of the buyer. |
| `buyer.billing_details.phone_number` | | | 320 | The phone number for the buyer should be formatted according to the [E164 number standard](https://www.twilio.com/docs/glossary/what-e164). |
| `buyer.billing_details.address.city` | | | 100 | The city for the address. |
| `buyer.billing_details.address.country` | | | 2 | The country for the address in ISO-3166 format. |
| `buyer.billing_details.address.line1` | | | 255 | The first line of the address. |
| `buyer.billing_details.address.line2` | | | 255 | The second line of the address. |
| `buyer.billing_details.address.postal_code` | | | 50 | The postal code or zip code for the address. |
| `buyer.billing_details.address.state` | | | 255 | The state, county, or province for the address. |
| `buyer.billing_details.address.state_code` | | | | The code of state, county, or province for the address in ISO 3166-2 format. |
| `buyer.billing_details.address.house_number_or_name` | | | 255 | The house number or name for the address. Not all payment services use this field but some do. |
| `buyer.billing_details.address.organization` | | | 255 | The optional name of the company or organization to add to the address. |
| `buyer.billing_details.tax_id.kind` | | | | The kind of tax ID. See [API Docs](https://docs.gr4vy.com/reference/buyers/new-buyer) for this field's accepted values. |
| `buyer.billing_details.tax_id.value ` | | | 50 | The tax ID for the buyer. |
| `payment_method.number` | Required (card) | 13 | 19 | The credit card number, without spaces or any other formatting. |
| `payment_method.expiration_date` | Required (card) | | | The credit card expiration date, formatted as a string in the `MM/YY` format. |
| `payment_method.scheme_transaction_id` | Recommended | | 100 | The latest scheme or network transaction ID for the card. This is required to enable subsequent MIT transactions for this card without requiring the buyer present. |
| `payment_method.external_identifier` | Required | | 200 | An external identifier that can be used to match the card against your own records. |
| `payment_method.token` | Required (non-card) | | | The non-card payment method's token. |
| `payment_method.payment_service_id` | Required (non-card). | | | The Gr4vy payment\_service\_id for the token. |
| `payment_method.method` | Required (non-card) | | | The non-card payment method's method. |
| `payment_method.label` | Ignored for card. | | | The label to display for non-card payment methods. |
| `payment_method.last_used_at` | | | | The timestamp in ISO-8601 format when this payment method was last used in a transaction. |
| `payment_method.cit_last_used_at` | | | | The timestamp in ISO-8601 format when this payment method was last used in a transaction for client initiated transactions. |
# Advanced authentication for Vault Forward
Source: https://docs.mattildapayments.com/guides/features/vault-forwarding/authentication
When using Vault Forward, the authentication to the downstream API is done by passing in the authorization header, you will need to pass your own API keys and credentials through the body
or headers. For example, when using a bearer token, it needs to be passed in the Vault Forward request as a `x-vault-forward-header-authorization` header.
```http theme={"dark"}
POST /vault-forward
host: api.acme.gr4vy.app
content-type: application/json
x-vault-forward-url: https://example.com/endpoint
x-vault-forward-http-method: PUT
x-vault-forward-header-authorization: Bearer 123
...
```
In some situations, passing through the authentication is not technically possible.
* The downstream service requires the request to be signed
* The downstream service requires two-way SSL / mutual TLS authentication
* The downstream service requires the entire payload to be encrypted
For these services, we have added support for advanced authentication.
## Setup
To set up advanced authentication, head over to the dashboard, switch to **Settings** -> **Manage merchants** then edit a merchant using the
actions menu, **...** -> **Edit merchant**. In a single merchant environment you may be able to go to this screen
directly via the **Settings** -> **Configuration** menu.
Next, switch to the **Vault Forwarding** tab and you should see the endpoints enabled for
your environment.

When an endpoints supports authentication, e.g. Visa, the actions menu should have an option to
edit the **Authentication methods**. Click on this menu, and it will take you to a new screen to set up
an authentication.
To set up an authentication method, click on the **Add authentication**, and select the method to add for that
endpoint. Fill in any of the required fields, and finally click the **Add** button.

Once set up, please note the UUID of each authentication method as you will need it in the next step.
> [!WARNING]
>
> **Validation:** We do not currently validate or verify the credentials provided. Please ensure the right values are passed, and no extra
> new lines, spaces, or other characters are filled in.
## Usage
To can make a Vault Forward request with an authentication method use the `x-vault-forward-authentications` header with a list
of one or more authentication methods UUIDs (comma separated) to use on that request. Each authentication method has it's unique UUID that
is displayed in the dashboard.
```http theme={"dark"}
POST /vault-forward
host: api.acme.gr4vy.app
content-type: application/json
x-vault-forward-url: https://example.com/endpoint
x-vault-forward-http-method: PUT
x-vault-forward-payment-methods: b77fef6d-c360-4b42-8f70-d884f4a6852a
x-valud-forward-authentications: 0a71cd3f-021e-4528-bcd7-38772594634b,2168f3c2-e327-47bd-9d5a-e9cfaeb53e96
{
"cards": [
{
"number": "{{ CARD_NUMBER_1 }}",
"expiry": "{{ CARD_EXPIRATION_DATE_1 }}",
"cvv": "123"
}
]
}
```
We will apply each authentication method to a request before we send it on to the target endpoint.
# Vault Forward card data from a checkout session
Source: https://docs.mattildapayments.com/guides/features/vault-forwarding/checkout-sessions
It is possible to use a Vault Forward directly with a checkout session and Secure Fields.
This is especially useful when you don't want to create a payment method, or when you want to collect
a CVV for a payment method.
## Forward CVV for a stored card
To forward a security code (CVV) for a stored card, create a checkout session and use it with Secure Fields to
collect the security code. More information on this can be found in our [Secure Fields guide on this topic](/guides/payments/secure-fields/stored-cards).
Once you've collected the security code, you can forward all the card details using the checkout session as described below.
## Forward a checkout session
To forward a checkout session, set the `x-vault-forward-checkout-session` instead of the `x-vault-forward-payment-methods` header.
```http Original request theme={"dark"}
POST /vault-forward
host: api.acme.gr4vy.app
content-type: application/json
x-vault-forward-url: https://example.com/endpoint
x-vault-forward-http-method: PUT
x-vault-forward-header-authorization: Bearer 123
x-vault-forward-checkout-session: b77fef6d-c360-4b42-8f70-d884f4a6852a
x-vault-forward-timeout: 10
{
"cards": [
{
"number": "{{ CARD_NUMBER_1 }}",
"expiry": "{{ CARD_EXPIRATION_DATE_1 }}",
"cvv": "{{ CARD_SECURITY_CODE_1 }}"
}
]
}
```
```http Forwarded request theme={"dark"}
PUT /endpoint
host: example.com
content-type: application/json
authorization: Bearer 123
{
"cards": [
{
"number": "4111111111111111",
"expiry": "12/25",
"cvv": "123"
}
]
}
```
> [!WARNING]
>
> Please note you can only ever provide one checkout session to vault forward.
# Enable a Vault Forward endpoint
Source: https://docs.mattildapayments.com/guides/features/vault-forwarding/enable
To use Vault forward the host name of the API you want to make an API request to needs to be
explicitly enabled in a production environment. There is a list of hosts to which we can forward
raw vaulted PCI data. To enable a host in an environment please put in a request with the support
team.
> [!NOTE]
>
> **Sandbox:** Vault forward supports any hostname in the sandbox environment and there's
> no need to explicitly enable an endpoint.
## Supported API endpoints
We currently support the following PCI endpoints in production. Additional API endpoints can be enabled on demand. Please contact our support team for next steps.
# Vault Forward card data to API endpoint
Source: https://docs.mattildapayments.com/guides/features/vault-forwarding/forward
Once an API endpoint has been [enabled](./enable) any vaulted data can be forwarded
to that endpoint using the Vault Forward API. To forward card data, you need to have some
card data stored in our vault. You can use any of our SDK, e-commerce plugins, and even our
API to store the card data in our Cloud Vault. Once stored, you can forward any stored card
(payment method) in our vault to your enabled API endpoint.
## Request
Vault Forward acts as a proxy to the API endpoint of your third-party service. You make the same request to
our API as you'd normally make to this endpoint with some minor changes.
1. Instead of sending the request to the endpoint, you send the data to our system.
2. In the body of the request, any PCI data is replaced with a template value, e.g. `{{ CARD_NUMBER_1 }}`.
3. Additional headers are required to specify for what cards to forward PCI data.
4. Any headers that need to be forwarded to the third-party endpoint will need to be changed to include the `x-vault-forward-header-` prefix.
5. The response, including the headers, will be returned to you for processing.
```http Original request theme={"dark"}
POST /vault-forward
host: api.acme.gr4vy.app
content-type: application/json
x-vault-forward-url: https://example.com/endpoint
x-vault-forward-http-method: PUT
x-vault-forward-header-authorization: Bearer 123
x-vault-forward-payment-methods: b77fef6d-c360-4b42-8f70-d884f4a6852a,1ca3fe71-7782-4f00-9b0e-c250b365bef1
x-vault-forward-timeout: 10
{
"cards": [
{
"number": "{{ CARD_NUMBER_1 }}",
"expiry": "{{ CARD_EXPIRATION_DATE_1 }}",
"cvv": "123"
},
{
"number": "{{ CARD_NUMBER_2 }}",
"expiry": "{{ CARD_EXPIRATION_DATE_2 }}",
"cvv": "234"
}
]
}
```
```http Forwarded request theme={"dark"}
PUT /endpoint
host: example.com
content-type: application/json
authorization: Bearer 123
{
"cards": [
{
"number": "4111111111111111",
"expiry": "12/25",
"cvv": "123"
},
{
"number": "4242424242424242",
"expiry": "03/26",
"cvv": "234"
}
]
}
```
### Headers
Vault Forward uses request headers to select the payment method to forward data for,
what endpoint to send the request to, and any additional other settings.
* `x-vault-forward-url` - the HTTPS URL to forward the request to. Its host must have been enabled if the request is in a production environment.
* `x-vault-forward-http-method` - the HTTP method to use when forwarding the request. The accepted values are `POST`, `PUT` and `PATCH`.
* `x-vault-forward-payment-methods` - a comma-separated list of IDs for **payment method**. At least 1 ID must be provided and they cannot be duplicates. Only card payment methods are accepted.
* `x-vault-forward-checkout-session` - the ID for a **checkout session**. At most 1 ID can be provided and if set `x-vault-forward-payment-methods` can be omitted. This can be used to [forward the security code of a card](./checkout-sessions).
* `x-vault-forward-header-{HEADER_NAME}` - each header value to forward in the request. For example, to forward an `authorization` header to the endpoints, it should be set as `x-vault-forward-header-authorization`.
* `x-vault-forward-timeout` (optional) - a timeout for the forwarded request. The default is 30 seconds.
### Payload
The request payload should contain the body which you want to forward to the third-party endpoint. It could be constructed in any format, for example JSON, or XML.
To forward vaulted data there are a set of placeholders that can be used as placeholders, using the `{{ PLACEHOLDER }}` syntax.
* `CARD_NUMBER_X`: The number for a card to forward.
* `CARD_EXPIRATION_DATE_X`: The expiration date for a card to forward.
* `CARD_EXPIRATION_DATE_M_X`: The expiration date's month as a non-zero-padded decimal number. Example: 1, 2, ..., 12.
* `CARD_EXPIRATION_DATE_MM_X`: The expiration date's month as zero-padded decimal number. Example: 01, 02, ..., 12.
* `CARD_EXPIRATION_DATE_YY_X`: The expiration date's year without century as a zero-padded decimal number. Example: 00, 01, ..., 99.
* `CARD_EXPIRATION_DATE_YYYY_X`: The expiration date's year with century as a decimal number. Example: 2013, 2014, ..., 9998, 9999.
* `CARD_SECURITY_CODE_X`: The security code for the card. This can only be forwarded when using [Secure Fields and checkout sessions](./checkout-sessions).
Note: The value `X` references the index of the payment method in the list of `x-vault-forward-payment-methods` (starting with 1)
## Authentication
To handle authentication to the downstream API, you will need to pass your own API keys and credentials through the body
or headers. For example, when using a bearer token, it needs to be passed in the Vault Forward request as a `x-vault-forward-header-authorization` header.
```http theme={"dark"}
POST /vault-forward
host: api.acme.gr4vy.app
content-type: application/json
x-vault-forward-url: https://example.com/endpoint
x-vault-forward-http-method: PUT
x-vault-forward-header-authorization: Bearer 123
...
```
In some situations, passing through the authentication is not technically possible.
* The downstream service requires the request to be signed
* The downstream service requires two-way SSL / mutual TLS authentication
* The downstream service requires the entire payload to be encrypted
For these services, we have added support for [advanced authentication](./authentication) to Vault Forward.
## Response
The response will contain the raw data received from the third-party endpoint and some additional information in the headers.
### HTTP status code
If there is some validation error before the request is sent to the third-party endpoint, the status code of
the `POST /vault-forward` API will be set to 4XX. In all other cases a `200` status will be returned
### Headers
When we receive a response from the third-party endpoint we will treat the headers in that response as follows.
* `content-type` - the content type of the response. This is transparently forwarded as received without any changes.
* `x-vault-forward-http-status-code` (optional) - the HTTP status code received from the third-party endpoint.
* `x-vault-forward-header-{HEADER_NAME}` - each header value received from the third-party endpoint, except for `content-type` which is returned as-is.
For example, if the API responded with `x-frame-options: SAMEORIGIN`, then our API will return a `x-vault-forward-header-x-frame-options: SAMEORIGIN` header.
* `x-vault-forward-error` (optional) - the error string of the request error. This is returned if we could not receive a response from the third party system, i.e. in case of a timeout or network error.
### Payload
The raw payload as received from the third party is returned as-is. Unless we did not receive a response from the third party, in
which case the payload will be empty.
### Example
```http Successful forward theme={"dark"}
HTTP 200
x-vault-forward-header-content-type: application/json
x-vault-forward-header-request-id: 123abc123abc
{
"status": "OK",
"transactionId": "123456789"
}
```
```json Invalid forward request theme={"dark"}
HTTP 400
{
"type": "error",
"code": "bad_request",
"status": 400,
"message": "Request failed validation",
"details": [
{
"type": "invalid",
"pointer": "x-vault-forward-http-method",
"message": "x-vault-forward-http-method is not a valid value (PUT/POST/PATCH)",
"location": "header"
}
]
}
```
```http Successful forward, error response theme={"dark"}
HTTP 200
x-vault-forward-http-status-code: 401
x-vault-forward-header-content-type: application/json
x-vault-forward-header-request-id: 123abc123abc
{
"status": "FAILURE",
"error": "Invalid authentication"
}
```
# Vault Forward
Source: https://docs.mattildapayments.com/guides/features/vault-forwarding/overview
Our platform offers the capability to forward stored information from the Cloud Vault
with third-party services. These external parties do not have to be directly integrated into
our platform but they do need to be PCI-compliant to receive raw payment data.
```http Original request theme={"dark"}
POST /vault-forward
host: api.example.gr4vy.app
content-type: application/json
x-vault-forward-url: https://example.com/endpoint
x-vault-forward-http-method: PUT
x-vault-forward-header-content-type: application/json
x-vault-forward-payment-methods: b77fef6d-c360-4b42-8f70-d884f4a6852a,1ca3fe71-7782-4f00-9b0e-c250b365bef1
x-vault-forward-timeout: 10
{
"cards": [
{
"number": "{{ CARD_NUMBER_1 }}",
"expiry": "{{ CARD_EXPIRATION_DATE_1 }}",
"cvv": "123"
},
{
"number": "{{ CARD_NUMBER_2 }}",
"expiry": "{{ CARD_EXPIRATION_DATE_2 }}",
"cvv": "234"
}
]
}
```
```http Forwarded request theme={"dark"}
PUT /endpoint
host: example.com
content-type: application/json
{
"cards": [
{
"number": "4111111111111111",
"expiry": "12/25",
"cvv": "123"
},
{
"number": "4242424242424242",
"expiry": "03/26",
"cvv": "234"
}
]
}
```
Typical examples would be external processing services, such as booking systems, reservation
systems, order management systems, or any other systems that need card details to fulfill a business process. Other examples include loyalty and rewards programs that need full card numbers for card-linked offers.
The Vault Forward service can be used to provide an API integration to any service that requires PCI card data, without putting the merchant in PCI scope.
To use Vault Forward please follow the next steps.
1. [Enable Vault](./enable) Forwarding for the API you want to connect to
2. [Add advanced authentication](./authentication) if the target API requires it
3. Use the [Vault Forward API](./forward) to send PCI data to the target API
# Advanced authentication for Visa
Source: https://docs.mattildapayments.com/guides/features/vault-forwarding/visa
## Prerequisites
Please ensure the Visa endpoints have been enabled for your instance by our support team.
## Setup
Once the Visa endpoint has been enabled, head over to the dashboard, switch to **Settings** -> **Manage merchants** then edit your merchant account
using the actions menu, **...** -> **Edit merchant**. In a single merchant environment you may be able to go to this screen
directly via the **Settings** -> **Configuration** menu.
Next, switch to the **Vault Forwarding** tab and you should see the Visa endpoint enabled for
your environment. In the actions menu should have an option to edit the **Authentication methods**.
Click on this menu, and it will take you to a new screen to set up
an authentication.
Visa has 2 authentication methods that can be set up: Message Level Encryption (MLE) and mutual TLS (mTLS).
### Mutual TLS (mTLS)
Mutual TLS ensures that all data between our system and Visa is encrypted at the TLS (SSL) level. This is generally a required authentication method for Visa endpoints
and will be the same for any merchant account.
To set up mTLS, head over to the **Visa Developer Center** and switch to your merchant account, **Credentials** and register a new certificate.
Once set up you should have a private key and 2 certificates. You can always redownload your certificate from the Visa dashboard by going to **Credentials** -> **Actions**.
-?> **Download Certificate**.
Similarly, you can download the DigiCert Global Root CA' certificate from the Visa dashboard as well. This root certificate may require conversion to the `pem` format.
```sh theme={"dark"}
openssl x509 -inform der -in Downloads/DigiCertGlobalRootCA.crt -outform pem -out DigiCertGlobalRootCA.pem
```
You can now upload this certificate (`cert`), private key (`cert_key`) and root certificate (`ca_cert`) via the dashboard by selecting the Mutual TLS
authentication method. Alternatively, you can use the [`POST /vault-forward/configs/{id}/authentications`](/reference/vault-forwarding/add-vault-forward-authentication) API as follows.
```json Request theme={"dark"}
{
"kind": "mtls",
"display_name": "mTLS",
"fields": [
{"key": "cert", "value": "{cert}"},
{"key": "cert_key", "value": "{cert_key}"},
{"key": "ca_cert", "value": "{ca_cert}"}
]
}
```
Note the created `id` of the authentication for later.
> [!WARNING]
>
> Please ensure keys and certificates are uploaded in a multiline format, without any extra spaces, new lines, or other characters.
### Message Level Encryption (MLE)
Message Level Encryption encrypts the payload sent to Visa, and this is generally recommended for most Visa endpoints
that send sensitive PCI data. This can be configured on a per merchant basis.
To set up MLE, create a new key via the **Visa Developer Center** -> **Merchant name** -> **Credentials** -> **Encryption/Decryption**. Note
the key ID and key value. You can then send this key (`key`) and key ID (`key_id`) via the dashboard by selecting the Message Level Encryption
authentication method. Alternatively, you can use the [`POST /vault-forward/configs/{id}/authentications`](/reference/vault-forwarding/add-vault-forward-authentication) API as follows.
```json Request theme={"dark"}
{
"kind": "mle",
"display_name": "MLE",
"fields": [
{"key": "key_id", "value": "{key_id}"},
{"key": "key", "value": "{key}"}
]
}
```
Note the created `id` of the authentication for later.
> [!WARNING]
>
> Please ensure keys are uploaded in a multiline format, without any extra spaces, new lines, or other characters.
## Usage
To connect to the Visa API, create an HTTP request with the following headers.
* `x-vault-forward-url`: `https://sandbox.api.visa.com/vop/v1/users/addcard` or the production equivalent
* `x-vault-forward-http-method: POST`
* `x-vault-forward-payment-methods`: the ID's for each of the payment methods to forward
* `x-vault-forward-header-content-type: application/json`
* `x-vault-forward-header-authorization:`
* Go to **Visa Developer Center** -> **Merchant name** -> **Credentials** -> **expand row**
* Generate [basic authentication header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#basic_authentication_scheme) with the given User ID and Password.
* `x-vault-forward-authentications`: the comma separated IDs of the mTLS and MLE authentication methods set up earlier
Then, make a `POST` request to [`/vault-forward`](/reference/vault-forwarding/make-vault-forward) as follows.
```json theme={"dark"}
{
"card": {
"expirationYear": "{{ CARD_EXPIRATION_DATE_YYYY_1 }}",
"cvv": "123",
"nameOnCard": "Test ABC",
"billingZipCode": "94354",
"expirationMonth": "{{ CARD_EXPIRATION_DATE_M_1 }}",
"cardNumber": "{{ CARD_NUMBER_1 }}"
},
"userKey": "9890124569",
"communityCode": "GAP"
}
```
We will automatically apply mutual TLS and merchant level encryption to the API request sent to Visa.
We will return the payload and headers received from Visa like any other forward request. It’s expected that the output is encrypted as merchants are expected to decrypt the response data themselves.
# Webhook events
Source: https://docs.mattildapayments.com/guides/features/webhooks/events
We currently send webhooks for the following events.
| Resource | Payload `name` | Description | |
| :- | :- | :- | - |
| Buyer | `buyer.created` | A buyer was created successfully. | |
| Buyer | `buyer.updated` | A buyer was updated successfully. This does not include it's shipping details, see `shipping-details.deleted`. | |
| Buyer | `buyer.deleted` | A buyer was deleted. | |
| Payment method | `payment-method.paused` | A stored payment method (e.g. card) was paused. | |
| Payment method | `payment-method.resumed` | A stored payment method (e.g. card) was resumed. | |
| Payment method | `payment-method.updated` | A stored payment method (e.g. card) was updated, likely due to an account update. | |
| Payment method | `payment-method.deleted` | A stored payment method (e.g. card) was deleted, likely due to an update from the payment service. | |
| Refund | `refund.declined` | A refund for a transaction was declined by the payment service. | |
| Refund | `refund.failed` | A refund for a transaction was otherwise rejected by the payment service. | |
| Refund | `refund.pending` | A refund for a transaction is pending. | |
| Refund | `refund.succeeded` | A refund for a transaction succeeded. | |
| Report execution | `report-execution.failed` | A report failed to generate. | |
| Report execution | `report-execution.succeeded` | A report was generated. | |
| Shipping details | `shipping-details.created` | A buyer successfully had it's shipping details added. | |
| Shipping details | `shipping-details.updated` | A buyer's shipping details were updated successfully. | |
| Shipping details | `shipping-details.deleted` | A buyer's shipping details were deleted. | |
| Transaction | `transaction.authenticated` | A transaction was successfully authenticated. | |
| Transaction | `transaction.authentication-pending` | A transaction is pending authentication. | |
| Transaction | `transaction.authorized` | A transaction is authorized (through 3DS or otherwise) but has not yet been authenticated. | |
| Transaction | `transaction.capture-failed` | An authorized transaction failed to capture. | |
| Transaction | `transaction.capture-pending` | An authorized transaction is pending capture. | |
| Transaction | `transaction.captured` | An authorized transaction was captured. | |
| Transaction | `transaction.declined` | A transaction was declined. | |
| Transaction | `transaction.failed` | A transaction failed due to an internal or external reason. Please check the `error_code` for the cause. | |
| Transaction | `transaction.review-accepted` | A transaction that was held in anti-fraud review has been accepted but it's status has not changed, only the `pending_review ` property has been set to `false`. | |
| Transaction | `transaction.void-declined` | An authorized transaction had it's request to void the authorization declined by the payment service. | |
| Transaction | `transaction.void-failed` | An authorized transaction had it's request to void the authorization otherwise rejected by the payment service. | |
| Transaction | `transaction.void-pending` | An authorized transaction has a pending void request. | |
| Transaction | `transaction.voided` | An authorized transaction has been voided. | |
> [!WARNING]
>
> We will be adding additional webhooks to cover all the remaining events in the
> payment lifecycle in a very near release.
# Webhooks
Source: https://docs.mattildapayments.com/guides/features/webhooks/overview
Webhooks allow you to receive notifications of events that occurred on our
platform. These notifications are delivered to an HTTPS endpoint
of your choice.
## Setup
We support multiple webhook URLs per instance. Webhooks can be configured
by administrators by heading to **Settings** -> **Integrations** ->
**Webhook subscriptions**. For each subscription, it's possible to listen to
the events for all merchant accounts in an instance, or to the events for one
merchant account.
## Legacy webhook subscriptions migration
Before the introduction of our **Webhook subscriptions** dashboard, webhook configuration was limited:
* One webhook per **merchant account**, configured in **Settings** → **Manage merchants**
* One hard-coded **instance-level** webhook, configurable via our support team
These legacy subscriptions will **remain active** for the time being. We are planning an automatic migration, but you can also migrate manually:
* **Merchant-level**: While this option has been removed from the dashboard, it may still be active via the API. To migrate, enable a new subscription in **Settings** → **Integrations** → **Webhook subscriptions**, then unset the legacy URL using the API or via support if needed.
* **Instance-level**: Contact support to have this migrated to the new system
## Webhook delivery behavior (legacy vs. new)
To avoid confusion during the migration period, here are key behaviors you should be aware of:
1. **Active legacy and new subscriptions will both receive events**\
As long as both are active and point to **different URLs**, each will receive webhook deliveries.
2. **No duplicate deliveries to the same URL**\
If both a legacy and a new subscription point to the **same URL**, our system includes **deduplication logic**, and only one delivery will go through. This prevents duplicate webhook events.
3. **Retries are subscription-specific**\
If a webhook delivery fails, it will only be retried for the subscription that encountered the failure — even if other subscriptions (pointing to the same or different URLs) succeed.
4. **Migration will eventually disable legacy subscriptions**\
Once automatic migration is complete, only the new subscription system will remain active.
## Supported features
* Multiple webhook subscriptions per merchant account
* Merchant account and instance-level webhook subscriptions
* Detailed [payloads](./payload) for transactions, payment methods, buyers, billing details, and most other transaction related events.
* Over 20 different webhook [events](./events).
* Basic authentication credentials (username/password)
* Automatic retries of undelivered events
* Webhook [signatures](./signatures) to verify authenticity.
## Upcoming features
* Event filtering per subscription
* Event log and replay capabilities
# Webhook payload
Source: https://docs.mattildapayments.com/guides/features/webhooks/payload
The payload for a webhook is a single event referencing a resource that has recently changed.
The data in `target` always represents a nested resource as returned by our regular [API endpoints](/reference).
```json Transaction theme={"dark"}
{
"type": "event",
"id": "347901e1-8b53-42a4-951b-ec546a5078f1",
"name": "transaction.captured",
"created_at": "2012-12-12T10:53:43+00:00",
"merchant_account_id": "mattilda",
"gr4vy_id": "mattilda",
"environment": "sandbox",
"target": {
"type": "transaction",
"id": "795c27e9d-6cc3-40f6-a359-1355c434c30d",
"status": "capture_succeeded",
"payment_method": {
"method": "card"
},
"external_identifier": "order-1234",
"amount": 1299,
"currency": "MXN",
"authorized_amount": 1299,
"captured_amount": 1299,
"refunded_amount": 0,
"payment_service_transaction_id": "8110000000002017185",
"payment_link_id": null,
"pending_review": false,
"error_code": null,
"metadata": {
"profile": "profile-1234"
},
"created_at": "2024-09-17T16:54:57.333316+00:00",
"updated_at": "2024-09-17T16:55:06.560721+00:00"
}
}
```
```json Buyer theme={"dark"}
{
"type": "event",
"name": "buyer.created",
"id": "d99a867a-a326-447f-b61e-2825ebe6f0c5",
"merchant_account_id": "mattilda",
"gr4vy_id": "mattilda",
"environment": "sandbox",
"created_at": "2024-11-20T16:50:52.609674+00:00",
"target": {
"type": "buyer",
"id": "f9d46f71-60d8-4b61-bddb-001a04c8224c",
"display_name": "John Smith",
"external_identifier": "user-123",
"created_at": "2024-11-20T16:50:52.603191+00:00",
"updated_at": "2024-11-20T16:50:52.603191+00:00",
"billing_details": {
"first_name": "John",
"last_name": "Smith",
"email_address": "john@example.com",
"phone_number": "+1234567890",
"address": {
"city": "Springfield",
"country": "US",
"postal_code": "123456",
"state": "CA",
"state_code": "US-CA",
"house_number_or_name": "21",
"line1": "22nd Street",
"line2": "",
"organization": "mattilda"
},
"tax_id": {
"value": "12-3456789",
"kind": "us.ein"
}
}
}
}
```
```json Payment method theme={"dark"}
{
"type": "event",
"id": "347901e1-8b53-42a4-951b-ec546a5078f1",
"name": "payment-method.updated",
"created_at": "2012-12-12T10:53:43+00:00",
"merchant_account_id": "mattilda",
"gr4vy_id": "mattilda",
"environment": "sandbox",
"target": {
"type": "payment-method",
"id": "8d29457b-683a-49c4-8afd-800cd7117236",
"status": "succeeded",
"method": "card",
"external_identifier": null,
"created_at": "2024-09-17T16:57:48.393644+00:00",
"updated_at": "2024-09-17T16:57:50.553736+00:00"
}
}
```
```json Refund theme={"dark"}
{
"type": "event",
"id": "347901e1-8b53-42a4-951b-ec546a5078f1",
"name": "refund.succeeded",
"created_at": "2012-12-12T10:53:43+00:00",
"merchant_account_id": "mattilda",
"gr4vy_id": "mattilda",
"environment": "sandbox",
"target": {
"type": "refund",
"id": "a994ec53-23b3-42e5-ab44-e4942d8aa7ba",
"transaction_id": "7ef82ff4-5862-4d2b-8bd0-4cbf86668fc5",
"payment_service_refund_id": "148206c4-fc32-44f3-906a-3d1b35865c19",
"amount": 1299,
"currency": "MXN",
"status": "succeeded",
"target_id": null,
"created_at": "2024-11-07T11:07:18.955537+00:00",
"updated_at": "2024-11-07T11:07:19.111351+00:00",
"transaction_external_identifier": "tx-123",
"external_identifier": "refund-234",
"target_type": "payment-method",
"reconciliation_id": "59zlCXgKuGfCz0wc8cTnOk",
"transaction_reconciliation_id": "3raSDUgac8qWle5IbcZiMP"
}
}
```
```json Report theme={"dark"}
{
"type": "event",
"id": "347901e1-8b53-42a4-951b-ec546a5078f1",
"name": "report-execution.succeeded",
"created_at": "2012-12-12T10:53:43+00:00",
"merchant_account_id": "mattilda",
"gr4vy_id": "mattilda",
"environment": "sandbox",
"target": {
"type": "report-execution",
"id": "8d29457b-683a-49c4-8afd-800cd7117236",
"status": "succeeded",
"report": {
"type": "report",
"id": "5b98970d-c6ee-48f1-a096-c5d37761f329"
},
"created_at": "2024-09-17T16:49:55.064633+00:00",
"updated_at": "2024-09-17T16:50:05.134346+00:00"
}
}
```
```json Shipping details theme={"dark"}
{
"type": "event",
"name": "shipping-details.created",
"id": "702863ee-fd78-467d-a0a7-533bf429b39c",
"created_at": "2024-11-20T12:48:38.409619+00:00",
"merchant_account_id": "mattilda",
"gr4vy_id": "mattilda",
"environment": "sandbox",
"target": {
"type": "shipping-details",
"id": "3dda8d7a-e7cd-43b8-9128-21adf1ec868b",
"buyer_id": "baa7b3b3-a4f1-49e3-afb0-0f41b48f5aa2",
"first_name": "John",
"last_name": "Smith",
"email_address": "john@example.com",
"phone_number": "+1234567890",
"address": {
"city": "Springfield",
"country": "MX",
"postal_code": "123456",
"state": "CA",
"state_code": "US-CA",
"house_number_or_name": "21",
"line1": "22nd Street",
"line2": "",
"organization": "mattilda"
},
"created_at": "2024-11-20T12:48:38.402474+00:00",
"updated_at": "2024-11-20T12:48:38.402474+00:00"
}
}
```
# Webhook signatures
Source: https://docs.mattildapayments.com/guides/features/webhooks/signatures
Webhook signatures let you verify that a webhook notification was sent by mattilda Pay and that its
content was not modified on the way to your endpoint. Verifying the signature protects you from
malicious parties sending forged or tampered data to your webhook endpoint.
> [!NOTE]
>
> The payload is **signed**, not encrypted. You don't need to decrypt anything: you recompute the
> same signature with your secret and compare it with the one we sent.
## Configuration
Signatures are computed with a **signing secret** shared between mattilda Pay and your merchant
account. Secrets start with `whsec_`.
To get a signing secret, contact the mattilda Pay support team. They will generate the secret for
your merchant account and share it with you through a secure channel. Once the secret is active,
every webhook we deliver to your endpoint includes the `X-Signature` header.
> [!WARNING]
>
> Store the secret in a secure place, such as a secrets manager or an environment variable. Never
> commit it to source control or expose it in client-side code.
## The `X-Signature` header
Each signed webhook is an HTTP `POST` with a JSON body (`Content-Type: application/json`) and the
following header.
```http theme={"dark"}
X-Signature: t=1751500000,v1=d51e200fd63385842a96fdcd5c8edcaef9cde70799841b1113380df92eb07f6c
```
| Element | Description |
| :- | :- |
| `t` | UNIX timestamp, in seconds (UTC), of the moment the webhook was signed. It is **not** an expiration time. |
| `v1` | Hex-encoded (lowercase) HMAC-SHA256 signature. During a [secret rotation](#secret-rotation) the header contains more than one `v1` entry, one per active secret. |
The signature is computed as follows.
```
v1 = hex( HMAC_SHA256( key = secret, message = t + "." + raw_body ) )
```
Where `raw_body` is the exact body of the HTTP request, byte for byte.
> [!NOTE]
>
> Every delivery attempt is signed again, so a retried webhook carries a new `t` value and a
> new `v1` signature.
## Signature verification
To verify a webhook, follow these steps.
1. Read the **raw body** of the request, before any JSON parsing.
2. Parse the `X-Signature` header: split it by `,`, then split each element by the first `=`.
Take the value of `t` and collect **all** the `v1` values in a list.
3. Build the signed content by joining the timestamp, a `.` character, and the raw body:
`{t}.{raw_body}`.
4. Compute the HMAC-SHA256 of the signed content using your secret as the key, and encode it
as lowercase hex.
5. Compare your value with each `v1` value using a constant-time comparison. The webhook is
valid if **at least one** of them matches.
6. Check that `t` is within your tolerance window (we recommend 5 minutes) to protect against
replay attacks.
> [!WARNING]
>
> Always verify the signature against the raw body you received. Don't parse the JSON and
> serialize it again: changes to whitespace, key order, or character escaping produce a
> different signature and the verification will fail.
### Code examples
```python Python theme={"dark"}
import hashlib
import hmac
import time
TOLERANCE_SECONDS = 300
def verify_signature(secret: str, raw_body: bytes, header: str) -> bool:
pairs = [item.split("=", 1) for item in header.strip().split(",")]
timestamp = int(next(value for key, value in pairs if key == "t"))
signatures = [value for key, value in pairs if key == "v1"]
if abs(time.time() - timestamp) > TOLERANCE_SECONDS:
return False
signed_content = f"{timestamp}.".encode("utf-8") + raw_body
expected = hmac.new(
secret.encode("utf-8"), signed_content, hashlib.sha256
).hexdigest()
return any(hmac.compare_digest(expected, sig) for sig in signatures)
# Flask example
# @app.post("/webhooks/mattilda")
# def webhook():
# if not verify_signature(SECRET, request.get_data(), request.headers.get("X-Signature", "")):
# abort(401)
# event = request.get_json()
# ...
# return "", 200
```
```javascript Node.js theme={"dark"}
const crypto = require("crypto");
const express = require("express");
const TOLERANCE_SECONDS = 300;
function verifySignature(secret, rawBody, header) {
const pairs = header.split(",").map((item) => {
const index = item.indexOf("=");
return [item.slice(0, index).trim(), item.slice(index + 1).trim()];
});
const timestamp = Number(pairs.find(([key]) => key === "t")?.[1]);
const signatures = pairs.filter(([key]) => key === "v1").map(([, value]) => value);
if (!timestamp || Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE_SECONDS) {
return false;
}
const expected = crypto
.createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest("hex");
return signatures.some(
(signature) =>
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))
);
}
const app = express();
// Use the raw body parser so the body is not re-serialized
app.post("/webhooks/mattilda", express.raw({ type: "application/json" }), (req, res) => {
if (!verifySignature(process.env.MATTILDA_WEBHOOK_SECRET, req.body, req.get("X-Signature") || "")) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body);
// ...
res.sendStatus(200);
});
```
```php PHP theme={"dark"}
'']);
if ($key === 't') {
$timestamp = (int) $value;
} elseif ($key === 'v1') {
$signatures[] = $value;
}
}
if ($timestamp === null || abs(time() - $timestamp) > TOLERANCE_SECONDS) {
return false;
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, $signature)) {
return true;
}
}
return false;
}
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
if (!verifySignature(getenv('MATTILDA_WEBHOOK_SECRET'), $rawBody, $header)) {
http_response_code(401);
exit;
}
$event = json_decode($rawBody, true);
// ...
http_response_code(200);
```
### Test values
Use these values to check your implementation. Disable the timestamp check (or set your clock
to `t`) while running this test.
| Input | Value |
| :- | :- |
| Secret | `whsec_selftest_secret` |
| Raw body | `{"name": "transaction.updated", "target": {"type": "transaction", "id": "abc"}}` |
| Header | `t=1751500000,v1=d51e200fd63385842a96fdcd5c8edcaef9cde70799841b1113380df92eb07f6c` |
The signature must match. Adding a single character to the body, or using a different secret,
must make the verification fail.
## Secret rotation
You can request a new signing secret from the mattilda Pay support team at any time, for example
if you suspect your secret was exposed.
During a rotation both the new and the previous secret are active for a grace period. While both
are active, every webhook is signed with each secret and the header contains one `v1` entry per
secret, the new one first:
```http theme={"dark"}
X-Signature: t=1751500000,v1=d51e200fd63385842a96fdcd5c8edcaef9cde70799841b1113380df92eb07f6c,v1=aa60557f8edaaf5dd86cf60cb84a4600ace124c9089e9d0e07b3ba97cab6d32f
```
Because your verification accepts the webhook when **any** `v1` matches, webhooks keep validating
with either secret. Update your endpoint to the new secret during the grace period, and let the
support team know so the previous secret can be retired.
> [!WARNING]
>
> Don't parse the header into a dictionary or map keyed by name. Repeated `v1` keys would
> overwrite each other and you would only keep one of the signatures.
## Best practices
* Respond with a `2XX` status code only after the signature is verified, and with a `4XX` status
code when it isn't.
* Use a constant-time comparison function (`hmac.compare_digest`, `crypto.timingSafeEqual`,
`hash_equals`) to compare signatures.
* Reject webhooks whose timestamp is outside your tolerance window.
* Process events idempotently: the same event can be delivered more than once, use the event
`id` to detect duplicates.
# Technical webhook considerations
Source: https://docs.mattildapayments.com/guides/features/webhooks/technical-considerations
## Endpoint URL
The webhook subscription endpoint URL configured to receive the webhooks should be a
HTTPS endpoint that supports TLS 1.2. Please ensure your Web Application Firewall (WAF)
does not block the webhook requests.
## Webhook logic
* Response time: The endpoint URL configured to receive the webhooks should return an HTTP response in the 200-299 range within 5000 milliseconds.
* Retry: We will attempt to send the webhook event if the merchant endpoint did not respond with a `2XX` in the allocated time or returned a non-2XX status code. We will attempt for up to 3 days. Due to the retry behavior, you might receive an event more than once if a timeout has occurred. You might also never receive an event if no successful delivery was possible in the 3-day window.
* Number of webhook endpoints: Currently we only support one webhook configured per environment. The production and sandbox environments both support a webhook endpoint.
* Delivery promise: We currently do not provide any guarantee as to the delivery time between an event occurring in our system and it being delivered via a webhook to the merchant.
## Acknowledging webhooks
When you receive a webhook event, you should always acknowledge its receipt, even if it contains additional information. To acknowledge a webhook we expect an HTTP response in the 200-299 range within 5000 milliseconds.
Any unacknowledged webhooks will be retried and might cause delay in further webhook delivery.
> [!WARNING]
>
> Please note that the content of a webhook event can change as we add more features. The addition of additional fields or enum values
> is not considered a backwards incompatible change. We recommend setting any JSON parser to ignore any unrecognised fields and values.
## Split authorization and capture
If a payment service supports delayed capture, we will always perform an authorization first even when the `intent` for a transaction is set to `capture`.
This allows us to perform various additional checks before proceeding with the capture. This also allows us the ability to hold a transaction in review.
As a consequence, this will sometimes result in multiple webhooks per transaction in case the first capture fails. In a normal situation, you would
only receive a `transaction.captured` event, but in case of a failure to capture we will automatically retry. In this situation you may
receive a `transaction.authenticated` webhook first, followed by a `transaction.captured` event.
This same order of events will happen when the `async_capture` property is set to `true` in the transaction request, as this will always handle
the capture asynchronously from the capture.
# Getting started with mattilda Pay
Source: https://docs.mattildapayments.com/guides/get-started
Grow your payment capabilities with code.
Welcome to our documentation! Let's get started using mattilda Pay,
today.
## Get started
> **[Embedded checkout](/guides/payments/embed/quick-start/overview)**
>
> Get set up with our hosted checkout experience and learn how to harness
> frontend orchestration.
> **[Card vaulting with Secure Fields](/guides/payments/secure-fields/quick-start/overview)**
>
> Make the most of our vault by using Secure Fields to capture card data into
> our PCI-compliant vault.
> **[Android and Google Pay](/guides/payments/android/quick-start/overview)**
>
> Start accepting cards, wallets, and Google Pay on Android.
> **[iOS and Apple Pay](/guides/payments/ios/quick-start/overview)**
>
> Start accepting cards, wallets, and Apple Pay on iOS devices.
> **[Integrate directly with our API](/guides/payments/direct-api/quick-start/overview)**
>
> Everything is driven by APIs allowing you to make a bespoke integration.
> **[Equip the right tools](/guides/tools)**
>
> Use our Postman and CLI tools to help explore our API in more detail.
## SDKs & Plugins
> **[iOS SDK](https://github.com/gr4vy/gr4vy-ios)**
>
> Get started on iOS and start accepting Apple Pay today.
> **[Android SDK](https://github.com/gr4vy/gr4vy-android)**
>
> Get started on Android and start accepting Google Pay today.
> **[React Native SDK](https://github.com/gr4vy/gr4vy-react-native)**
>
> Get started on Android and iOS with React Native.
> **[C# SDK](https://github.com/gr4vy/gr4vy-csharp)**
>
> Make server-side calls with our C# SDK.
> **[Go SDK](https://github.com/gr4vy/gr4vy-go)**
>
> Make server-side calls with our Go SDK.
> **[Java SDK](https://github.com/gr4vy/gr4vy-java)**
>
> Make server-side calls with our Java SDK.
> **[PHP SDK](https://github.com/gr4vy/gr4vy-php)**
>
> Make server-side calls with our PHP SDK.
> **[Python SDK](https://github.com/gr4vy/gr4vy-python)**
>
> Make server-side calls with our Python SDK.
> **[TypeScript SDK](https://github.com/gr4vy/gr4vy-typescript)**
>
> Make server and client-side API calls with our TypeScript SDK.
## Tools
> **[CLI](/guides/tools/cli)**
>
> Get started with our command line interface tool.
> **[Postman](/guides/tools/postman)**
>
> Start exploring our API using our official Postman collection.
## Deep dive
> **[Google Pay](/guides/features/google-pay/overview)**
>
> Discover the different ways to integrate Google Pay.
> **[Apple Pay](/guides/features/apple-pay/overview)**
>
> Discover the different ways to integrate Apple Pay.
> **[Universal 3-D Secure](/guides/features/3ds/overview)**
>
> Learn about our universal 3DS solution.
> **[API Reference](/reference)**
>
> Explore the full suite of API endpoints available.
# Android events
Source: https://docs.mattildapayments.com/guides/payments/android/events
The following events can be raised by the Android SDK.
`Gr4vyResult.TransactionCreated
`
Returns data about the transaction object when the transaction was
successfully created.
```json theme={"dark"}
{
"transactionID": "8724fd24-5489-4a5d-90fd-0604df7d3b83",
"status": "pending",
"paymentMethodID": "17d57b9a-408d-49b8-9a97-9db382593003"
}
```
`Gr4vyEvent.TransactionFailed`
Returned when the transaction encounters an error.
```json theme={"dark"}
{
"transactionID": "8724fd24-5489-4a5d-90fd-0604df7d3b83",
"status": "pending",
"paymentMethodID": "17d57b9a-408d-49b8-9a97-9db382593003"
}
```
`Gr4vyResult.Cancelled`
Returned when the user cancels/quits the SDK.
`Gr4vyResult.GeneralError`
Returned when the SDK encounters an error.
```json theme={"dark"}
{
"Gr4vy Error: Failed to load"
}
```
# Google Pay on Android
Source: https://docs.mattildapayments.com/guides/payments/android/google-pay
On Android, Google Pay can be easily integrated both with and without the SDK. In both offerings, we have removed
the need for you to sign up for a Google Developer account, reducing additional financial and maintenance costs.
| | [Using SDK][mobile] | [Without SDK][mobile-without] |
| - | - | - |
| Google Developer account required? | No | No |
| Customization & Theming? | Limited | Full |
| Integrated with Checkout Flow? | Yes | Optional |
> [!NOTE]
>
> \[Google Pay]\[google-pay] is also available on web.
[mobile]: /guides/features/google-pay/mobile
[mobile-without]: /guides/features/google-pay/mobile-without-sdk
[google-pay]: /guides/features/google-pay
# Android options
Source: https://docs.mattildapayments.com/guides/payments/android/options
The SDK can be configured in a few ways.
| Field | Optional / Required | Description |
| - | - | - |
| `gr4vyId` | **Required** | Should always be set to '"mattilda"'. The ID automatically sets the `apiHost` to `api.mattildapayments.com` for production and `api.sandbox.mattildapayments.com` and to `embed.sandbox.mattildapayments.com` for the sandbox environment. |
| `environment` | `Optional` | `"sandbox"`, `"production"`. Defaults to `"production"`. |
| `token` | **Required** | The server-side generated JWT token used to authenticate any of the API calls. |
| `amount` | **Required** | The amount to authorize or capture in the specified `currency` only. |
| `currency` | **Required** | A valid, active, 3-character `ISO 4217` currency code to authorize or capture the `amount` for. |
| `country` | **Required** | A valid `ISO 3166` country code. |
| `buyerId` | `Optional` | The buyer ID for this transaction. The transaction will automatically be associated with a buyer with that ID. |
| `buyerExternalIdentifier` | `Optional` | An optional external ID for a Gr4vy buyer. The transaction will automatically be associated with a buyer with that external ID. If no buyer with this external ID exists then it will be ignored. This option is ignored if the `buyerId` is provided. |
| `externalIdentifier` | `Optional` | An optional external identifier that can be supplied. This will automatically be associated with any resource created by mattilda Pay and can subsequently be used to find a resource by that ID. |
| `store` | `Optional` | `'ask'`, `'preselect'`, `true`, `false` - Explicitly store the payment method, ask the buyer or preselect it by default. Requires `buyerId` or `buyerExternalIdentifier`. |
| `display` | `Optional` | `all`, `addOnly`, `storedOnly`, `supportsTokenization` - Filters the payment methods to show stored methods only, new payment methods only or methods that support tokenization. |
| `intent` | `Optional` | `authorize`, `preferAuthorize`, `capture` - Defines the intent of this API call. This determines the desired initial state of the transaction. When used, `preferAuthorize` automatically switches to `capture` if the selected payment method doesn't support delayed capture. |
| `metadata` | `Optional` | An optional dictionary of keys and values for transaction metadata. All values should be a string. |
| `paymentSource` | `Optional` | `installment`, `recurring` - Can be used to signal that Embed is used to capture the first transaction for a subscription or an installment. When used, `store` is implied to be `true` and `display` is implied to be `supportsTokenization`. This means that payment options that do not support tokenization are automatically hidden. |
| `cartItems` | `Optional` | An optional array of cart item objects, each object must define a `name`, `quantity`, and `unitAmount`. |
| `theme` | `Optional` | Theme customization options. See [Theming](https://github.com/gr4vy/gr4vy-embed/tree/main/packages/embed#theming). The iOS SDK also contains an additional two properties within the `colors` object; `headerBackground` and `headerText`. These are used for the navigation background and foreground colors. |
| `locale` | `Optional` | An optional locale, consists of an `ISO 639 Language Code` followed by an optional `ISO 3166 Country Code`, e.g. `en`, `en-gb` or `pt-br`. |
| `requireSecurityCode` | `Optional` | An optional boolean that forces security code to be prompted for stored card payments. |
| `shippingDetailsId` | `Optional` | An optional unique identifier of a set of shipping details stored for the buyer. |
# Step 3: Install the Android SDK
Source: https://docs.mattildapayments.com/guides/payments/android/quick-start/android
Next, we can quickly embed the SDK in your Android app to
store card details, authorize payments, and capture a transaction.
## Add the SDK
The [Android SDK](https://github.com/gr4vy/gr4vy-android) is available as a Maven bundle
on [Jitpack](https://jitpack.io/#gr4vy/gr4vy-android). In Gradle,
this can be set up as follows.
```js theme={"dark"}
repositories {
mavenCentral()
maven { url "https://jitpack.io" }
}
dependencies {
implementation 'com.github.gr4vy:gr4vy-android:v1.4.0'
}
```
## Set up the app
Next, add the following meta information to your app's manifest.
```xml theme={"dark"}
```
> [!WARNING]
>
> Replace `[ID]` with the ID of your instance and
> `[ENVIRONMENT]` with either `sandbox` or `production`.
Additionally, ensure you have internet access added
to the permissions in your manifest.
```xml theme={"dark"}
```
## Prepare the SDK
Next, add the following to the top of your activity where
you want to enable the payment sheet.
```java theme={"dark"}
private lateinit var gr4vySDK: Gr4vySDK
```
Then, initialize the SDK within the `onCreate()` method of your activity.
```java theme={"dark"}
gr4vySDK = Gr4vySDK(activityResultRegistry, this, this)
```
Next, register the observer as follows.
```java theme={"dark"}
lifecycle.addObserver(gr4vySDK)
```
Finally, implement the `Gr4vyResultHandler` interface on the activity
and implement the required methods.
```java theme={"dark"}
class MainActivity : ComponentActivity(), Gr4vyResultHandler
```
# Step 1: Create an API key for use with Android
Source: https://docs.mattildapayments.com/guides/payments/android/quick-start/key
Before your application can communicate with the API you will need to
create a new API key. The API handles authentication using a signed **JSON
Web Token** (JWT) which is passed in an HTTP header.
```bash theme={"dark"}
curl -X GET https://api.mattildapayments.com/transactions \
-H "authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIi..."
```
> [!TIP]
>
> We recommend you use an SDK. Our SDKs makes the process of generating a token a lot easier and is probably
> available in your preferred programming language. We will get to this in the
> next step.
## Create a new API key
To use the API you will need to generate a new **API key**. Ask your Account Manager for an API key, which will come in a .pem file, in order to start with your integration.
> [!NOTE]
>
> Learn more about private keys, key-pairs, and JWT in our
> [in-depth guide on authentication](/guides/api/authentication).
## Summary
In this step you:
* Learned about API authentication.
* Created a new private key for the API.
* Stored this API key in a secure place where your application can access it.
# Android SDK
Source: https://docs.mattildapayments.com/guides/payments/android/quick-start/overview
Get set up with the Android SDK for your checkout experience.
In this quick start guide we will take you through the following steps.
1. [Create an API key](/guides/payments/android/quick-start/key) which is needed to generate
the signed JWT token in step 2.
2. [Set up a server-side SDK](/guides/payments/android/quick-start/sdks) to generate a client
token for authenticating to the API.
3. [Install the Android SDK](/guides/payments/android/quick-start/android) which will handle the
capture of the payment method details and process the payment.
4. [Process the transaction](/guides/payments/android/quick-start/transact) and inspect the result.
# Step 2: Generate a client token for use with Android
Source: https://docs.mattildapayments.com/guides/payments/android/quick-start/sdks
Before you add the SDK to your Android app you will need to create a client
token that can be used to authenticate the transaction.
## Loading token in Android
The token needs to be shared with your Android application over your own API.
We recommend you create a token per checkout and only use a token for a short
amount of time.
## Summary
In this step you:
* Created a signed JWT token using a server-side SDK.
* Shared the JWT with your Android application
# Step 4: Create a transaction
Source: https://docs.mattildapayments.com/guides/payments/android/quick-start/transact
With the SDK ready, it's time to create a transaction.
## Open the payment sheet
To open the payment sheet call the `.launch()` method on the SDK.
```java theme={"dark"}
gr4vySDK.launch(
context = this,
token = "[TOKEN]",
amount = 1299,
currency = "MXN",
country = "MX"
)
```
> [!WARNING]
>
> Replace the `[TOKEN]` with the JWT created in step 2. Additional
> [options](/guides/payments/android/options) can be provided when launching the SDK.
## Handle SDK events
The `Gr4vyResultHandler` requires you to handle the events emitted by the SDKs as follows.
```java theme={"dark"}
override fun onGr4vyResult(result: Gr4vyResult) {
when(result) {
is Gr4vyResult.GeneralError -> startActivity(Intent(this, FailureActivity::class.java))
is Gr4vyResult.TransactionCreated -> startActivity(Intent(this, SuccessActivity::class.java))
is Gr4vyResult.TransactionFailed -> startActivity(Intent(this, FailureActivity::class.java))
}
}
```
> [!NOTE]
>
> Learn more about the events triggered by the Android SDK in our [events](/guides/payments/android/events) guide.
# commercetools Administration
Source: https://docs.mattildapayments.com/guides/payments/commercetools/backend
## Payment information
Payment information can be found on the order details pages in the
commercetools Merchant Center by going to **Orders** -> **\[Select Order]**.
Information such as transaction ID, transaction status, and transaction amount,
currency etc. are available on the **Payments** tab.

## Capture a payment
An administrator can capture an authorized transaction by creating a new delivery for the order.
To do this, go to **Orders** -> **\[Select Order]** -> **Shipping & Delivery** -> and click
the **+ Add Delivery** button under **Deliveries**.
Select the items and quantities that will be delivered and then click
**Save** to capture the payment.

> [!NOTE]
>
> **Capture**
>
> Capture is not available if the **Payment Action** configuration is
> set to **Authorize and Capture**.
## Refund a payment
An administrator can refund a transaction by creating a new return for an order.
To do this, go to **Orders** -> **\[Select Order]** -> **Returns** -> and click the **+ Create return** button.
Select the items and quantities that will be returned and then click **Save** to refund the payment.

# commercetools Configuration
Source: https://docs.mattildapayments.com/guides/payments/commercetools/configuration
Within the commercetools Merchant Center you can access the integration configuration by
selecting **Gr4vy** in the side navigation. Within this menu there are three configuration sections.

## API Configuration
This section contains the basic setup of the plugin. You will need to fill in
the **Gr4vy ID**, **Private Key**, and **Environment** fields based on your environment.

## Options
This section allows you to further configure the behavior of the integration.

## Theme
Control of the theming of the Gr4vy Embed component used in storefront. See
[Embed theming](/guides/payments/embed/theming) for more details.

# commercetools Frontend
Source: https://docs.mattildapayments.com/guides/payments/commercetools/frontend
## Checkout page
Once the extension has been installed and configured, and Gr4vy Embed has been integrated into
your storefront, you should see the available payment methods listed on the checkout page.

## Customer account dashboard
Logged-in customers will see payment information within the order details
pages available in **My Orders** section of **My Account**.

# commercetools Installation
Source: https://docs.mattildapayments.com/guides/payments/commercetools/installation
## Before you start
It's recommended that you first install the commercetools integration in a development
commercetools environment which is an exact copy of your live store. After you have
verified everything is working properly in your development environment, you can
safely install the integration in your live environment.
### Integration Marketplace
The Gr4vy [commercetools integration](https://marketplace.commercetools.com/integration/gr4vy) is available for free
in the commercetools Integration Marketplace.
### Install the integration
The installation and setup of the Gr4vy commercetools integration requires several different modules.
* Merchant Center Custom App
* Extension Module
* Notification Module
* Setup Module
You will also need to integrate Gr4vy Embed with your storefront application. Example
code for how to integrate Gr4vy Embed with the default commercetools storefront is provided.
Documentation for installing and configuring each of the modules listed above is included
in the [GitHub repository](https://github.com/gr4vy/gr4vy-commercetools) for the integration.
# commercetools Integration
Source: https://docs.mattildapayments.com/guides/payments/commercetools/overview
Bring mattilda Pay Embed right into your commercetools ecommerce experience.
By using our [commercetools integration](https://marketplace.commercetools.com/integration/gr4vy)
you will be able to access the following features.
* A fully customizable unified checkout
* Unified dashboard across multiple processors
* Multi-currency support
* Buy Now Pay Later and local payment methods
* PCI Vault that maintains all customer's card details across multiple processors
* Universal 3-D Secure
* Authorization/Capture/Refund flows for ecommerce checkout
# Step 4: Handle redirect
Source: https://docs.mattildapayments.com/guides/payments/direct-api/quick-start/handle-redirect
Requests that require a redirect will return a `status` of `buyer_approval_pending` with a `payment_method.approval_url`. In this situation, it's required to redirect the buyer to this approval URL.
```json theme={"dark"}
{
"type": "transaction",
"id": "0c41c8df-27f4-480e-97f0-9401558ae25e",
"status": "buyer_approval_pending",
"payment_method": {
"type": "payment-method",
"method": "card",
"mode": "redirect",
"approval_url": "https://www.sandbox.mpay.com/checkoutnow?token=7NP38594266148058",
...
},
...
}
```
Approval may be needed for cards to facilitate 3-D Secure, and for non-cards to get the buyer to grant account payment authentication.
## Start the approval
Your application will need to redirect your customer to the `payment_method.approval_url`, where they will be required to authenticate the payment. The exact way of this authentication will depend on the payment method.
After they've authenticated themselves, the customer will be redirected back to the `redirect_url` that you set when creating the transaction.
> [!WARNING]
>
> If the customer abandons the checkout or somehow experiences network connection issues, the transaction state can get out of sync between your application and ours. We recommend [the following best practices](/guides/best-practice) in handling these situations.
## Handle the return to your app
When a customer is redirected back to your site, the transaction status is not known. Your application will therefore need to call our API to get the latest transaction status. We will show you how to do this in the next step. To do this, your `redirect_url` will be appended with the `transaction_id` and status of the transaction.
```
[redirect_url]?transaction_id=2f37e0d0-5549-42c4-9c5c-e03d5fa97148&transaction_status=capture_succeeded
```
> [!WARNING]
>
> Although we do provide the `transaction_status` in this callback, it's recommended to also fetch the latest status vai the API, as the status may have changed since.
After you've handled the redirect, you can display a message to your customer letting them know the result of the transaction.
## Summary
In this step you:
* Sent a customer to the approval URL
* Handled the customer returning to your redirect URL
# Step 1: Authentication
Source: https://docs.mattildapayments.com/guides/payments/direct-api/quick-start/key
The API uses **Bearer (Token) Authentication** to authenticate requests. The value of this bearer token is a **JSON Web Token** (JWT), which is passed in the `Authorization` HTTP header and signed by your private API Key.
```bash theme={"dark"}
curl -X GET https://api.mattildapayments.com/transactions \
-H "authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIi..."
```
## Create a new API key
To use the API you will need to generate a new **API key**. Head over to
your dashboard and visit the **Integrations** page.

On this page, click the **Add API key** button and select a name for your key. The name is purely for you to track what key is for what integration.
You will need to store the downloaded key securely as we will not store this key for you.
**Using an SDK**
Using an SDK is the most simple way to call and authenticate with our API. When using one of our SDKs to call the API, authentication is handled by the SDK client. You will
only need to initialize the SDK with your private to handle authentication.
**Without an SDK**
If you would like to call the API without using an SDK, you will need to generate the JWT token yourself and pass it as a bearer token in your API requests. You can generate a signed JWT token either using a helper function in an SDK or by manually generating and signing it.
Our [authentication guide](/guides/api/authentication) has details on using these options.
## Summary
In this step you:
* Learned about API authentication
* Created a new private key for the API
* Used an SDK to authenticate or manually created a token
# Direct API
Source: https://docs.mattildapayments.com/guides/payments/direct-api/quick-start/overview
Get set up with a direct API integration.
In some situations, using our [Web](/guides/payments/embed/quick-start/overview), [Android](/guides/payments/android/quick-start/overview), and [iOS](/guides/payments/ios) SDKs are not desirable. In these situations, you can directly integrate into our API to create a bespoke orchestration solution.
This integration is perfect for merchants who may want to integrate a wallet, or other alternative payment method
like SPEI directly via the API.
> [!WARNING]
>
> We recommend using [Secure Fields](/guides/payments/secure-fields) when working with cards as it reduces the PCI scope of your integration. If you intend to use our API directly for card payments without Secure Fields then you will have to go through your own PCI-DSS level 1 certification.
In this quick start guide, we will take you through the following steps.
1. [Authenticate](/guides/payments/direct-api/quick-start/key) by creating an API key and generating a signed JWT token.
2. [Get the payment options](/guides/payments/direct-api/quick-start/payment-options) to display at checkout via the API.
3. [Create a transaction](/guides/payments/direct-api/quick-start/transaction) with the payment method selected at checkout.
4. [Redirect the customer](/guides/payments/direct-api/quick-start/handle-redirect) to the payment service to complete the payment.
5. [Get the transaction result](/guides/payments/direct-api/quick-start/status) to determine the status of the payment.
# Step 2: Get a list of payment options
Source: https://docs.mattildapayments.com/guides/payments/direct-api/quick-start/payment-options
Next, you can use the payment options endpoint to determine which payment
options can be shown at checkout for the combination of `amount`, `currency`, `country`, `cart_items`
and `metadata` should be displayed in your checkout.
The [payment options API endpoint](/reference/payment-options/list-payment-options-with-post) makes it
easy to get a list of payment options.
```csharp C# theme={"dark"}
using Gr4vy;
using Gr4vy.Models.Components;
var sdk = new Gr4vySDK(
id: "mattilda",
server: SDKConfig.Server.Sandbox,
bearerAuthSource: Auth.WithToken(privateKey),
merchantAccountId: "example"
);
var res = await sdk.PaymentOptions.ListAsync(paymentOptionRequest: new PaymentOptionRequest() {});
// handle response
```
```go Go theme={"dark"}
package main
import(
"context"
gr4vygo "github.com/gr4vy/gr4vy-go"
"os"
"github.com/gr4vy/gr4vy-go/models/components"
"log"
)
func main() {
ctx := context.Background()
privateKey := "...."
withToken := gr4vy.WithToken(privateKey, []JWTScope{ReadAll, WriteAll}, 60)
s := gr4vy.New(
gr4vy.WithID("mattilda"),
gr4vy.WithServer(gr4vy.ServerSandbox),
gr4vy.WithSecuritySource(withToken),
gr4vy.WithMerchantAccountID("example"),
)
res, err := s.PaymentOptions.List(ctx, components.PaymentOptionRequest{})
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}
```
```java Java theme={"dark"}
package hello.world;
import java.lang.Exception;
import com.gr4vy.sdk.BearerSecuritySource;
import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.Gr4vy.AvailableServers;
import org.openapis.openapi.models.components.PaymentOptionRequest;
import org.openapis.openapi.models.errors.*;
import org.openapis.openapi.models.operations.ListPaymentOptionsResponse;
public class Application {
public static void main(String[] args) throws Exception {
Gr4vy sdk = Gr4vy.builder()
.id("mattilda")
.server(AvailableServers.SANDBOX)
.merchantAccountId("example")
.securitySource(new BearerSecuritySource.Builder(privateKey).build())
.build();
ListPaymentOptionsResponse res = sdk.paymentOptions().list()
.paymentOptionRequest(PaymentOptionRequest.builder()
.build())
.call();
if (res.paymentOptions().isPresent()) {
// handle response
}
}
}
```
```php PHP theme={"dark"}
declare(strict_types=1);
require 'vendor/autoload.php';
use Gr4vy;
use Gr4vy\Auth;
,
$privateKey = "...";
$sdk = Gr4vy\SDK::builder()
-\u003esetId('mattilda')
-\u003esetServer('sandbox')
-\u003esetSecuritySource(Auth::withToken($privateKey))
-\u003esetMerchantAccountId('example')
-\u003ebuild();
$paymentOptionRequest = new Gr4vy\PaymentOptionRequest();
$response = $sdk->paymentOptions->list(
paymentOptionRequest: $paymentOptionRequest
);
if ($response->paymentOptions !== null) {
// handle response
}
```
```python Python theme={"dark"}
from gr4vy import Gr4vy, auth
import os
with Gr4vy(
id="mattilda",
server="production",
merchant_account_id="example",
bearer_auth=auth.with_token(open("./private_key.pem").read())
) as g_client:
res = g_client.payment_options.list(locale="en")
# Handle response
print(res)
```
```ts TypeScript theme={"dark"}
import { Gr4vy } from "@gr4vy/sdk";
const gr4vy = new Gr4vy({
server: "sandbox",
id: "mattilda",
bearerAuth: withToken({
privateKey: fs.readFileSync("private_key.pem", "utf8"),
}),
});
async function run() {
const result = await gr4vy.paymentOptions.list({});
console.log(result);
}
run();
```
> [!NOTE]
>
> This API will automatically use your checkout Flow rules
> to limit these results.
Each payment option will include the `method`, `icon_url`, `label` and other useful information
on supported features that you can use to display the options on your checkout.
```bash Response theme={"dark"}
{
"items": [
{
"type": "payment-option",
"method": "card",
"icon_url": "https://api.sandbox.mattildapayments.com/assets/icons/payment-methods/card.svg",
"mode": "card",
"label": "Card",
"can_store_payment_method": true,
"can_delay_capture": true,
"context": {
"approval_ui": {
"height": "589px",
"width": "500px"
},
"required_fields": {}
}
},
{
"type": "payment-option",
"method": "alipay",
"icon_url": "https://api.sandbox.mattildapayments.com/assets/icons/payment-methods/alipay.svg",
"mode": "redirect",
"label": "Alipay",
"can_store_payment_method": true,
"can_delay_capture": false,
"context": {
"approval_ui": {
"height": "589px",
"width": "500px"
},
"required_fields": {}
}
}
]
}
```
> [!NOTE]
>
> This API supports an optional `locale` that can be set to get the `label` in your local language.
Your application can now display these payment options on your checkout page.
To display the available options and allow your customer to checkout, use each label and icon, and then handle
the transaction according to the next step.
> [!WARNING]
>
> We recommend using [Secure Fields](/guides/payments/secure-fields) when working with cards as it reduces the PCI scope of your integration. If you intend to use our API directly for card payments without Secure Fields then you will have to go through your own PCI-DSS level 1 certification.
By implementing the payment options in this way you can fully utilize payment orchestration
while having all the flexibility on the design and layout.
## Summary
In this step you:
* Called the payment options endpoint
* Displayed the payment options on your checkout
# Step 5: Get transaction result
Source: https://docs.mattildapayments.com/guides/payments/direct-api/quick-start/status
Finally, after the transaction has been created your application can get the
latest details and status using the transaction ID received via the callback to
the redirect URL, or on direct callback from the API.
## Get transaction details
This transaction ID can be used with the SDK to [fetch additional details about
the transaction](/reference/transactions/get-transaction). The transaction includes details about the payment method used and the status
of the transaction.
```json theme={"dark"}
{
"type": "transaction",
"id": "fe26475d-ec3e-4884-9553-f7356683f7f9",
"status": "authorized",
"amount": 1299,
"currency": "MXN",
"payment_method": {
"type": "payment-method",
"id": "77a76f7e-d2de-4bbc-ada9-d6a0015e6bd5",
"method": "card",
...
},
...
}
```
> [!NOTE]
>
> Visit the [API reference documentation](/reference) for full details about the
> transaction resource, and any other API.
# Step 3: Create a transaction
Source: https://docs.mattildapayments.com/guides/payments/direct-api/quick-start/transaction
After your buyer selects their method of payment in the previous step, you're ready to create a transaction.
## Create a Transaction
The transaction should be populated with the selected `method`, your `redirect_url`, and
any other relevant transaction information.
* `payment_method.method` - This will be the method selected by the customer at checkout. This will be one of the values retrieved from the payment options endpoint in the previous step.
* `payment_method.redirect_url` - This should be provided to redirect the buyer back to your application after they have authenticated the payment. This is also required for card in order to support 3-D Secure.
See the [`POST /transactions`](/reference/transactions/new-transaction) API endpoint for more details.
```csharp C# theme={"dark"}
var transaction = await _client.Transactions.CreateAsync(
transactionCreate: new TransactionCreate()
{
Amount = 1299,
Currency = "MXN",
Country = "MX",
PaymentMethod =
TransactionCreatePaymentMethod.CreateCheckoutSessionWithUrlPaymentMethodCreate(
new RedirectPaymentMethodCreate()
{
Method = "clearpay",
RedirectUrl = "https://example.com/callback",
}
),
}
);
```
```go Go theme={"dark"}
amount := int64(1299)
currency := "MXN"
method := "clearpay"
redirectUrl: "https://example.com/callback"
redirectPaymentMethodCreate := components.RedirectPaymentMethodCreate{
Method: method,
RedirectUrl: redirectUrl
}
paymentMethod := components.CreateTransactionCreatePaymentMethodRedirectPaymentMethodCreate(redirectPaymentMethodCreate)
transactionCreate := components.TransactionCreate{
Amount: amount,
Currency: currency,
PaymentMethod: &paymentMethod,
}
transaction, err := client.Transactions.Create(ctx, transactionCreate, nil, nil)
// handle response
```
```java Java theme={"dark"}
CreateTransactionResponse transactionResponse = gr4vyClient.transactions().create()
.transactionCreate(TransactionCreate.builder()
.amount(1299L)
.currency("MXN")
.paymentMethod(TransactionCreatePaymentMethod.of(RedirectPaymentMethodCreate.builder()
.method("clearpay")
.redirectUrl("https://example.com/callback")
.build()))
.build())
.call();
Transaction transaction = transactionResponse.transaction().orElse(null);
// handle response
```
```php PHP theme={"dark"}
$transactionCreate = new TransactionCreate(amount: 1299, currency: 'USD', paymentMethod: new RedirectPaymentMethodCreate(method: 'clearpay', redirectUrl: 'https://example.com/callback'));
$response = self::$sdk->transactions->create($transactionCreate);
$transaction = $response->transaction;
```
```python Python theme={"dark"}
transaction: models.Transaction = client.transactions.create(
amount=1299,
currency="MXN",
payment_method={
"method": "clearpay",
"redirect_url": "https://example.com/callback",
}
)
```
```ts TypeScript theme={"dark"}
const transaction = await gr4vy.transactions.create({
amount: 1299,
currency: "MXN",
paymentMethod: {
method: "clearpay",
redirectUrl: "https://example.com/callback"
}
})
```
The response of this transaction will include a `status`, which will tell you how to handle the
next step.
> [!WARNING]
>
> Requests that require a redirect will return a `status` of `buyer_approval_pending` with a `payment_method.approval_url`. In the next step we will show you how to handle this situation.
```json Response theme={"dark"}
{
"type": "transaction",
"id": "0c41c8df-27f4-480e-97f0-9401558ae25e",
"merchant_account_id": "mattilda",
"created_at": "2023-04-28T08:33:06.979938+00:00",
"updated_at": "2023-04-28T08:33:14.791510+00:00",
"amount": 1299,
"captured_amount": 0,
"refunded_amount": 0,
"currency": "MXN",
"country": "MX",
"external_identifier": null,
"status": "buyer_approval_pending",
"intent": "capture",
"payment_method": {
"type": "payment-method",
"method": "card",
"mode": "redirect",
"label": null,
"scheme": null,
"expiration_date": null,
"approval_url": "https://www.sandbox.mpay.com/checkoutnow?token=7NP38594266148058",
"country": "MX",
"currency": "MXN",
"details": null,
"id": null,
"approval_target": "any",
"external_identifier": null
},
"method": "card",
"error_code": null,
"payment_service": {
"id": "e9bd6ec4-03eb-410c-b655-45b458f185f2",
"type": "payment-service",
"payment_service_definition_id": "card",
"method": "card",
"display_name": "}card"
},
"buyer": null,
"raw_response_code": "CREATED",
"raw_response_description": "",
"shipping_details": null,
"avs_response_code": null,
"cvv_response_code": null,
"payment_source": "ecommerce",
"merchant_initiated": false,
"is_subsequent_payment": false,
"cart_items": [],
"scheme_transaction_id": null,
"three_d_secure": null,
"payment_service_transaction_id": "7NP38594266148058",
"metadata": null,
"authorized_at": null,
"captured_at": null,
"voided_at": null,
"buyer_approval_timedout_at": null
}
```
## Summary
In this step you:
* Called the transactions endpoint
* Handled the transaction response
# Common issues with Embed
Source: https://docs.mattildapayments.com/guides/payments/embed/common-issues
## Issue: "Must create a new `ApplePaySession` from a user gesture handler."
This JavaScript error is thrown by the Apple Pay SDK if there's an attempt to create a `ApplePaySession` outside of a user gesture handler.
This usually means there's too much time between the last user interaction, and the start of the Apple Pay session.
This is usually caused by some kind of slow task that is performed right after a user clicked a button to submit Embed and before the Apple Pay payment sheet opens. For example, you may try to make an
API call to your server to get the latest order ID, which can take hundreds of milliseconds. This delay between the last user action
and the start of the Apple Pay session causes Apple Pay to fail.
### Solution: Use `onBeforeTransaction`
To solve for this issue, move any slow actions into Embed's `onBeforeTransaction` callback. This function will run before the transaction is created, but after Apple Pay has been initialized.
Make sure to return a promise from inside the callback block. You will need to make it resolve or reject depending on your needs. If `reject` is called, a transaction will
not be created and the `transactionFailed` event will be broadcasted.
```js theme={"dark"}
onBeforeTransaction: () => {
return new Promise((resolve, reject) => {
fetch('https://example.com/someapi')
.then((response) => response.json())
.then((data) => {
resolve()
})
.catch((err) => {
reject()
})
});
},
```
#### Waiting for a server response before programmatically submitting Embed
In some cases, you might want to make a call to your server to fetch some information to include as part of the transaction,
when the user clicks your custom Pay button and before submitting with `embed.submit()`.
However, this can cause the issue described above, where Apple Pay fails because there's a delay between the last user interaction
(clicking the Pay button) and the start of the Apple Pay session (happening on `embed.submit()` once the call is complete).
Moving the call to `onBeforeTransaction` won't work in this case as that callback is executed after the Apple Pay session
has already been initialized.
It is currently not possible to update the information in the payment sheet once open.
This is a security measure of the Apple Pay SDK and there is no way to prevent this error from occurring in that scenario.
## Issue: "Page already has an active payment session."
This JavaScript error is thrown by the Apple Pay SDK if more than one `ApplePaySession` is used during the transaction.
This usually means Embed has been submitted more than once in quick succession, therefore multiple `ApplePaySession` are created and used in the transaction process.
Other reasons might include the session being expired (it expires after five minutes) or the session request not being sent from within Embed.
### Solution: Make sure Embed is not submitted twice too quickly
To solve the issue, make sure your integration doesn't cause Embed submitting multiple times too quickly.
* Check that your form or submit button handlers are not firing more than once
* If you're [submitting Embed without a form](/guides/payments/embed/quick-start/embed#submission-without-a-form), make sure not to pass the `form` option at the same time
# Digital wallets in Embed
Source: https://docs.mattildapayments.com/guides/payments/embed/digital-wallets
Embed supports both the Apple Pay and Google Pay wallets out of the box.
## Apple Pay
On the web, Apple Pay can be easily integrated both with and without Embed. In both offerings, we have removed
the need for you to sign up for an Apple Developer account, reducing additional financial and maintenance costs.
| | [Using SDK (Embed)][ap-web] | [Without SDK][ap-web-without] |
| - | - | - |
| Apple Developer account required? | No | No |
| Apple merchant account required? | No | No |
| Customization & Theming? | Limited | Full |
| Domain association required? | Yes | Yes |
| Integrated with Checkout Flow? | Yes | Optional |
> [!NOTE]
>
> \[Apple Pay]\[apple-pay] is also available on iOS.
## Google Pay
On the web, Google Pay can be easily integrated both with and without Embed. In both offerings, we have removed
the need for you to sign up for a Google Developer account, reducing additional financial and maintenance costs.
| | [Using SDK (Embed)][gp-web] | [Without SDK][gp-web-without] |
| - | - | - |
| Google Developer account required? | No | No |
| Customization & Theming? | Limited | Full |
| Integrated with Checkout Flow? | Yes | Optional |
> [!NOTE]
>
> \[Google Pay]\[google-pay] is also available on Android.
[gp-web]: /guides/features/google-pay/web
[gp-web-without]: /guides/features/google-pay/web-without-sdk
[google-pay]: /guides/features/google-pay/overview
[ap-web]: /guides/features/apple-pay/web
[ap-web-without]: /guides/features/apple-pay/web-without-sdk
[apple-pay]: /guides/features/apple-pay/overview
# Embed events
Source: https://docs.mattildapayments.com/guides/payments/embed/events
Embed accepts an `onEvent` parameter that can be used to listen to certain
events emitted from the form.
```js theme={"dark"}
setup({
element: '.container',
...,
onEvent: (name, data) => {
...
}
})
```
Embed emits the following events:
#### `argumentError`
Returned when the initial input (`element`, `options`) are incorrectly formatted or missing.
```json theme={"dark"}
{
"code": "argumentError",
"option": "currency",
"message": "must be a valid number"
}
```
#### `optionsLoaded`
Returned when options are loaded. Stored options include the `id`.
```json theme={"dark"}
[
{
"id": "...",
"method": "card",
"mode": "card"
},
{
"method": "card",
"mode": "card"
}
]
```
#### `formUpdate`
Returned when the form updates. Currently this only informs the developer if the form
is valid.
```json theme={"dark"}
{
"valid": false
}
```
#### `transactionCreated`
Returns a full transaction object when mattilda Pay accepted the transaction,
regardless of its status. Be aware that this can be a pending or declined
transaction. To track API failures please use the `transactionFailed` event.
```json theme={"dark"}
{
"type": "transaction",
"id": "8724fd24-5489-4a5d-90fd-0604df7d3b83",
"status": "pending",
...
}
```
#### `transactionCancelled`
Returned when a buyer has explicitly canceled a transaction, e.g. closing a popup or dismissing Apple Pay. This is currently not supported for 3-D Secure transactions
and should not be conflated with transaction being declined or an error occurring.
```json theme={"dark"}
{
"type": "transactionCancelled"
}
```
#### `transactionFailed`
Returned when an API call fails to create a transaction due to a client or
server error. In other words, this event is raised when incorrect data (like an
invalid JWT) is passed to the mattilda Pay API and a HTTP status code in the `4XX` or
`5XX` range is returned.
To catch failed or declined transactions due to
downstream issues with the payment service, please subscribe to the
`transactionCreated` event.
```json theme={"dark"}
{
"type": "error",
"code": "unauthorized",
"status": 401,
"message": "No valid API authentication found"
}
```
#### `apiError`
Returned when the form encounters an API error.
```json theme={"dark"}
{
"type": "error",
"code": "unauthorized",
"status": 401,
"message": "No valid API authentication found",
"details": []
}
```
# In-app browsers with Embed
Source: https://docs.mattildapayments.com/guides/payments/embed/in-app-browsers
Some of the most popular apps on mobile (and some on desktop) rely on in-app browsers to keep a user within the app while browsing third-party sites. Notable examples of these include Facebook, Instagram, and other Meta apps on mobile.
Although these in-app browsers mostly look like regular web browsers they have some irregular behavior when it comes to dealing with opening new tabs and windows, a feature that Embed relies on when dealing with alternative and local payment methods.
As a result of this irregular behavior the browser might not redirect to these payment services, or if a redirect does happen the original merchant checkout page may be lost. The consequence of this is that in some edge cases the transaction may complete successfully but your site would not be directly notified of this in the customer's browser. Additionally, the customer may be left with a browser window that does not close to reveal your checkout page.
## Integration
In addition to our general [best practice](/guides/best-practice) guidance, we recommend you add support for a return URL to handle in-app browsers, detailed below.
### Set a return URL to handle in-app browsers
To prevent the possibility for some customers using in-app browsers to be left without a direct link back to your site, we recommend setting the optional `fullPageReturnUrl`. When the `fullPageReturnUrl` is set as well as `redirectMode=fallback` then Embed will first attempt its normal redirect behavior and only if Embed detects a situation where the normal redirect cannot occur (for example when your customer is accessing your application from one of these in-app browsers) it will redirect the customer to your `fullPageReturnUrl`, appending it with the transaction ID and transaction status.
```
[fullPageReturnUrl]?transaction_id=2f37e0d0-5549-42c4-9c5c-e03d5fa97148&transaction_status=capture_succeeded
```
Your application should host a page at the `fullPageReturnUrl` that handles the resulting customer redirection for those edge cases.
If preferable, you can set the `redirectMode` to `fullPage` to always redirect to the `fullPageReturnUrl`. This can be very useful when testing your return URL integration.
Here is an example of how these properties can be set when configuring Embed.
```js theme={"dark"}
embed.setup({
fullPageReturnUrl: "https://example.com/checkout/callback"
// Setting the redirectMode to fullPage forces the uses of this return URL
redirectMode: "fullPage"
// The redirectMode defaults to "fallback" which will try to use a popup first before
// falling back to a full page redirect.
})
```
# Embed localization
Source: https://docs.mattildapayments.com/guides/payments/embed/locale
## Overview
Embed can be configured to use a different language using the `locale` property.
By default, this will be set to `en` (English). Embed accepts a
[ISO 639-1 Language Code](https://www.iso.org/iso-639-language-codes.html) (e.g.
`en` or `fr`) and an optional
[ISO 3166 Country Code](https://www.iso.org/iso-3166-country-codes.html) (e.g.
`AU` or `GB`). The country code allows us to provide a localized version of the
language based on a specific country, e.g. `fr-CA` would represent Canadian
French.
## Usage
The locale can be set to any of the [supported Locales](#locales). The
locale property will fall back to English if a locale is not provided, is
incorrect or not supported.
> [!WARNING]
>
> Embed currently does not automatically detect the buyer's locale. The locale
> will always be set to `en` when not provided.
```tsx React theme={"dark"}
```
```js CDN theme={"dark"}
setup({
...,
amount: 1299,
country='AU'
currency: "MXN",
locale: 'en-AU'
});
/>
```
## Locales
We currently support the following locales.
| Locale Name | Language Code (ISO 639-1) | Country Code (ISO 3166) | Locale |
| - | - | - | - |
| American English | `en` | `US` | `en-US` |
| British English | `en` | `GB` | `en-GB` |
| Brazilian Portuguese | `pt` | `BR` | `pt-BR` |
| Croatian | `hr` | | `hr` |
| Dutch | `nl` | | `nl` |
| French | `fr` | | `fr` |
| German | `de` | | `de` |
| Indonesian | `id` | | `id` |
| Italian | `it` | | `it` |
| Malay | `ms` | | `ms` |
| Portuguese | `pt` | | `pt` |
| Romanian | `ro` | | `ro` |
| Spanish | `es` | | `es` |
| Thai | `th` | | `th` |
# Embed options
Source: https://docs.mattildapayments.com/guides/payments/embed/options
Embed can be configured in a few ways.
### Setup with element & form
Embed expects the query for two HTML elements to attach itself to. The values
for these elements are a query string that can be parsed by
`document.querySelector`. For example, `` would be
represented as `.container`, while `
```
```html Node theme={"dark"}
```
```html CDN theme={"dark"}
```
> [!NOTE]
>
> The Node and CDN versions of Embed needs to be attached to an HTML element.
> In this case, we attached the UI to a `
` with the class `container`.
> The UI can be attached to any element using any `querySelector`-compatible query.
You should now see Embed loaded on the page. The available payment methods will
heavily depend on the enabled payment services in your account.
## Catch transaction ID
The Embed UI will handle the capture of any payment details and then creates a
transaction. Once the transaction has been created Embed will submit the form it
was attached to and append the query string parameters `transaction_id` and
`transaction_status`. Optionally, this form submission behavior can be
overridden using the [`onComplete`](/guides/payments/embed/options#options) option.
```js React theme={"dark"}
const Embed = require("@gr4vy/embed-react")
// or: import Embed from "@gr4vy/embed-react"
```
```html Node theme={"dark"}
```
```html CDN theme={"dark"}
```
> [!NOTE]
>
> **`form` vs `onComplete`**
>
> In this example, Embed uses the `onComplete` callback to catch the transaction ID when
> the transaction was created. When no `onComplete` is present it will submit the
> attached form and append `transaction_id` and
> `transaction_status` to the query string of the page that's being submitted to.
### Submission without a form
Embed does not require a form to be present, `submit` can be called directly. `onComplete` should be used if you are choosing this option. Additionally, the `form` option should not be passed in this scenario to avoid issues related to Embed being submitted twice in a row.
```js React theme={"dark"}
const { default: Embed, EmbedInstance } = require("@gr4vy/embed-react")
// or: import Embed, { EmbedInstance } from "@gr4vy/embed-react"
const embed = useRef();
```
```html Node theme={"dark"}
```
```html CDN theme={"dark"}
```
## Summary
In this step you:
* Installed and initialized Embed.
* Caught the resulting transaction identifier.
# Step 4: Inspect a transaction
Source: https://docs.mattildapayments.com/guides/payments/embed/quick-start/inspect
After the transaction has been created your application can get the
latest details and status using the transaction ID submitted in the form
or passed back in the `onComplete` callback.
## Get transaction details
This transaction ID can be used with the SDK to fetch additional details about
the transaction.
```csharp C# theme={"dark"}
using Gr4vy;
using Gr4vy.Models.Components;
var sdk = new Gr4vySDK(
merchantAccountId: "mattilda",
bearerAuth: ""
);
var res = await sdk.Transactions.GetAsync(transactionId: "7099948d-7286-47e4-aad8-b68f7eb44591");
// handle response
```
```go Go theme={"dark"}
package main
import(
"context"
gr4vygo "github.com/gr4vy/gr4vy-go"
"os"
"log"
)
func main() {
ctx := context.Background()
s := gr4vygo.New(
gr4vygo.WithMerchantAccountID("mattilda"),
gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
)
res, err := s.Transactions.Get(ctx, "7099948d-7286-47e4-aad8-b68f7eb44591")
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}
```
```java Java theme={"dark"}
package hello.world;
import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.GetTransactionResponse;
import java.lang.Exception;
public class Application {
public static void main(String[] args) throws Exception {
Gr4vy sdk = Gr4vy.builder()
.merchantAccountId("mattilda")
.bearerAuth("")
.build();
GetTransactionResponse res = sdk.transactions().get()
.transactionId("7099948d-7286-47e4-aad8-b68f7eb44591")
.call();
if (res.transaction().isPresent()) {
// handle response
}
}
}
```
```php PHP theme={"dark"}
declare(strict_types=1);
require 'vendor/autoload.php';
use Gr4vy;
$sdk = Gr4vy\SDK::builder()
->setMerchantAccountId('default')
->setSecurity(
''
)
->build();
$response = $sdk->transactions->get(
transactionId: '7099948d-7286-47e4-aad8-b68f7eb44591'
);
if ($response->transaction !== null) {
// handle response
}
```
```python Python theme={"dark"}
from gr4vy import Gr4vy
import os
with Gr4vy(
merchant_account_id="mattilda",
bearer_auth=os.getenv("GR4VY_BEARER_AUTH", ""),
) as g_client:
res = g_client.transactions.get(transaction_id="7099948d-7286-47e4-aad8-b68f7eb44591")
# Handle response
print(res)
```
The transaction includes details about the payment method used, and the status
of the transaction.
```json Response theme={"dark"}
{
"type": "transaction",
"id": "f7099948d-7286-47e4-aad8-b68f7eb44591",
"status": "authorized",
"amount": 1299,
"currency": "MXN",
"payment_method": {
"type": "payment-method",
"id": "77a76f7e-d2de-4bbc-ada9-d6a0015e6bd5",
"method": "card",
...
},
...
}
```
> [!NOTE]
>
> Visit the [API reference documentation](/reference) for full details about the
> transaction resource, and any other API.
# Step 1: Create an API key for use with Embed
Source: https://docs.mattildapayments.com/guides/payments/embed/quick-start/key
Before your application can communicate with the API you will need to
get a new API key. The API handles authentication using a signed **JSON
Web Token** (JWT) which is passed in a HTTP header.
```bash theme={"dark"}
curl -X GET https://api.mattildapayments.com/transactions \
-H "authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIi..."
```
> [!TIP]
>
> We recommend you use an SDK. Our SDKs makes the process of generating a token a lot easier and is probably
> available in your preferred programming language. We will get to this in the
> next step.
## Create a new API key
To use the API you will need to generate a new **API key**. Ask your Account Manager for an API key, which will come in a .pem file, in order to start with your integration.
## Summary
In this step you:
* Learned about API authentication.
* Created a new private key for the API.
* Stored this API key in a secure place where your application can access it.
# Step 5: Go live
Source: https://docs.mattildapayments.com/guides/payments/embed/quick-start/live
After testing your implementation in your sandbox environment, the next step
is to set up your production environment and go live.
1. Change the `environment` parameter to `production`.
2. Create a production API key
```html React theme={"dark"}
```
```js Node theme={"dark"}
setup({
gr4vyId: "mattilda",
environment: "production"
...
});
```
```js CDN theme={"dark"}
gr4vy.setup({
gr4vyId: "mattilda",
environment "production",
...
});
```
After completion, your transactions should appear in production environment.
## Summary
* Go live with Embed
# Embed
Source: https://docs.mattildapayments.com/guides/payments/embed/quick-start/overview
Get set up with Embed as your web checkout experience.
Embed is our hosted checkout experience that provides you with a payment
selector integrated right inside your checkout page. In this quick start
guide we will take you through the following steps.
1. [Create an API key](/guides/payments/embed/quick-start/key) which is needed to generate
the signed JWT token in step 2.
2. [Set up a server-side SDK](/guides/payments/embed/quick-start/sdks) to generate a client
token for authenticating to the API.
3. [Set up Embed](/guides/payments/embed/quick-start/embed) which will handle the
capture of the payment method details.
4. [Process the transaction](/guides/payments/embed/quick-start/inspect) and inspect the result.
5. [And finally prepare to go live](/guides/payments/embed/quick-start/live) by switching to production.
# Step 2: Generate a client token for use with Embed
Source: https://docs.mattildapayments.com/guides/payments/embed/quick-start/sdks
Before you add Embed to your web checkout you will need to create a client
token that can be used to authenticate the transaction.
## Summary
In this step you:
* Created a signed JWT token using a server-side SDK.
* Served the JWT token to your front-end application, where it will be used by
Embed.
# Embed Theming
Source: https://docs.mattildapayments.com/guides/payments/embed/theming
Embed can be customized to match your brand using the `theme` property. The
theme property allows you to set common styles such as the font, color and
border styles.
## Overview
Embed is a composition of UI components such as a *Payment Header*, *Content*
and *Lists*. These components can change over time and so we therefore do not
support direct styling of these. The following diagram shows an example of how
basic theming is applied. **Embed styles are derived from the theme values you
provide.**

## Usage
To apply a theme, embed can be passed an Object containing
[Theme Options](#options).
**The theme options will override the default theme**.
```js React theme={"dark"}
```
```js CDN theme={"dark"}
setup({
gr4vyId: "mattilda",
element: ".container",
amount: 1299,
country='AU'
currency: "MXN",
token: token,
theme: {
colors: {
primary: "green",
text: "black",
},
borderWidths: {
input: "thick",
},
radii: {
input: "none",
},
}
});
/>
```
## Options
### Fonts
Fonts can be customized with a valid CSS property.
```js theme={"dark"}
{
fonts: {
/**
* Body - Used for all text
*/
body: "google:Lato, Tahoma, Arial";
}
}
```
> [!TIP]
>
> **Using Google Fonts**
>
> Fonts prefixed with `google:` are downloaded automatically from
> [Google Fonts](https://fonts.google.com/). This allows you to choose the closest
> font to your brand. We recommend choosing a font with support for the weights
> `400`, `600` and `700`.
### Colors
Colors are named semantically, for example `primary` or `danger`. This allows us
to update introduce new features or UI elements without explicitly requiring you
to update your theme. As an example, we may introduce a 'Default Card' button at
a later stage that would be based on the `danger` set of colors.
```js theme={"dark"}
{
colors: {
/**
* Text - Main body text, labels and headers
*/
text: "#0f0f0f",
/**
* Subtle Text - Hints and Smaller text, e.g. Card Expiry
*/
subtleText: "#434343",
/**
* Label Text - Labels for inputs can be a different color
*/
labelText: "#0f0f0f",
/**
* Primary - Interactive elements or Brand
*/
primary: "#006cd0",
/**
* Page - The main body/page of the Embed iFrame
*/
pageBackground: "#ffffff",
/**
* Container - Used for bounding elements, e.g. an individual payment option
*/
containerBackgroundUnchecked: "#fcfcfc",
containerBackgroundHover: "#eeeeee",
containerBackground: "#ffffff",
containerBorder: "#f2f2f2",
/**
* Input - Used for inputs
*/
inputBorder: "#b6b6b6",
inputBackground: "#ffffff",
inputText: "#0f0f0f",
inputRadioBorder: "#ddd", // defaults to containerBorder
inputRadioBorderChecked: "#ddd", // default to primary
/**
* Danger - Used for Error states or Destructive Action
*/
danger: "#d82121",
dangerBackground: "#fbf7f7",
dangerText: "#b81010"
/**
* Info - Used for information / loading states
*/
info: "#3ea2ff",
infoBackground: "#e7f2fb",
infoText: "#0367c4",
/**
* Focus - Color of the focus ring if shadows.focus is not set.
*/
focus: "#4844ff",
/**
* Badge - Color of badge background.
*/
badgeBackground: "transparent",
}
}
```
### Borders Widths
Borders can be set using an alias of `thin` for a `1px` border width or `thick`
for a `2px` border width.
```js theme={"dark"}
{
borderWidths: {
/**
* Container - A bounding layout element
*/
container: 'thin', // 'thin', 'thick' or 'none'
/**
* Input - A Form Input, e.g. Card Number
*/
input: 'thin' // 'thin' or 'thick'
}
}
```
### Radii
Radii can be set to either `none`, `subtle` or `rounded`. These aliases
correspond to `0`, `2px` and `4px`. Setting the radii to `none` will remove it
entirely.
```js theme={"dark"}
{
radii: {
/**
* Container - A bounding layout element
*/
container: "subtle"; // 'subtle', 'rounded' or 'none'
/**
* Input - A Form Input, e.g. Card Number
*/
input: "subtle"; // 'subtle', 'rounded' or 'none'
}
}
```
### Focus Ring
The focus ring is set using a CSS `box-shadow` instead of the default browser
focus ring. It can be overridden, but we advise at least keeping a visible focus
ring for accessibility. This will override any focus styles set elsewhere in the
theme.
```js theme={"dark"}
{
shadows: {
/**
* Focus Ring - Surrounds an element that is currently focused
*/
focusRing: "0 0 0 2px #ffffff, 0 0 0 4px #4844ff";
}
}
```
## FAQ
> **How do I load my own CSS files?**
>
> We currently do not support adding your own styles directly via CSS. Using a
> theme allows us to roll out updates and ensure compatibility with new
> features.
> **What browsers are supported?**
>
> Theming is currently supported in all modern browsers including Microsoft
> Edge. Some browsers like Internet Explorer 11 are not supported, and in these
> the default theme will be used.
> **What values can be set?**
>
> Values can be a valid CSS property value. e.g. `colors.primary` could be a
> hex, RGB or HSL. You can also have multiple shadows for a focus ring, e.g. `0
> 0 0 2px white, 0 0 0 4px green`
# Apple Pay on iOS
Source: https://docs.mattildapayments.com/guides/payments/ios/apple-pay
On mobile apps, Apple Pay can be easily integrated both with and without our SDK. In both offerings, there will
be the need for you to sign up for an Apple Developer account and create your own Apple merchant ID and
processing certificate.
| | [Using SDK][mobile] | [Without SDK][mobile-without] |
| - | - | - |
| Apple Developer account required? | Yes | Yes |
| Apple merchant account required? | Yes | Yes |
| Customization & Theming? | Limited | Full |
| Domain association required? | No | No |
| Integrated with Checkout Flow? | Yes | Optional |
> [!NOTE]
>
> \[Apple Pay]\[apple-pay] is also available on the web.
[mobile]: /guides/features/apple-pay/ios
[mobile-without]: /guides/features/apple-pay/ios-without-sdk
[apple-pay]: /guides/features/apple-pay/overview
# iOS events
Source: https://docs.mattildapayments.com/guides/payments/ios/events
The following events can be raised by the iOS SDK.
`transactionCreated`
Returns data about the transaction object when the transaction was
successfully created.
```json theme={"dark"}
{
"transactionID": "8724fd24-5489-4a5d-90fd-0604df7d3b83",
"status": "pending",
"paymentMethodID": "17d57b9a-408d-49b8-9a97-9db382593003"
}
```
`transactionFailed`
Returned when the transaction encounters an error.
```json theme={"dark"}
{
"transactionID": "8724fd24-5489-4a5d-90fd-0604df7d3b83",
"status": "pending",
"paymentMethodID": "17d57b9a-408d-49b8-9a97-9db382593003"
}
```
When a network error occurs, the payload includes a `responseCode`.
```json theme={"dark"}
{
"transactionID": "",
"status": "",
"paymentMethodID": null,
"responseCode": "ETIMEDOUT",
}
```
Here's a list of potential values for `responseCode`:
| Code | Definition |
| - | - |
| `ERR_BAD_OPTION_VALUE` | Invalid or unsupported value provided in axios configuration. |
| `ERR_BAD_OPTION` | Invalid option provided in axios configuration. |
| `ECONNABORTED` | Request timed out due to exceeding timeout specified in axios configuration. |
| `ETIMEDOUT` | Request timed out due to exceeding default axios time limit. |
| `ERR_NETWORK` | Network-related issue. |
| `ERR_FR_TOO_MANY_REDIRECTS` | Request is redirected too many times; exceeds max redirects specified in axios configuration. |
| `ERR_DEPRECATED` | Deprecated feature or method used in axios. |
| `ERR_BAD_RESPONSE` | Response cannot be parsed properly or is in an unexpected format. |
| `ERR_BAD_REQUEST` | Requested has unexpected format or missing required parameters. |
| `ERR_CANCELED` | Feature or method is canceled explicitly by the user. |
| `ERR_NOT_SUPPORT` | Feature or method not supported in the current axios environment. |
| `ERR_INVALID_URL` | Invalid URL provided for axios request. |
`cancelled`
Returned when the user closes the payment sheet without creating a transaction.
`generalError`
Returned when the SDK encounters an error.
```json theme={"dark"}
{
"mattilda Pay Error: Failed to load"
}
```
# iOS options
Source: https://docs.mattildapayments.com/guides/payments/ios/options
The SDK can be configured in a few ways.
| Field | Optional / Required | Description |
| - | - | - |
| `gr4vyId` | **`Required`** | Should always be set to `mattilda`. |
| `token` | **`Required`** | The server-side generated JWT token which will be used to authenticate any of the API calls. |
| `environment` | `Optional` | `.sandbox`, `.production`. Defaults to `.production`. |
| `amount` | **`Required`** | The amount to authorize or capture in the specified `currency` only. |
| `currency` | **`Required`** | A valid, active, 3-character `ISO 4217` currency code to authorize or capture the `amount` for. |
| `country` | **`Required`** | A valid `ISO 3166` country code. |
| `buyerId` | `Optional` | An optional ID for a buyer. The transaction will automatically be associated with a buyer with that ID. If no buyer with this ID exists then it will be ignored. |
| `buyerExternalIdentifier` | `Optional` | An optional external ID for a Gr4vy buyer. The transaction will automatically be associated with a buyer with that external ID. If no buyer with this external ID exists then it will be ignored. This option is ignored if the `buyerId` is provided. |
| `presentingViewController` | **`Required`** | The view controller that opens the payment sheet. |
| `externalIdentifier` | `Optional` | An optional external identifier that can be supplied. This will automatically be associated with any resource that opens the payment sheet and subsequently used to find a resource by that ID. |
| `store` | `Optional` | `'ask'`, `'preselect'`, `true`, `false` - Explicitly store the payment method, ask the buyer or preselect it by default. Requires `buyerId` or `buyerExternalIdentifier`. |
| `display` | `Optional` | `all`, `addOnly`, `storedOnly`, `supportsTokenization` - Filters the payment methods to show stored methods only, new payment methods only or methods that support tokenization. |
| `intent` | `Optional` | `authorize`, `preferAuthorize`, `capture` - Defines the intent of this API call. This determines the desired initial state of the transaction. When used, `preferAuthorize` automatically switches to `capture` if the selected payment method doesn't support delayed capture. |
| `metadata` | `Optional` | An optional dictionary of keys and values for transaction metadata. All values should be a string. |
| `paymentSource` | `Optional` | `installment`, `recurring` - Can be used to signal that Embed is used to capture the first transaction for a subscription or an installment. When used, `store` is implied to be `true` and `display` is implied to be `supportsTokenization`. This means that payment options that do not support tokenization are automatically hidden. |
| `cartItems` | `Optional` | An optional array of cart item objects, each object must define a `name`, `quantity`, and `unitAmount`. |
| `applePayMerchantId` | `Optional` | The Apple merchant ID to be used during Apple Pay transactions. |
| `debugMode` | `Optional` | `true`, `false`. Defaults to `false`, this prints to the console. |
| `theme` | `Optional` | Theme customization options. See [Theming](https://github.com/gr4vy/gr4vy-embed/tree/main/packages/embed#theming). The iOS SDK also contains an additional two properties within the `colors` object; `headerBackground` and `headerText`. These are used for the navigation background and foreground colors. |
| `locale` | `Optional` | An optional locale, consists of an `ISO 639 Language Code` followed by an optional `ISO 3166 Country Code`, e.g. `en`, `en-gb` or `pt-br`. |
| `requireSecurityCode` | `Optional` | An optional boolean that forces security code to be prompted for stored card payments. |
| `shippingDetailsId` | `Optional` | An optional unique identifier of a set of shipping details stored for the buyer. |
| `merchantAccountId` | `Optional` | An optional merchant account ID. |
| `onEvent` | `Optional` | **Please see below for more details.** |
# Step 3: Install the iOS SDK
Source: https://docs.mattildapayments.com/guides/payments/ios/quick-start/ios
Next, we can embed the SDK in your iOS app to
store card details, authorize payments, and capture a transaction.
## Add the SDK
The [iOS SDK](https://github.com/gr4vy/gr4vy-ios) is available as a CocoaPods pod
and can be set up as follows.
```ruby Podfile theme={"dark"}
use_frameworks!
target 'TARGET_NAME' do
pod 'gr4vy-ios', '1.3.0'
end
```
> [!NOTE]
>
> Replace `TARGET_NAME` with your own build target. Please check [GitHub](https://github.com/gr4vy/gr4vy-ios) for
> the latest version of our SDK.
Then, in the `Podfile` directory type the following command.
```sh theme={"dark"}
pod install
```
On M1 Macs please add `arch -x86_64` to the command.
```sh theme={"dark"}
arch -x86_64 pod install
```
# Step 1: Create an API key for use with iOS
Source: https://docs.mattildapayments.com/guides/payments/ios/quick-start/key
Before your application can communicate with the API you will need to
create a new API key. The API handles authentication using a signed **JSON
Web Token** (JWT) which is passed in a HTTP header.
```bash theme={"dark"}
curl -X GET https://api.mattildapayments.com/transactions \
-H "authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIi..."
```
> [!TIP]
>
> We recommend you use an SDK. Our SDKs makes the process of generating a token a lot easier and is probably
> available in your preferred programming language. We will get to this in the
> next step.
## Create a new API key
To use the API you will need to generate a new **API key**. Head over to
your dashboard and visit the **Integrations** page.

On this page, click the **Add API key** button select a name for your key. The name is purely for you to track what key is for what integration.
You will need to store the downloaded key securely as we will not store this key for you.
> [!NOTE]
>
> Learn more about private keys, key-pairs, and JWT in our
> [in-depth guide on authentication](/guides/api/authentication).
## Summary
In this step you:
* Learned about API authentication.
* Created a new private key for the API.
* Stored this API key in a secure place where your application can access it.
# iOS SDK
Source: https://docs.mattildapayments.com/guides/payments/ios/quick-start/overview
Get set up with the iOS SDK for your checkout experience.
In this quick start guide, we will take you through the following steps.
1. [Create an API key](/guides/payments/ios/quick-start/key) which is needed to generate
the signed JWT token in step 2.
2. [Set up a server-side SDK](/guides/payments/ios/quick-start/sdks) to generate a client
token for authenticating to the API.
3. [Install the iOS SDK](/guides/payments/ios/quick-start/ios) which will handle the
capture of the payment method details and process the payment.
4. [Process the transaction](/guides/payments/ios/quick-start/transact) and inspect the result.
\`
# Step 2: Generate a client token for use with iOS
Source: https://docs.mattildapayments.com/guides/payments/ios/quick-start/sdks
Before you add the SDK to your iOS app you will need to create a client
token that can be used to authenticate the transaction.
## Loading token in iOS
The token needs to be shared with your iOS application via your own API.
We recommend you create a token per checkout and only use a token for a short
amount of time.
## Summary
In this step you:
* Created a signed JWT token using a server-side SDK.
* Shared the JWT with your iOS application
# Step 4: Create a transaction
Source: https://docs.mattildapayments.com/guides/payments/ios/quick-start/transact
With the SDK ready, it's time to create a transaction.
## Initialize the SDK
To initialize the SDK, call the `.init()` method on the SDK.
```swift theme={"dark"}
import gr4vy_ios
let result = Gr4vy.init(
gr4vyId: "mattilda",
token: "[TOKEN]",
amount: 1299,
currency: "MXN",
country: "MX",
buyerId: nil,
environment: Gr4vyEnvironment.sandbox
)
```
> [!NOTE]
>
> Replace the `[TOKEN]` with the JWT created in step 2.
> Additional [options](/guides/payments/ios/options) can be provided when launching the SDK.
## Launch & handle events
Next, it's time to open the payment sheet with the `.launch()` method. The launch method requires attaching an event handler
that listens for transactions that have been created or failed, as well as more generic errors.
```swift theme={"dark"}
result?.launch(presentingViewController: self, onEvent: { event in
switch event {
case .transactionFailed(let transactionID, let status, let paymentMethodID, let responseCode):
print("Handle a transaction failure, ID: \(transactionID), Status: \(status), PaymentMethodID: \(paymentMethodID ?? "Unknown"), ResponseCode: \(responseCode ?? "Unknown")")
case .transactionCreated(let transactionID, let status, let paymentMethodID):
print("Handle successful transaction, ID: \(transactionID), Status: \(status), PaymentMethodID: \(paymentMethodID ?? "Unknown")")
case .generalError(let error):
print("Error: \(error.description)")
}
})
```
When calling `.launch()` the `presentingViewController` is the current view controller this SDK is launched from.
The SDK will present the payment sheet on top of the current view controller, passing events back to the presenting view controller
via the `onEvent` callback.
> [!NOTE]
>
> Learn more about the events triggered by the iOS SDK in our [events](/guides/payments/ios/events) guide.
# Magento Administration
Source: https://docs.mattildapayments.com/guides/payments/magento/backend
## Payment information
Transaction information can be found in the order edit page in the
Magento admin by going to:
**Sales** -> **Orders** -> **\[Select Order]**
Information such as transaction id, transaction status, amount of transaction,
currency etc are presented in the **Payment Information** section:

## Capture payment online
The admin user can capture an Authorized transaction by creating a new invoice
for the order.
To do this, go to:
**Sales > Orders > \[Select Order]** and click the **Invoice link**
Select the **Capture Online** option under the **Amount** heading.
Finally, click the **\[Submit Invoice]** button to capture the payment.
> [!NOTE]
>
> **Capture Online**
>
> Capture Online is not available if the **Payment Action** configuration is
> set to **Authorize and Capture**

## Refund payment
To perform an online refund, go to the edit page of the invoice you want to
refund, via either of these routes:
**Sales > Invoices > \[Select Invoice]** and click on the **\[Credit Memo]**
button
**Sales > Orders > \[Select Order]**, click on the **Invoices** tab, **\[Select
Invoice]** and finally, click on the **\[Credit Memo]** button
On the refund page, there are two action buttons available:
1. **\[Refund Offline]** - This option won't trigger a refund transaction in
Gr4vy, only in Magento
2. **\[Refund]** - This option will instruct us to refund the captured
transaction amount to the customer's account

## Order comments history
Transaction information is appended to the order comments history section within
the order view page whenever a customer submits a transaction, or when an admin
user performs a payment capture or a transaction refund request.
There are four types of transactional information, see examples below:
1. Authorization message from Magento
2. Authorization message from Gr4vy, with transaction ID
3. Capture message from Gr4vy
4. Refund message from Gr4vy

# Magento Configuration
Source: https://docs.mattildapayments.com/guides/payments/magento/configuration
Within the Magento dashboard you can access the module configuration by
going to **Stores** -> **Settings** -> **Configuration** -> **Sales** ->
**Payment Methods** -> **Gr4vy**.

There are three configuration sections.
## **API Configuration**
This contains the basic set up. You will need to fill in
the `Gr4vy ID`, `Private Key`, and `Environment` fields based on your environment.

### API key
To use Magento you will need to generate a new **API key**. Head over to
your dashboard and visit the **Integrations** page.

On this page, click the **Add API key** button, and select a name for your key. The name is purely for you to
track what key is for what integration. You will need to upload the downloaded key
to Magento via the configuration panel.
When creating an API key for Magento we recommend restricting the permissions for this key to **Processing only**.
Additionally, in a Multi-Merchant environment, we recommend you restrict it to the targeted
merchant account only.
## Options
This allows you to further configure the behavior of the plugin.

## Theming
Control of the theming of the Embed plugin used in Magento. See
[Embed theming](/guides/payments/embed/theming) for more details.

## **Webhook Configuration**
The plugin supports handling incoming webhooks for asynchronous transaction status updates. To support webhooks you'll need to setup the Magento Plugin webhook URL `{{magento2_url}}/gr4vy/webhook/order`.
# Magento Frontend
Source: https://docs.mattildapayments.com/guides/payments/magento/frontend
## Checkout page
Once the module is installed and configured, you should see the mattilda Pay
payment method listed in the Payment Method section on the checkout page.

1. The description will change depending on the configuration value specified in
the admin
2. Card details the customer opted to save from previous transactions
3. Available payment options as configured in your merchant dashboard.
## Customer account dashboard
Logged in customers will see payment information within the order details
page.

# Magento Installation
Source: https://docs.mattildapayments.com/guides/payments/magento/installation
## Before you start
It's recommended that you first install the Magento module in a development
Magento environment which is an exact copy of your live store. After you have
verified everything is working properly in your development environment, you can
safely install the module in your live environment.
## Create a backup
Back up your Magento store database and files before installing the module.
You can do this via SSH or using the account dashboard of your hosting provider.
## Installation options
### Install the module via the marketplace
Our [Magento plugin](https://marketplace.magento.com/gr4vy-magento.html) is available for free
in the Magento Marketplace.
### Install the module with Composer
The module can be installed by running the command below in the Magento root
directory.
```sh theme={"dark"}
composer require gr4vy/magento
```
After installing with Composer, run the following commands in the Magento root directory
to complete the setup.
```sh theme={"dark"}
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush
php bin/magento setup:static-content:deploy
```
# Magento Plugin
Source: https://docs.mattildapayments.com/guides/payments/magento/overview
Bring Embed right into your Magento ecommerce experience.
By using our [Magento extension](https://marketplace.magento.com/gr4vy-magento.html)
you will be able to access the following features.
* A fully customizable unified checkout
* Unified dashboard across multiple processors
* Multi-currency support
* Buy Now Pay Later and local payment methods
* PCI Vault that maintains all customer's card details across multiple processors
* Universal 3-D Secure
* Authorization/Capture/Refund flows for ecommerce checkout
# Apple Pay on React Native
Source: https://docs.mattildapayments.com/guides/payments/react-native/apple-pay
On iOS, Apple Pay can be easily integrated both with and without our SDK. In both offerings, there will
be the need for you to sign up for an Apple Developer account and create your own Apple merchant ID and
processing certificate.
| | [Using SDK][mobile] | [Without SDK][mobile-without] |
| - | - | - |
| Apple Developer account required? | Yes | Yes |
| Apple merchant account required? | Yes | Yes |
| Customization & Theming? | Limited | Full |
| Domain association required? | No | No |
| Integrated with Checkout Flow? | Yes | Optional |
> [!NOTE]
>
> \[Apple Pay]\[apple-pay] is also available on the web.
[mobile]: /guides/features/apple-pay/ios
[mobile-without]: /guides/features/apple-pay/ios-without-sdk
[apple-pay]: /guides/features/apple-pay
# React Native events
Source: https://docs.mattildapayments.com/guides/payments/react-native/events
The library uses event emitters to send specific events happening in our SDK back to your React Native app.
The object `EmbedReactNativeEventEmitter` can be imported and used to listen to such events.
```js theme={"dark"}
import { EmbedReactNativeEventEmitter, Gr4vyEvent } from '@gr4vy/embed-react-native';
const onEvent = (event: Gr4vyEvent) => {
const { name, data } = event
console[name === 'generalError' ? 'error' : 'log'](name, data)
}
useEffect(() => {
const onEventSubscription = EmbedReactNativeEventEmitter.addListener(
'onEvent',
onEvent
)
return () => {
onEventSubscription.remove()
}
}, [])
```
## Available events.
`transactionCreated`
Returns data about the transaction object when the transaction was
successfully created.
```json theme={"dark"}
{
"name": "transactionCreated",
"data": {
"success": true,
"transactionId": "8724fd24-5489-4a5d-90fd-0604df7d3b83",
"status": "capture_succeeded",
"paymentMethodId": "17d57b9a-408d-49b8-9a97-9db382593003",
"approvalUrl": "https://example.com"
}
}
```
`transactionFailed`
Returned when the transaction encounters an error.
```json theme={"dark"}
{
"name": "transactionFailed",
"data": {
"success": false,
"transactionId": "8724fd24-5489-4a5d-90fd-0604df7d3b83",
"status": "authorization_failed",
"paymentMethodId": "17d57b9a-408d-49b8-9a97-9db382593003"
}
}
```
`generalError`
Returned when the SDK encounters an error.
```json theme={"dark"}
{
"name": "generalError",
"data": {
"message": "Gr4vy Error: Failed to load"
}
}
```
`cancelled`
Returned when the SDK gets closed.
```json theme={"dark"}
{
"name": "cancelled",
"data": {
"message": "User cancelled"
}
}
```
# Google Pay on React Native
Source: https://docs.mattildapayments.com/guides/payments/react-native/google-pay
On Android, Google Pay can be easily integrated both with and without the SDK. In both offerings, we have removed
the need for you to sign up for a Google Developer account, reducing additional financial and maintenance costs.
| | [Using SDK][mobile] | [Without SDK][mobile-without] |
| - | - | - |
| Google Developer account required? | No | No |
| Customization & Theming? | Limited | Full |
| Integrated with Checkout Flow? | Yes | Optional |
> [!NOTE]
>
> \[Google Pay]\[google-pay] is also available on web.
[mobile]: /guides/features/google-pay/mobile
[mobile-without]: /guides/features/google-pay/mobile-without-sdk
[google-pay]: /guides/features/google-pay
# React Native options
Source: https://docs.mattildapayments.com/guides/payments/react-native/options
The SDK can be configured in a few ways.
| Field | Optional / Required | Description |
| - | - | - |
| `gr4vyId` | **`Required`** | Should always be set to `mattilda`. |
| `token` | **`Required`** | The server-side generated JWT token which will be used to authenticate any of the API calls. |
| `environment` | `Optional` | `.sandbox`, `.production`. Defaults to `.production`. |
| `amount` | **`Required`** | The amount to authorize or capture in the specified `currency` only. |
| `currency` | **`Required`** | A valid, active, 3-character `ISO 4217` currency code to authorize or capture the `amount` for. |
| `country` | **`Required`** | A valid `ISO 3166` country code. |
| `buyerId` | `Optional` | An optional ID for a buyer. The transaction will automatically be associated with a buyer with that ID. If no buyer with this ID exists then it will be ignored. |
| `buyerExternalIdentifier` | `Optional` | An optional external ID for a buyer. The transaction will automatically be associated to a buyer with that external ID. If no buyer with this external ID exists then it will be ignored. This option is ignored if the `buyerId` is provided. |
| `presentingViewController` | **`Required`** | The view controller that opens the payment sheet. |
| `externalIdentifier` | `Optional` | An optional external identifier that can be supplied. This will automatically be associated to any resource that opens the payment sheet and subsequently used to find a resource by that ID. |
| `store` | `Optional` | `'ask'`, `'preselect'`, `true`, `false` - Explicitly store the payment method, ask the buyer or preselect it by default. Requires `buyerId` or `buyerExternalIdentifier`. |
| `display` | `Optional` | `all`, `addOnly`, `storedOnly`, `supportsTokenization` - Filters the payment methods to show stored methods only, new payment methods only or methods that support tokenization. |
| `intent` | `Optional` | `authorize`, `preferAuthorize`, `capture` - Defines the intent of this API call. This determines the desired initial state of the transaction. When used, `preferAuthorize` automatically switches to `capture` if the selected payment method doesn't support delayed capture. |
| `metadata` | `Optional` | An optional dictionary of keys and values for transaction metadata. All values should be a string. |
| `paymentSource` | `Optional` | `installment`, `recurring` - Can be used to signal that Embed is used to capture the first transaction for a subscription or an installment. When used, `store` is implied to be `true` and `display` is implied to be `supportsTokenization`. This means that payment options that do not support tokenization are automatically hidden. |
| `cartItems` | `Optional` | An optional array of cart item objects, each object must define a `name`, `quantity`, and `unitAmount`. Other optional properties are `discountAmount`, `taxAmount`, `externalIdentifier`, `sku`, `productUrl`, `imageUrl`, `categories` and `productType`. |
| `applePayMerchantId` | `Optional` | The Apple merchant ID to be used during Apple Pay transactions. |
| `debugMode` | `Optional` | `true`, `false`. Defaults to `false`, this prints to the console. |
| `theme` | `Optional` | Theme customization options [See Theming Options](/guides/payments/embed/theming#theme-options). The SDK also contains an additional two properties within the `colors` object: `headerBackground` and `headerText`. These are used for the navigation background and foreground colors. |
| `locale` | `Optional` | An optional locale, this consists of a `ISO 639 Language Code` followed by an optional `ISO 3166 Country Code`, e.g. `en`, `en-gb` or `pt-br`. |
| `requireSecurityCode` | `Optional` | An optional boolean which forces security code to be prompted for stored card payments. |
| `shippingDetailsId` | `Optional` | An optional unique identifier of a set of shipping details stored for the buyer. |
| `merchantAccountId` | `Optional` | An optional merchant account ID. |
| `connectionOptions` | `Optional` | An optional set of values passed to a connection when processing a transaction (see [New transaction](/reference/transactions/new-transaction)) |
# Step 3: Install the React Native SDK
Source: https://docs.mattildapayments.com/guides/payments/react-native/quick-start/embed
Next, we can embed the SDK in your React Native app to
store card details, authorize payments, and capture a transaction.
## Add the SDK
The [React Native SDK](https://github.com/gr4vy/gr4vy-react-native) is available as an NPM package.
```sh theme={"dark"}
yarn add @gr4vy/embed-react-native
# OR
npm install @gr4vy/embed-react-native
```
This will install the SDK, as well as the native iOS and Android dependencies.
# Step 1: Create an API key for use with React Native
Source: https://docs.mattildapayments.com/guides/payments/react-native/quick-start/key
Before your application can communicate with the API you will need to
create a new API key. The API handles authentication using a signed **JSON
Web Token** (JWT) which is passed in an HTTP header.
```bash theme={"dark"}
curl -X GET https://api.mattildapayments.com/transactions \
-H "authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIi..."
```
> [!TIP]
>
> We recommend you use an SDK. Our SDKs make the process of generating a token a lot easier and
> is available in many popular programming languages. We will get to this in the
> next step.
## Create a new API key
To use the API you will need to generate a new **API key**. Head over to
your dashboard and visit the **Integrations** page.

On this page, click the **Add API key** button and select a name for your key. The name is purely for you to track what key is for what integration.
You will need to store the downloaded key securely as we will not store this key for you.
> [!NOTE]
>
> Learn more about API keys and JWTs in our
> [in-depth guide on authentication](/guides/api/authentication).
## Summary
In this step you:
* Learned about API authentication.
* Created a new API key for use with the API.
* Stored this API key in a secure place where your application can access it.
# React Native SDK
Source: https://docs.mattildapayments.com/guides/payments/react-native/quick-start/overview
Get set up with the React Native mobile SDK for your checkout experience.
In this quick start guide, we will take you through the following steps.
1. [Create an API key](/guides/payments/react-native/quick-start/key) which is needed to generate
the signed JWT token in step 2.
2. [Set up a server-side SDK](/guides/payments/react-native/quick-start/sdks) to generate a client
token for authenticating to the API.
3. [Install the React Native SDK](/guides/payments/react-native/quick-start/embed) which will handle the
capture of the payment method details and process the payment.
4. [Process the transaction](/guides/payments/react-native/quick-start/transact) and inspect the result.
\`
# Step 2: Generate a client token for use with React Native
Source: https://docs.mattildapayments.com/guides/payments/react-native/quick-start/sdks
Before you add the SDK to your React Native app you will need to create a client
token that can be used to authenticate the transaction.
## Loading token in React Native
The token needs to be shared with your React Native application via your own API.
We recommend you create a token per checkout and only use a token for a short
amount of time.
## Summary
In this step you:
* Created a signed JWT token using a server-side SDK.
* Shared the JWT with your React Native application
# Step 4: Create a transaction
Source: https://docs.mattildapayments.com/guides/payments/react-native/quick-start/transact
With the SDK installed, it's time to create a transaction.
## Initialize the SDK
To initialize the SDK, call the `.showPaymentSheet()` method on the SDK to open the payment sheet
to prompt the buyer to pay.
```js theme={"dark"}
import EmbedReactNative from '@gr4vy/embed-react-native';
const handleCheckout = () => {
EmbedReactNative.showPaymentSheet({
gr4vyId: 'mattilda',
environment: 'sandbox',
token: '[TOKEN]',
amount: 1299,
currency: 'AUD',
country: 'AU',
...
})
}
```
> [!NOTE]
>
> Replace the `[TOKEN]` with the JWT created in step 2.
> Additional [options](/guides/payments/react-native/options) can be provided when launching the SDK.
## Handle events
Once launched, the SDK will send events when a transaction was created and for some failures.
To handle these events, add a new event listener to the SDK.
```js theme={"dark"}
import { EmbedReactNativeEventEmitter, Gr4vyEvent } from '@gr4vy/embed-react-native';
const onEvent = (event: Gr4vyEvent) => {
const { name, data } = event
console[name === 'generalError' ? 'error' : 'log'](name, data)
}
useEffect(() => {
const onEventSubscription = EmbedReactNativeEventEmitter.addListener(
'onEvent',
onEvent
)
return () => {
onEventSubscription.remove()
}
}, [])
```
> [!NOTE]
>
> Learn more about the events triggered by the React Native SDK in our [events](/guides/payments/react-native/events) guide.
# Click to Pay with Secure Fields
Source: https://docs.mattildapayments.com/guides/payments/secure-fields/click-to-pay
Enable Click to Pay for use with Secure Fields
Click to Pay is the better way to pay online – featuring advanced
payment technology built on secure remote commerce industry standards.
## Merchant setup
In order to process Click to Pay payments you will need to register as
a Digital Payments Application (DPA). You can set up Click to Pay in the
dashboard which will automatically register and configure your DPA with Mastercard.

## Prepare the server
Before you can load Click to Pay with Secure Fields into your checkout, you will
need to generate a checkout session via the API. This is made easy with our
server-side SDKs.
### Install a server-side SDK
Use the package manager in your preferred programming language to install our
server-side SDK. Generating a checkout session can only be done server side and
we do not recommend doing this client side as it will expose your API key to your
customers.
```sh C# theme={"dark"}
dotnet add package Gr4vy
```
```sh Go theme={"dark"}
go get github.com/gr4vy/gr4vy-go
```
```sh Java theme={"dark"}
# Please check for the latest version
implementation 'com.gr4vy:sdk:1.0.0'
```
```sh PHP theme={"dark"}
composer require "gr4vy/gr4vy-php"
```
```sh Python theme={"dark"}
pip install gr4vy
```
```sh TypeScript theme={"dark"}
npm install @gr4vy/sdk
# or: yarn add @gr4vy/sdk
```
> [!WARNING]
>
> Please install the [latest release](/guides/get-started#sdks-and-plugins) of your preferred SDK.
### Initialize the SDK client
Next, initialize the SDK with the ID of your instance and the private key.
```csharp C# theme={"dark"}
using Gr4vy;
using Gr4vy.Models.Components;
using System.Collections.Generic;
// Loaded the key from a file, env variable,
// or anywhere else
var privateKey = "...";
var sdk = new Gr4vySDK(
id: "mattilda",
server: SDKConfig.Server.Sandbox,
bearerAuthSource: Auth.WithToken(privateKey),
merchantAccountId: "example"
);
```
```go Go theme={"dark"}
package main
import (
"context"
gr4vy "github.com/gr4vy/gr4vy-go"
"github.com/gr4vy/gr4vy-go/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
privateKey := "...." // Private key loaded from disk or env var
withToken := gr4vy.WithToken(privateKey, []JWTScope{ReadAll, WriteAll}, 60)
s := gr4vy.New(
gr4vy.WithID("mattilda"),
gr4vy.WithServer(gr4vy.ServerSandbox),
gr4vy.WithSecuritySource(withToken),
gr4vy.WithMerchantAccountID("example"),
)
}
```
```java Java theme={"dark"}
package hello.world;
import com.gr4vy.sdk.BearerSecuritySource;
import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.Gr4vy.AvailableServers;
import com.gr4vy.sdk.models.components.AccountUpdaterJobCreate;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.ListTransactionsRequest;
import java.lang.Exception;
import java.util.List;
public class Application {
public static void main(String[] args) throws Exception {
String privateKey = "-----BEGIN PRIVATE KEY-----\n...."; // a valid private key
Gr4vy sdk = Gr4vy.builder()
.id("mattilda")
.server(AvailableServers.SANDBOX)
.merchantAccountId("example")
.securitySource(new BearerSecuritySource.Builder(privateKey).build())
.build();
}
}
```
```php PHP theme={"dark"}
declare(strict_types=1);
require 'vendor/autoload.php';
use Gr4vy;
use Gr4vy\Auth;
// Loaded the key from a file, env variable,
// or anywhere else
$privateKey = "...";
$sdk = Gr4vy\SDK::builder()
->setId('mattilda')
->setServer('sandbox')
->setSecuritySource(Auth::withToken($privateKey))
->setMerchantAccountId('mattilda')
->build();
```
```python Python theme={"dark"}
from gr4vy import Gr4vy, auth
import os
client = Gr4vy(
id="mattilda",
server="production",
merchant_account_id="example",
bearer_auth=auth.with_token(open("./private_key.pem").read())
)
```
```ts TypeScript theme={"dark"}
import fs from "fs";
import { Gr4vy, withToken } from "@gr4vy/sdk";
const gr4vy = new Gr4vy({
server: "sandbox",
id: "mattilda",
bearerAuth: withToken({
privateKey: fs.readFileSync("private_key.pem", "utf8"),
}),
});
```
> [!WARNING]
>
> This SDK needs to be initialized on your server-side. Please do not expose
> your private key to your client-side code.
This assumes the key you created in the previous step is kept in a secure location and
can be loaded as a string. You could store this key in an environment variable or a secure vault.
> [!NOTE]
>
> To learn more about our API authentication, and how to generate a bearer token
> for use without our SDKs, please see our more extensive [authentication
> guide](/guides/api/authentication).
### Create a checkout session
With the SDK installed, you can use it to create a checkout session for use with
Click to Pay.
```js Node theme={"dark"}
const response = await client.newCheckoutSession();
```
```py Python theme={"dark"}
response = client.create_new_checkout_session()
```
```php PHP theme={"dark"}
$checkout_session = $client->newCheckoutSession()
```
```java Java theme={"dark"}
CheckoutSession session = client.newCheckoutSession()
```
```shell cURL theme={"dark"}
curl -i -X POST "https://api.mattildapayments.com/checkout-sessions" \
-H "Authorization: Bearer [JWT_TOKEN]" \
-H "Content-Type: application/json"
```
> [!NOTE]
>
> Please refer to the API reference to [learn more about our Checkout
> Sessions](/reference/checkout-sessions/new-checkout-session) and the
> additional options that can be passed when creating them.
## Create your checkout
With your checkout session ready, it's time to start creating a card form that
can support Click to Pay.
Our frontend integration is called Secure Fields and it essentially wraps each
of your credit card input fields in a secure element, keeping you PCI-compliant
and allowing for seamless integration with Click to Pay.
> [!NOTE]
>
> For more information on Secure Fields, please see our [detailed
> guide](/guides/payments/secure-fields/) which will cover all the available
> options, events, and theming customizations available.
### Install Secure Fields
There are three ways to install **Secure Fields** for use with Click to Pay:
either as a React library, a Node library or straight off our CDN.
**React**
```bash theme={"dark"}
npm install @gr4vy/secure-fields-react --save
# or: yarn add @gr4vy/secure-fields-react
```
### Initializing secure fields
With **Secure Fields** installed it's now possible to initialize the connection
to your instance. It expects the checkout session ID you created earlier.
```jsx theme={"dark"}
import { SecureFields } from "@gr4vy/secure-fields-react";
```
> [!WARNING]
>
> When `SecureFields` is loaded without a valid `sessionId` it will error. We recommend only loading
> the component if the session ID is set.
>
> ```jsx theme={"dark"}
> {sessionId && (
>
> ...
>
> )}
> ```
### Create a card form
Next, you can add any of the 3 individual card fields to your form. You can mix
and match these with your own forms, and you can add your own labels.
Let's start by adding your form with 4 fields: the cardholder's name,
the card number, card expiration date, and the security code for the card.
```jsx theme={"dark"}
import {
CardForm,
CardNumber,
ExpiryDate,
SecurityCode,
useSecureFields
} from '@gr4vy/secure-fields-react'
const secureFields = useSecureFields()
{/* This card form will automatically hide */}
{
console.log('Card form visibility changed. Visible', visible)
}}
>
{/* You can add your own fields as well as secure fields */}
{/* These are fields that will become secure fields */}
```
You should now see each secure field loaded on your page. Please see our more
extensive guides on how to add [event listeners](/guides/payments/secure-fields/events) and
your own [styles](/guides/payments/secure-fields/theming) to **Secure Fields**.
### Add Click to Pay
Next, add the Click to Pay components to show and hide their UI on demand.
```jsx theme={"dark"}
import {
ClickToPay,
ClickToPaySignIn
} from '@gr4vy/secure-fields-react'
{/* The main Click to Pay component */}
{/* An optional sign-in with email or phone for Click to Pay would go here */}
{/* This shows how to sign in with email. For the mobile number use the `mobileNumber` with a `countryCode` and `number` */}
{/* ... */}
{/* ... */}
```
> [!NOTE]
>
> Secure Fields will automatically display and hide the Click to Pay Component, the sign in form, and your card form, based on the
> status of Click to Pay.
### Handle form submission
Once the data has been submitted, you can use the `onCardVaultSuccess` property
on the `SecureFields` component to create a transaction.
```tsx theme={"dark"}
{
// call your API
}}
>...
```
> [!NOTE]
>
> For more information on Secure Fields, please see our [detailed
> guide](/guides/payments/secure-fields/) which will cover all the available
> options, events, and theming customizations available.
**Node/CDN**
```bash Node theme={"dark"}
npm install @gr4vy/secure-fields --save
# or: yarn add @gr4vy/secure-fields
```
```html CDN theme={"dark"}
```
> [!NOTE]
>
> When using the CDN the latest version of the library is always pulled straight
> from the server for every request.
### Initializing secure fields
With **Secure Fields** installed it's now possible to initialize the connection
to your instance. It expects the checkout session ID you created earlier.
```js theme={"dark"}
import SecureFields from "@gr4vy/secure-fields";
// set up the environment
const gr4vyId = "mattilda";
const environment = "sandbox"; // or "production"
const sessionId = "[CHECKOUT_SESSION.ID]";
// initialize the SDK
const secureFields = new SecureFields({
gr4vyId,
environment,
sessionId,
});
// enable debugging
secureFields.setDebug(true);
```
### Create a card form
Next, you can add any of the 3 individual card fields to your form. You can mix
and match these with your own forms, and you can add your own labels.
Let's start by adding your form with 4 fields: the cardholder's name,
the card number, card expiration date, and the security code for the card.
```html theme={"dark"}
```
It is important to add all the card inputs including the number, expiration
date, and security code. Without each of these fields, a transaction can not be
processed. Additional inputs can be added to your form but they will not be
handled by our library.
Next, initialize each of the inputs as a secure field.
```js theme={"dark"}
// Add fields using a querySelector compatible string
const number = secureFields.addCardNumberField("#cc-number", {
placeholder: "Enter card number",
});
const securityCode = secureFields.addSecurityCodeField("#cc-security-code", {
placeholder: "Enter CVV",
});
// Alternatively an HTML element can be passed directly
const expiryDate = secureFields.addExpiryDateField(
document.querySelector("#cc-expiry-date"),
{
placeholder: "Enter expiry date",
}
);
```
This example replaces each of the `` fields for the card form with a new
PCI secure field. It's worth noting that we did not attach a secure field for
the cardholder name, instead, this field will remain a regular HTML input
> [!NOTE]
>
> Every field that Secure Field is attached to needs to be an HTML element. In
> this case, we attached the fields to `` fields. The fields can be
> attached to any element using a `querySelector`-compatible query.
You should now see each secure field loaded on your page. Please see our more
extensive guides on how to add [event listeners](/guides/payments/secure-fields/events) and
your own [styles](/guides/payments/secure-fields/theming) to **Secure Fields**.
### Add Click to Pay
Next, add a placeholder component to your form so we know where to render the
Click to Pay component. Additionally, add a checkbox to allow a customer not
already enrolled to determine if they want to share the card data with Click to
Pay or not. Finally, add the rest of the Click to Pay components to show and hide
their UI on demand.
```html theme={"dark"}
```
Next, attach the secure field for Click to Pay to this element. This will require
an HTML query for the consent checkbox that controls if the card data for a new card
is shared with Click to Pay or not. Next to the consent label, add a link to let users
learn more about Click to Pay. References to the card form and sign in HTML containers
you added previously are also required.
```js theme={"dark"}
const clickToPay = secureFields.addClickToPay('#click-to-pay', {
srcDpaId: '{SRC_DPA_ID}',
dpaName: '{DPA_NAME}',
dpaLocale: 'en_AU',
cardBrands: ['mastercard', 'visa', 'american-express'],
consentCheckbox: "#click-to-pay-consent-checkbox",
learnMoreLink: "#click-to-pay-learn-more-link",
cardForm: "#cc-form",
signIn: "#click-to-pay-sign-in"
// email: 'john@example.com', // optional: define a Click to Pay user e-mail instead of capturing it with the sign-in form
/* mobileNumber: {
countryCode: "61",
phoneNumber: "491570159"
}, */ // optional: define a Click to Pay user phone instead of capturing it with the sign-in form
})
```
> [!NOTE]
>
> Secure Fields will automatically display and hide the Click to Pay Component, the sign in form, and your card form, based on the
> status of Click to Pay.
### Handle form submission
To handle a form submission, you can listen to the submission of the `