### Generate JWT and Fetch Payment Methods (Python) Source: https://docs.montonio.com/api/stargate/guides/payment-methods This Python example illustrates how to create a JWT using the 'PyJWT' library and subsequently use it for an API request to Montonio to obtain payment methods. It specifies the installation command 'pip3 install PyJWT' and includes setting an expiration time for the token. The 'requests' library is used for the HTTP call. ```python ''' We recommend using the PyJWT package to generate Json Web Tokens. You can install it with pip: > pip3 install PyJWT More information can be found at https://pyjwt.readthedocs.io/en/latest/ ''' import jwt import datetime import requests # 1. Create the authorization token payload payload = { 'accessKey': 'MY_ACCESS_KEY', 'exp': datetime.datetime.now(timezone.utc) + datetime.timedelta(minutes=10) } # 2. Generate the token token = jwt.encode(payload, 'MY_SECRET_KEY', algorithm='HS256') print(token) # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiIxZTU0ZTM4NS1hODBiLTRhYzQtYTY1MC1kNmZkNmY3OTA2NGIiLCJpYXQiOjE2OTE3NTQ0OTEsImV4cCI6MTY5MTc1NTA5MX0.nbv7DKAThu_4vaymKPJoTVqQHMZtZ7Hoonk6EAOEIkM # 3. Make the request headers = { 'Authorization': f'Bearer {token}' } response = requests.get('https://stargate.montonio.com/api/stores/payment-methods', headers=headers) data = response.json() print(data['paymentMethods']) # use this data to render the payment methods ``` -------------------------------- ### JavaScript Example Source: https://docs.montonio.com/api/stargate/guides/payment-links Example of how to create a payment link using JavaScript, including JWT generation and API call. ```APIDOC ## JavaScript Example ### Description This example demonstrates how to create a payment link using JavaScript. It covers gathering payment data, generating a JWT using the `jsonwebtoken` package, and sending the JWT to the Montonio API using `axios`. ### Prerequisites - Install `jsonwebtoken`: `npm install jsonwebtoken` - Install `axios`: `npm install axios` ### Code ```javascript // We recommend using the jsonwebtoken package to generate // Json Web Tokens. You can install it with npm: // > npm install jsonwebtoken // More information can be found at // https://www.npmjs.com/package/jsonwebtoken import jwt from "jsonwebtoken"; import axios from "axios"; /** * Note: Please make sure to make these calls from your server, * and not from the client. This is to prevent your secret key * from being exposed to the public. */ // 1. Gather the payment link data const payload = { "accessKey": "MY_ACCESS_KEY", "description": "MY-ORDER-ID-123", "currency": "EUR", "amount": 99.99, "locale": "et", "expiresAt": "2025-03-05T14:48:00.000Z", "notificationUrl": "https://mystore.domain/payments/notify", "askAdditionalInfo": true }; // 2. Generate the token const token = jwt.sign(payload, "MY_SECRET_KEY", { algorithm: "HS256", expiresIn: "10m", // this is only for the token, not the expiry of the payment link itself }); // console.log(token); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiJNWV9BQ0NFU1NfS0VZIiwiZGVzY3JpcHRpb24iOiJNWS1PUkRFUi1JRC0xMjMiLCJjdXJyZW5jeSI6IkVVUiIsImFtb3VudCI6OTkuOTksImxvY2FsZSI6ImV0IiwiZXhwaXJlc0F0IjoiMjAyNS0wMy0wNVQxNDo0ODowMC4wMDBaIiwibm90aWZpY2F0aW9uVXJsIjoiaHR0cHM6Ly9teXN0b3JlLmRvbWFpbi9wYXltZW50cy9ub3RpZnkiLCJhc2tBZGRpdGlvbmFsSW5mbyI6dHJ1ZSwiaWF0IjoxNzM1NDg4NDY0LCJleHAiOjE3MzU0ODkwNjR9.Citf04hOfRJR7P76g_xWDU1MDyqf5bVFvIIql8yhBD8 // 3. Send the token to the API and get the payment link URL axios .post("https://stargate.montonio.com/api/payment-links", { data: token, }) .then((response) => { const { data } = response; console.log(data.url); // https://pay.montonio.com/payment-link-id }); // Note: After successfully creating the payment link, you may now share it with your clients ``` ``` -------------------------------- ### PHP Example Source: https://docs.montonio.com/api/stargate/guides/payment-links Example of how to create a payment link using PHP, including JWT generation and API call. ```APIDOC ## PHP Example ### Description This example demonstrates how to create a payment link using PHP. It covers gathering payment data, generating a JWT using the `firebase/php-jwt` package, and sending the JWT to the Montonio API using cURL. ### Prerequisites - Install `firebase/php-jwt`: `composer require firebase/php-jwt` ### Code ```php composer require firebase/php-jwt * More information can be found at * https://github.com/firebase/php-jwt */ // If you are using composer remember you need to autoload files like this // require __DIR__ . '/vendor/autoload.php'; use \Firebase\JWT\JWT; // 1. Gather the payment link data $payload = [ "accessKey" => "MY_ACCESS_KEY", "description" => "MY-ORDER-ID-123", "currency" => "EUR", "amount" => 99.99, "locale" => "et", "expiresAt" => "2025-03-05T14:48:00.000Z", "askAdditionalInfo" => true, "notificationUrl" => "https://mystore.domain/payments/notify" ]; // add expiry to payment data for JWT validation. This is different from the expiry of the payment link itself $payload['exp'] = time() + (10 * 60); // 2. Generate the token using Firebase's JWT library $token = JWT::encode($payload, 'MY_SECRET_KEY', 'HS256'); // Remove this var_dump once you want the header (location) to work correctly var_dump($token); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiJNWV9BQ0NFU1NfS0VZIiwiZGVzY3JpcHRpb24iOiJNWS1PUkRFUi1JRC0xMjMiLCJjdXJyZW5jeSI6IkVVUiIsImFtb3VudCI6OTkuOTksImxvY2FsZSI6ImV0IiwiZXhwaXJlc0F0IjoiMjAyNS0wMy0wNVQxNDo0ODowMC4wMDBaIiwibm90aWZpY2F0aW9uVXJsIjoiaHR0cHM6Ly9teXN0b3JlLmRvbWFpbi9wYXltZW50cy9ub3RpZnkiLCJhc2tBZGRpdGlvbmFsSW5mbyI6dHJ1ZSwiaWF0IjoxNzM1NDg4NDY0LCJleHAiOjE3MzU0ODkwNjR9.Citf04hOfRJR7P76g_xWDU1MDyqf5bVFvIIql8yhBD8 // 3. Send the token to the API $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://sandbox-stargate.montonio.com/api/payment-links"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ 'data' => $token ])); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($status >= 400) { var_dump($result); // "{"statusCode":401,"message":"STORE_NOT_FOUND","error":"Unauthorized"}" exit; } $data = json_decode($result, true); // var_dump($data['url']); // https://pay.montonio.com/payment-link-id exit; // Note: After successfully creating the payment link, you may now share it with your clients ``` ``` -------------------------------- ### Python Example Source: https://docs.montonio.com/api/stargate/guides/payment-methods Example of how to generate a JWT and make a request to the /stores/payment-methods endpoint using Python. ```APIDOC ```python ''' We recommend using the PyJWT package to generate Json Web Tokens. You can install it with pip: > pip3 install PyJWT More information can be found at https://pyjwt.readthedocs.io/en/latest/ ''' import jwt import datetime import requests # 1. Create the authorization token payload payload = { 'accessKey': 'MY_ACCESS_KEY', 'exp': datetime.datetime.now(timezone.utc) + datetime.timedelta(minutes=10) } # 2. Generate the token token = jwt.encode(payload, 'MY_SECRET_KEY', algorithm='HS256') print(token) # 3. Make the request headers = { 'Authorization': f'Bearer {token}' } response = requests.get('https://stargate.montonio.com/api/stores/payment-methods', headers=headers) data = response.json() print(data['paymentMethods']) # use this data to render the payment methods ``` ``` -------------------------------- ### PHP Example Source: https://docs.montonio.com/api/stargate/guides/payment-methods Example of how to generate a JWT and make a request to the /stores/payment-methods endpoint using PHP. ```APIDOC ```php composer require firebase/php-jwt * More information can be found at * https://github.com/firebase/php-jwt */ // Should be loaded only once in the app, check composer docs for the specific framework you are using require __DIR__ . '/vendor/autoload.php'; use \Firebase\JWT\JWT; // 1. Create the authorization token payload $payload = [ 'accessKey' => 'YOUR_ACCESS_KEY', ]; // add expiry to the token for JWT validation $payload['exp'] = time() + (10 * 60); // 2. Generate the token using Firebase's JWT library $token = JWT::encode($payload, 'MY_SECRET_KEY', 'HS256'); // var_dump($token); // 3. Make the request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://sandbox-stargate.montonio.com/api/stores/payment-methods"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', "Authorization: Bearer ${token}" ]); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($status >= 400) { var_dump($result); exit; } // 4. Decode the list of enabled payment methods $data = json_decode($result, true); var_dump($data['paymentMethods']); // use the data to render the payment methods // if empty that means the paymentMethods have not been enabled for you store, contact customer support ``` ``` -------------------------------- ### JavaScript Example Source: https://docs.montonio.com/api/stargate/guides/payment-methods Example of how to generate a JWT and make a request to the /stores/payment-methods endpoint using JavaScript. ```APIDOC ```javascript /** * We recommend using the jsonwebtoken package to generate * Json Web Tokens. You can install it with npm: * > npm install jsonwebtoken * More information can be found at * https://www.npmjs.com/package/jsonwebtoken */ import jwt from 'jsonwebtoken'; import axios from 'axios'; /** * Note: Please make sure to make these calls from your server, * and not from the client. This is to prevent your secret key * from being exposed to the public. */ // 1. Create the authorization token payload const payload = { accessKey: 'MY_ACCESS_KEY' // your store's Access Key from the Partner System }; // 2. Generate the token const token = jwt.sign( payload, 'MY_SECRET_KEY', // your store's Secret Key from the Partner System { algorithm: 'HS256', expiresIn: '10m' } ); // console.log(token); // 3. Make the request axios.get('https://stargate.montonio.com/api/stores/payment-methods', { headers: { 'Authorization': `Bearer ${token}` } }).then(response => { const { data } = response; console.log(data.paymentMethods); // use this data to render the payment methods }); ``` ``` -------------------------------- ### PHP: Initiate Payment and Get Payment URL Source: https://docs.montonio.com/api/stargate/guides/orders This PHP snippet demonstrates how to initiate a payment with Montonio. It uses cURL to send a POST request to the Montonio API, retrieves the payment URL from the response, and redirects the customer. Ensure cURL is enabled in your PHP installation. The output is a redirect to the payment gateway. ```php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://stargate.montonio.com/api/orders'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array( 'grant_type' => 'client_credentials', 'client_id' => 'MY_CLIENT_ID', 'client_secret' => 'MY_CLIENT_SECRET' ))); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); cert_close($ch); if ($status >= 400) { var_dump($result); // "{"statusCode":401,"message":"STORE_NOT_FOUND","error":"Unauthorized"}" exit; } // 5. Get the payment URL $data = json_decode($result, true); // var_dump($data['paymentUrl']); // https://gateway.montonio.com/some-random-uuid // 6. Redirect the customer to the checkout page header("Location: " . $data['paymentUrl']); exit; ``` -------------------------------- ### Authentication - JWT Generation Examples Source: https://docs.montonio.com/api/shipping-v2/reference Examples demonstrating how to generate JWT for authentication using JavaScript, PHP, and Python. ```APIDOC ## JWT Generation Examples ### JavaScript ```javascript import jwt from 'jsonwebtoken'; const payload = { accessKey: 'MY_ACCESS_KEY' }; const authHeader = jwt.sign( payload, 'MY_SECRET_KEY', { algorithm: 'HS256', expiresIn: '1h' } ); console.log(authHeader); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiJNWV9BQ0NFU1NfS0VZIiwiaWF0IjoxNjc1OTM4NjM3LCJleHAiOjE2NzU5NDIyMzd9.f-wXP8t5HGhr5XKAl3eCeWbHnY3SO9DcY5WiWo06-uQ ``` ### PHP ```php require __DIR__ . '/vendor/autoload.php'; use \Firebase\JWT\JWT; $payload = [ 'accessKey' => 'MY_ACCESS_KEY', 'iat' => time(), 'exp' => time() + (60 * 60) ]; $token = JWT::encode($payload, 'MY_SECRET_KEY', 'HS256'); // var_dump($token); // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2Nlc3NLZXkiOiJNWV9BQ0NFU1NfS0VZIiwiaWF0IjoxNjc2MDQ1NTg5LCJleHAiOjE2NzYwNDkxODl9.9kz7LBZZVJrJbSO_42NTTg1Wg4HEP01cqOw0IzQ0nXU ``` ### Python ```python import jwt from datetime import datetime, timedelta, timezone payload = { 'accessKey': 'MY_ACCESS_KEY', 'iat': datetime.now(timezone.utc), 'exp': datetime.now(timezone.utc) + timedelta(hours=1) } auth_header = jwt.encode( payload, 'MY_SECRET_KEY', algorithm='HS256' ) print(auth_header) # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3Nfa2V5IjoibWVyY2hhbnRfYWNjZXNzX2tleSIsImlhdCI6MTYwMzcxMTQ3NSwiZXhwIjoxNjAzNzE1MDc1fQ.UYwRQXykcIVNzIjni3icf_FBbxSXZ_m-2SsFfz3zjBs ``` ``` -------------------------------- ### GET /stores/payment-methods Source: https://docs.montonio.com/api/stargate/guides/payment-methods Fetches a list of all payment methods enabled for your store. This includes details for payment initiation banks. ```APIDOC ## GET /stores/payment-methods ### Description Retrieves a list of all enabled payment methods for the authenticated store, including specific bank options for payment initiation. ### Method GET ### Endpoint /stores/payment-methods ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **paymentMethods** (array) - A list of available payment methods. - Each payment method object may contain: - **systemName** (string) - The system name of the payment method (e.g., `paymentInitiation`, `cardPayments`). - **supportedCurrencies** (array) - A list of currencies supported by this payment method. - **banks** (array, optional) - For `paymentInitiation`, a list of available banks for a given country. - Each bank object may contain: - **name** (string) - The name of the bank. - **country** (string) - The country code the bank operates in. #### Response Example ```json { "paymentMethods": [ { "systemName": "paymentInitiation", "supportedCurrencies": ["EUR", "PLN"], "banks": [ { "name": "Luminor Bank", "country": "LT" }, { "name": "SEB Bank", "country": "LT" } ] }, { "systemName": "cardPayments", "supportedCurrencies": ["EUR", "PLN"] }, { "systemName": "blik", "supportedCurrencies": ["PLN"] }, { "systemName": "bnpl", "supportedCurrencies": ["EUR"] }, { "systemName": "hirePurchase", "supportedCurrencies": ["EUR"] } ] } ``` ``` -------------------------------- ### Montonio API Example Response - Order Details Source: https://docs.montonio.com/api/stargate/reference This JSON object represents an example response from the Montonio API, detailing an order's status, payment information, customer details, and refund history. It includes fields like payment status, amounts, currency, line items, billing and shipping addresses, and timestamps. ```json { "uuid": "0ac2124d-9f8e-4a29-816d-7eef5b9bb0fd", "paymentStatus": "PARTIALLY_REFUNDED", "locale": "et", "merchantReference": "MY-ORDER-ID-123", "merchantReferenceDisplay": "MY-ORDER-ID-123", "merchantReturnUrl": "https://mystore.com/payment/return", "merchantNotificationUrl": "https://mystore.com/payment/notify", "grandTotal": "100.00", "currency": "EUR", "paymentMethodType": "cardPayments", "paymentIntents": [ { "uuid": "293513c0-66b1-401a-8afa-75e1f5714516", "paymentMethodType": "cardPayments", "paymentMethodMetadata": {}, "amount": "100.00", "currency": "EUR", "status": "PAID", "serviceFee": "3.15", "serviceFeeCurrency": "EUR", "createdAt": "2023-05-23T08:22:53.899Z" } ], "refunds": [ { "uuid": "92b11684-319a-4cce-92f5-56d348aa986a", "amount": "25", "status": "SUCCESSFUL", "currency": "EUR", "createdAt": "2023-05-23T08:37:55.534Z", "type": "PARTIAL_REFUND" }, { "uuid": "8453465a-a9d8-469e-a838-5b2b5b20f429", "amount": "25", "status": "SUCCESSFUL", "currency": "EUR", "createdAt": "2023-05-23T11:03:04.954Z", "type": "PARTIAL_REFUND" } ], "availableForRefund": 50, "isRefundableType": false, "lineItems": [ { "name": "Hoverboard", "quantity": 1, "finalPrice": 100 } ], "billingAddress": { "firstName": "CustomerFirst", "lastName": "CustomerLast", "email": "test@montonio.com", "phoneNumber": null, "phoneCountry": null, "addressLine1": "Kai 1", "addressLine2": null, "locality": "Tallinn", "region": null, "country": "EE", "postalCode": "10111", "companyName": null, "companyLegalName": null, "companyRegCode": null, "companyVatNumber": null }, "shippingAddress": { "firstName": "CustomerFirstShipping", "lastName": "CustomerLastShipping", "email": "test@montonio.com", "phoneNumber": null, "phoneCountry": null, "addressLine1": "Kai 1", "addressLine2": null, "locality": "Tallinn", "region": null, "country": "EE", "postalCode": "10111", "companyName": null, "companyLegalName": null, "companyRegCode": null, "companyVatNumber": null }, "expiresAt": null, "createdAt": "2023-05-23T08:22:53.879Z", "storeName": "My Store Name", "businessName": "My Business Name", "paymentUrl": null } ``` -------------------------------- ### GET /api/stores/payment-methods Source: https://docs.montonio.com/api/stargate/guides/payment-methods Retrieves a list of available payment methods for a given store. ```APIDOC ## GET /api/stores/payment-methods ### Description Retrieves a list of available payment methods for a given store. This endpoint is useful for displaying payment options to users during checkout. ### Method GET ### Endpoint /api/stores/payment-methods ### Parameters #### Query Parameters None #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example ```curl curl -X GET \ 'https://stargate.montonio.com/api/stores/payment-methods' \ -H 'Authorization: Bearer ' ``` ### Response #### Success Response (200) - **payment_methods** (array) - A list of payment method objects. - **code** (string) - The unique code for the payment method. - **name** (string) - The display name of the payment method. - **type** (string) - The type of payment method (e.g., 'card', 'banklink'). #### Response Example ```json { "payment_methods": [ { "code": "lks", "name": "Luminor banklink", "type": "banklink" }, { "code": "swedbank", "name": "Swedbank banklink", "type": "banklink" } ] } ``` ``` -------------------------------- ### GET /webhooks - List All Webhooks Source: https://docs.montonio.com/api/shipping-v2/guides/webhooks Retrieves a list of all currently registered webhooks for your store. ```APIDOC ## GET /webhooks ### Description Retrieves a list of all webhooks currently registered for the authenticated store. ### Method GET ### Endpoint `/webhooks` ### Parameters None ### Request Example (No request body or parameters required for this endpoint) ### Response #### Success Response (200) - **id** (string) - The unique identifier for the webhook. - **createdAt** (string) - The timestamp when the webhook was created. - **url** (string) - The registered webhook URL. - **enabledEvents** (array of strings) - The list of events enabled for this webhook. #### Response Example ```json [ { "id": "3f922a3a-5063-405b-a489-a2a13a86a13b", "createdAt": "2024-06-13T10:41:22.191Z", "url": "https://webhook.site/305802f7-4bad-4401-b4ee-b4d89aeae6d2", "enabledEvents": [ "shipment.registered" ] }, { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "createdAt": "2024-06-12T09:30:00.000Z", "url": "https://example.com/montonio-callback", "enabledEvents": [ "shipment.statusUpdated", "labelFile.ready" ] } ] ``` ### Errors - **401** Unauthorized. Please check your authentication token. - **500** Internal server error. Something went wrong on our side. ``` -------------------------------- ### Initialize Montonio Checkout SDK Source: https://docs.montonio.com/api/stargate/widgets This snippet demonstrates how to initialize the Montonio Checkout SDK with basic configuration, including access key, store setup data, and event handlers. It also shows how to retrieve and display preferred region and provider information. The SDK is loaded via a script tag, and initialization occurs within the `window.onMontonioLoaded` function. ```html Montonio SDK
``` -------------------------------- ### Payment Initiation - Card Payments Source: https://docs.montonio.com/api/stargate/guides/orders Configure options specifically for initiating card payments. Requires separate onboarding. ```APIDOC ## POST /api/payments (Hypothetical Endpoint) ### Description Initiates a card payment with Montonio. Requires separate onboarding. Supported currencies: `EUR`, `PLN`. ### Method POST ### Endpoint /api/payments ### Parameters #### Request Body - **payment** (object) - Required - The payment object. - **method** (string) - Required - Must be set to `cardPayments`. - **methodOptions** (object) - Optional - Options specific to card payments. - **preferredMethod** (string) - Optional - Determines the default UI selection between Card payments or Wallets. Defaults to `wallet` (Apple/Google Pay). Available values: `wallet`, `card`. - **preferredLocale** (string) - Optional - The preferred language of the payment gateway. Defaults to the Order locale. Available values are `de`, `en`, `et`, `fi`, `lt`, `lv`, `pl`, `ru`. ### Request Example ```json { "payment": { "method": "cardPayments", "methodOptions": { "preferredMethod": "wallet", "preferredLocale": "en" } } } ``` ### Response #### Success Response (200) - **paymentId** (string) - The unique identifier for the initiated payment. - **status** (string) - The current status of the payment. #### Response Example ```json { "paymentId": "pay_abc123xyz", "status": "pending" } ``` ``` -------------------------------- ### Get available payment methods (cURL) Source: https://docs.montonio.com/api/stargate/reference Example cURL request to retrieve all enabled payment methods for a store from the Montonio API. Requires an 'Authorization' header with a Bearer token. ```bash curl -X GET \ 'https://stargate.montonio.com/api/stores/payment-methods' \ -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiJNWV9BQ0NFU1NfS0VZIiwiaWF0IjoxNjc1OTM4NjM3LCJleHAiOjE2NzU5NDIyMzd9.f-wXP8t5HGhr5XKAl3eCeWbHnY3SO9DcY5WiWo06-uQ' ``` -------------------------------- ### Validate Montonio Order Token - Python Source: https://docs.montonio.com/api/stargate/guides/orders Illustrates the initial step for validating a Montonio Order Token in Python using the `PyJWT` package. It mentions installing the package via pip and provides a starting point for token verification. ```python ''' We recommend using the PyJWT package to verify Json Web Tokens. You can install it with pip: > pip3 install PyJWT More information can be found at https://pyjwt.readthedocs.io/en/latest/ ''' import jwt ``` -------------------------------- ### Configure Payment Initiation in PHP Source: https://docs.montonio.com/api/stargate/guides/orders This snippet shows how to set up the 'paymentInitiation' method for an order in PHP. It details the 'methodOptions' including 'preferredProvider', 'preferredCountry', and 'paymentDescription'. The 'preferredProvider' code should be retrieved from the GET /stores/payment-methods endpoint. ```php $order["payment"] => [ "method" => "paymentInitiation", "methodOptions" => [ // This is the code of the bank that the customer chose at checkout. // See the GET /stores/payment-methods endpoint for the list of available banks. "preferredProvider" => "LHVBEE22", // For international banks (e.g., Revolut, N26), ensure this matches // the country of the bank list you displayed to the customer. "preferredCountry" => "EE", "preferredLocale" => "et", "paymentDescription" => "Payment for order 123" ] ] ``` -------------------------------- ### Generate JWT and Fetch Payment Methods (PHP) Source: https://docs.montonio.com/api/stargate/guides/payment-methods This PHP example demonstrates how to generate a JWT using the 'firebase/php-jwt' package and authenticate an API call to retrieve payment methods. The code includes instructions for composer installation and highlights the importance of server-side execution. It uses cURL for making the HTTP request. ```php composer require firebase/php-jwt * More information can be found at * https://github.com/firebase/php-jwt */ // Should be loaded only once in the app, check composer docs for the specific framework you are using require __DIR__ . '/vendor/autoload.php'; use \Firebase\JWT\JWT; // 1. Create the authorization token payload $payload = [ 'accessKey' => 'YOUR_ACCESS_KEY', ]; // add expiry to the token for JWT validation $payload['exp'] = time() + (10 * 60); // 2. Generate the token using Firebase's JWT library $token = JWT::encode($payload, 'MY_SECRET_KEY', 'HS256'); // var_dump($token); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiIxZTU0ZTM4NS1hODBiLTRhYzQtYTY1MC1kNmZkNmY3OTA2NGIiLCJpYXQiOjE2OTE3NTQ0OTEsImV4cCI6MTY5MTc1NTA5MX0.nbv7DKAThu_4vaymKPJoTVqQHMZtZ7Hoonk6EAOEIkM // 3. Make the request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://sandbox-stargate.montonio.com/api/stores/payment-methods"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', "Authorization: Bearer ${token}" ]); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($status >= 400) { var_dump($result); // "{"statusCode":401,"message":"STORE_NOT_FOUND","error":"Unauthorized"}" exit; } // 4. Decode the list of enabled payment methods $data = json_decode($result, true); var_dump($data['paymentMethods']); // use the data to render the payment methods // if empty that means the paymentMethods have not been enabled for you store, contact customer support ``` -------------------------------- ### Payment Initiation - BLIK Payments Source: https://docs.montonio.com/api/stargate/guides/orders Configure options for initiating BLIK payments. BLIK is available only in Poland and requires separate onboarding. Supported currency: `PLN`. ```APIDOC ## POST /api/payments (Hypothetical Endpoint) ### Description Initiates a BLIK payment with Montonio. BLIK is only available in Poland and requires separate onboarding. Supported currency: `PLN`. ### Method POST ### Endpoint /api/payments ### Parameters #### Request Body - **payment** (object) - Required - The payment object. - **method** (string) - Required - Must be set to `blik`. - **methodOptions** (object) - Optional - Options specific to BLIK payments. - **preferredLocale** (string) - Optional - The preferred language of the payment gateway. Defaults to the Order locale. Available values are `de`, `en`, `et`, `fi`, `lt`, `lv`, `pl`, `ru`. ### Request Example ```json { "payment": { "method": "blik", "methodOptions": { "preferredLocale": "pl" } } } ``` ### Response #### Success Response (200) - **paymentId** (string) - The unique identifier for the initiated payment. - **status** (string) - The current status of the payment. #### Response Example ```json { "paymentId": "pay_abc123xyz", "status": "pending" } ``` ``` -------------------------------- ### Fetch Label File Request (JavaScript) Source: https://docs.montonio.com/api/shipping-v2/guides/labels This example shows how to fetch a generated label file using the Montonio API with JavaScript and Axios. It performs a GET request to the /label-files/{id} endpoint to retrieve the label file details, including the download URL once the status is 'ready'. ```javascript import axios from 'axios'; const config = { method: 'get', url: 'https://shipping.montonio.com/api/v2/label-files/f8d8c402-0535-413f-b723-fd1101f2b580', headers: { Authorization: 'Bearer [your_token]', } }; async function makeRequest() { try { const response = await axios.request(config); console.log(JSON.stringify(response.data)); } catch (error) { console.log(error); } } makeRequest(); ``` -------------------------------- ### Payment Initiation - General Options Source: https://docs.montonio.com/api/stargate/guides/orders Configure general options for payment initiation, such as preferred bank, country, locale, and payment description. ```APIDOC ## POST /api/payments (Hypothetical Endpoint) ### Description Initiates a payment with Montonio, allowing configuration of various payment method options. ### Method POST ### Endpoint /api/payments ### Parameters #### Request Body - **payment** (object) - Required - The payment object containing method and method options. - **method** (string) - Required - The payment method to use (e.g., `cardPayments`, `blik`). - **methodOptions** (object) - Optional - Options specific to the chosen payment method. - **preferredProvider** (string) - Optional - The bank that the customer chose for this payment. Leave blank to let the customer choose their bank in our interface. The value can be found in the `code` parameters of the `GET /payment-methods` response. Highly recommended to improve customer experience and save time at checkout. - **preferredCountry** (string) - Optional - The preferred country for the methods list of the payment gateway. Defaults to the merchant's country. Available values are `EE`, `LV`, `LT`, `FI`, `PL`, `DE`. Note: For international banks, set `preferredCountry` to match the customer's country. - **preferredLocale** (string) - Optional - The preferred language of the payment gateway. Defaults to the Order locale. Available values are `de`, `en`, `et`, `fi`, `lt`, `lv`, `pl`, `ru`. - **paymentDescription** (string) - Optional - Description of the payment that will be relayed to the bank's payment order. Defaults to `merchantReference`. - **paymentReference** (string) - Optional - Structured payment reference number used for accounting purposes. This number is strictly validated by banks. ### Request Example ```json { "payment": { "method": "someMethod", "methodOptions": { "preferredProvider": "someBankCode", "preferredCountry": "EE", "preferredLocale": "en", "paymentDescription": "Order #12345", "paymentReference": "REF-12345-XYZ" } } } ``` ### Response #### Success Response (200) - **paymentId** (string) - The unique identifier for the initiated payment. - **status** (string) - The current status of the payment. #### Response Example ```json { "paymentId": "pay_abc123xyz", "status": "pending" } ``` ``` -------------------------------- ### Refund Order using JWT - JavaScript Source: https://docs.montonio.com/api/stargate/guides/refunds This JavaScript example demonstrates how to refund an order using the Montonio API. It utilizes the 'jsonwebtoken' NPM package to create and sign a JWT with order details and secret key. The signed JWT is then sent via a POST request to the Montonio API. Ensure you have installed the 'jsonwebtoken' and 'axios' packages. ```javascript /** * We recommend using the jsonwebtoken NPM package to generate * Json Web Tokens. You can install it with npm: * > npm install jsonwebtoken */ const jwt = require('jsonwebtoken'); const axios = require('axios'); const { randomUUID } = require('crypto'); // For production use https://stargate.montonio.com/api const MONTONIO_BASE_URL = 'https://sandbox-stargate.montonio.com/api'; const MONTONIO_ACCESS_KEY = 'YOUR_ACCESS_KEY'; const MONTONIO_SECRET_KEY = 'YOUR_SECRET_KEY'; const MONTONIO_ORDER_UUID = '12228dce-2f7c-4db5-8d28-5d82a19aa3b6'; // 1. Compose the data for the refund // We suggest saving the idempotency key in your database to prevent duplicate refunds const idempotencyKey = randomUUID(); const payload = { "accessKey": MONTONIO_ACCESS_KEY, "orderUuid": MONTONIO_ORDER_UUID, "amount": 1.00, // Please make sure to round the amount to 2 decimal places "idempotencyKey": idempotencyKey } // 2. Generate the token and sign it with your Secret Key const token = jwt.sign( payload, MONTONIO_SECRET_KEY, { algorithm: 'HS256', expiresIn: '10m' } ); // 3. Make the request axios.post(MONTONIO_BASE_URL + '/refunds', { data: token }).then(response => { console.log(response.data); }).catch(error => { console.log(error.response.data); }); ``` -------------------------------- ### Get Pickup Points (cURL) Source: https://docs.montonio.com/api/shipping-v2/reference This cURL example shows how to fetch carrier-specific pickup points for a store. It requires carrier code, country code, and optionally a pickup point type. The response provides a list of pickup points with their details such as ID, name, type, address, and carrier code. This is useful for integrating local delivery options. ```cURL curl -X 'GET' \ 'https://shipping.montonio.com/api/v2/shipping-methods/pickup-points?carrierCode=omniva&countryCode=EE&type=parcelMachine' \ -H 'accept: application/json' \ -H 'Authorization: Bearer [your_token]' ``` -------------------------------- ### Configure Payment Initiation in Python Source: https://docs.montonio.com/api/stargate/guides/orders This snippet illustrates the configuration of the 'paymentInitiation' payment method for an order in Python. Key 'methodOptions' like 'preferredProvider', 'preferredCountry', and 'paymentDescription' are included. The correct 'preferredProvider' code can be found using the GET /stores/payment-methods endpoint. ```python order["payment"] = { "method": "paymentInitiation", "methodOptions": { # This is the code of the bank that the customer chose at checkout. # See the GET /stores/payment-methods endpoint for the list of available banks. "preferredProvider": "LHVBEE22", # For international banks (e.g., Revolut, N26), ensure this matches # the country of the bank list you displayed to the customer. "preferredCountry": "EE", "preferredLocale": "et", "paymentDescription": "Payment for order 123" } } ```