openapi: 3.0.0
info:
  title: OP Corporate Banking APIs Token management
  description: |
    <br/>OP Corporate Banking APIs Token management enables OP corporate customers
    to access OP Corporate Banking APIs.

    ## Authentication
    Authentication in OP Corporate Banking APIs is based on practices
    from OpenID Connect (OIDC) 1.0 and OAuth 2.0. No user authentication is required (OAuth2.0 server-to-server client credentials flow is followed).

    ## Security Considerations
    It is extremely important that the client ID, client secret and client certificate
    private key are not exposed at any point. Together they represent the identity
    of the client and thereby the corporation. In the possession of an attacker
    they could be used to make fraudulent API calls potentially causing considerable
    damage.

    ## Change log
    ### V1.0.2 (09/2026)
    - Updated the Sandbox API endpoint address

    ### V1.0.1 (08/2024)
    Added error 401 in response

    ### V1.0 (12/2019)
    Initial version  
  contact:
    name: Support
    email: corp-payment-APIs@op.fi
  version: 1.0.2
servers:
  - url: 'https://api.sandbox.corporate-api.op.fi'
    description: Sandbox environment (uses test data)
  - url: 'https://api.corporate-api.op.fi/'
    description: Production environment (uses live data)
paths:
  /corporate-oidc/v1/token:
    post:
      summary: Generate access token
      description: |
        The service generates an access token
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/generateAccessTokenRequest'
      operationId: generateToken
      x-codeSamples:
        - lang: Shell
          label: CLI
          source: |
            #!/bin/bash

            # To run this you need openssl and jq installed.

            # Steps for registering the required keys and certificates
            # 1. Valid Corporate API contract created through OP API Admin
            # 2. OAuth clientId and clientSecret provisioned
            # 3. mTLS private key generated: openssl genrsa -out sandbox-mtls.key 4096
            # 4. mTLS certificate signing request (CN and other attributes are ignored):
              openssl req -new -key sandbox-mtls.key -out sandbox-mtls.csr
            # 5. Valid mTLS certificate aquired from OP API Admin using the csr from 
              step 4. and in "sandbox-mtls.crt" file

            # OAuth credentials
            clientId="TODO put here oauth client id"
            clientSecret="TODO and here client secret"

            # MTLS credentials
            mtlsKey="sandbox-mtls.key"
            mtlsCertificate="sandbox-mtls.crt"

            API_SERVER="https://api.sandbox.corporate-api.op.fi"

            echo "Getting access token"

            reply=$(curl -s ${API_SERVER}/corporate-oidc/v1/token \
              --key ${mtlsKey} \
              --cert ${mtlsCertificate} \
              -H 'Content-Type:application/x-www-form-urlencoded' \
              -d "grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}")
                
            token=$(echo $reply | jq -r .access_token)
            echo "Access token is: $token"
        - lang: C#
          source: |
            /*
                OP Corporate Banking API Token management - Generate access token C# code example

                # Steps for registering the required keys and certificates
                # 1. Valid Corporate API contract created in OP API Admin
                # 2. OAuth clientId and clientSecret provisioned
                # 3. MTLS private key generated: openssl genrsa -out mtls-private.key 4096
                # 4. MTLS certificate signing request (CN and other attributes are ignored): openssl req -new -key mtls-private.key -out mtls.csr
                # 5. Valid MTLS certificate downloaded from OP API Admin as file "mtls-certificate.crt" by uploading the certificate signing request (CSR) from the previous step

                Generated keys and certificates should be added also to the application folder.
            */

            namespace GenerateToken
            {
                using System;
                using System.Net.Http;
                using System.Security.Cryptography.X509Certificates;
                using System.IO;
                using System.Text;
                using System.Text.Json.Nodes;
                using Newtonsoft.Json.Linq;
                using System.Net.Http.Headers;
                using System.Text.Json;
                using System.Dynamic;

                public class Program
                {
                    private const string ApiUrl = "api.sandbox.corporate-api.op.fi";

                    static async Task Main(string[] args)
                    {
                        // OAuth credentials
                        var clientId = "TODO your oauth client id";
                        var clientSecret = "TODO your oauth client secret";

                        // Read mtls credentials from file.
                        var mtlsCertificate = File.ReadAllText("TODO your MTLS certificate filename");
                        var mtlsPrivateKey = File.ReadAllText("TODO your decrypted MTLS private key filename");

                        // Add MTLS credentials to http client handler.
                        var httpClientHandler = new HttpClientHandler();
                        X509Certificate2 certificate = X509Certificate2.CreateFromPem(mtlsCertificate, mtlsPrivateKey);
                        httpClientHandler.ClientCertificates.Add(certificate);
                        httpClientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;

                        // ############################
                        // GET TOKEN
                        // ############################

                        var postData = new List<KeyValuePair<string, string>>
                        {
                            new("grant_type", "client_credentials"),
                            new("client_id", clientId),
                            new("client_secret", clientSecret)
                        };

                        // Replace 'ApiUrl' with the actual URL you need to call
                        Console.WriteLine("Getting access token");
                        var httpClient = new HttpClient(httpClientHandler);
                        var response = await httpClient.PostAsync($"https://{ApiUrl}/corporate-oidc/v1/token", new FormUrlEncodedContent(postData));
                        response.EnsureSuccessStatusCode();
                        var authContent = await response.Content.ReadAsStringAsync();
                        dynamic data = JObject.Parse(authContent);
                        var token = data.access_token.ToString();
                        Console.WriteLine($"Access token is: {token}\n");
                    }
                }
            }
        - lang: Java
          source: |
            /**
              OP Corporate Banking API Token management - Generate access token Java code example
              You need openssl installed to generate certificates and keys.

              # Steps for registering the required keys and certificates
              # 1. Valid Corporate API contract created in API Admin
              # 2. OAuth clientId and clientSecret provisioned
              # 3. MTLS private key generated: openssl genrsa -out sandbox-mtls.key 4096
              # 4. MTLS certificate signing request (CN and other attributes are ignored): openssl req -new -key sandbox-mtls.key -out sandbox-mtls.csr
              # 5. Valid MTLS certificate downloaded from API Admin as file "sandbox-mtls.crt" by uploading the certificate signing request (CSR) from the previous step

              Add generated certificates and keys to resources folder.
            */
            package example;

            import java.io.BufferedReader;
            import java.io.IOException;
            import java.io.InputStream;
            import java.io.InputStreamReader;
            import java.net.URI;
            import java.net.http.HttpClient;
            import java.net.http.HttpRequest;
            import java.net.http.HttpRequest.BodyPublishers;
            import java.net.http.HttpResponse;
            import java.nio.charset.StandardCharsets;
            import java.security.KeyFactory;
            import java.security.KeyStore;
            import java.security.NoSuchAlgorithmException;
            import java.security.PrivateKey;
            import java.security.SecureRandom;
            import java.security.cert.CertificateFactory;
            import java.security.cert.X509Certificate;
            import java.security.spec.EncodedKeySpec;
            import java.security.spec.InvalidKeySpecException;
            import java.security.spec.PKCS8EncodedKeySpec;
            import java.time.Instant;
            import java.util.Base64;
            import java.util.UUID;
            import java.util.stream.Collectors;

            import javax.net.ssl.KeyManagerFactory;
            import javax.net.ssl.SSLContext;

            import org.json.JSONArray;
            import org.json.JSONObject;

            public class GenerateToken {

                private static final String API_URL = "api.sandbox.corporate-api.op.fi";
                private static final char[] MY_PASSWORD = "password".toCharArray();

                public static void main(String[] args) throws Exception {
                    // OAuth credentials
                    String clientId = "TODO: your oauth client id";
                    String clientSecret = "TODO: your oauth client secret";

                    // MTLS credentials
                    String mtlsCertificate = "TODO: your MTLS certificate filename";
                    String mtlsPrivateKey = "TODO: your decrypted MTLS private key filename";

                    // Load the client certificate
                    var certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(GenerateToken.class.getResourceAsStream(mtlsCertificate));

                    // Load the MTLS private key
                    PrivateKey privateKey = getPrivateKey(mtlsPrivateKey);

                    // Create a KeyStore with the client certificate and private key
                    KeyStore keyStore = KeyStore.getInstance("PKCS12");
                    keyStore.load(null, null);
                    keyStore.setKeyEntry("alias", privateKey, MY_PASSWORD, new X509Certificate[]{certificate});

                    // Create an SSLContext with the KeyStore
                    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
                    keyManagerFactory.init(keyStore, MY_PASSWORD);
                    SSLContext sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

                    // Create the HttpClient with the SSLContext
                    HttpClient httpClient = HttpClient.newBuilder().sslContext(sslContext).build();

                    // ############################
                    // GET TOKEN
                    // ############################

                    HttpRequest tokenRequest = HttpRequest.newBuilder()
                            .uri(URI.create("https://" + API_URL + "/corporate-oidc/v1/token"))
                            .header("Content-Type", "application/x-www-form-urlencoded")
                            .POST(BodyPublishers.ofString("grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret))
                            .build();

                    System.out.println("Getting access token");
                    HttpResponse<String> tokenResponse = httpClient.send(tokenRequest, HttpResponse.BodyHandlers.ofString());
                    String token = new JSONObject(tokenResponse.body()).getString("access_token");
                    System.out.println("Access token is: " + token + "\n");

                }

                static PrivateKey getPrivateKey(String fileName) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
                    // Read PEM formatted key content.
                    String pemFormattedKey = getResourceFileAsString(fileName);
                    // Remove header, footer, and line breaks
                    var privateKeyPEM = pemFormattedKey
                        .replace("-----BEGIN PRIVATE KEY-----", "")
                        .replace("-----END PRIVATE KEY-----", "")
                        .replaceAll("\\s+", "")
                        .trim();

                    // Decode the base64-encoded key data
                    byte[] decodedPrivateKeyBytes = Base64.getDecoder().decode(privateKeyPEM);

                    // Generate private key
                    KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
                    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodedPrivateKeyBytes);
                    return privateKeyFactory.generatePrivate(privateKeySpec);
                }

                static String getResourceFileAsString(String fileName) throws IOException {
                    try (InputStream is = GenerateToken.class.getResourceAsStream(fileName)) {
                            try (InputStreamReader isr = new InputStreamReader(is);
                                    BufferedReader reader = new BufferedReader(isr)) {
                            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
                        }
                    }
                }
            }
        - lang: Javascript
          label: Node.js
          source: |
            /*
              OP Corporate Banking API Token management - Generate access token Node.js code example

              To run this you need openssl and jq installed in addition to a Node.js runtime (or a Node.js virtual machine such as nvm).
              The example can be run on Node.js runtime versions 17.0 and above.

              Steps for registering the required keys and certificates
              1. Valid Corporate API contract created in OP API Admin
              2. OAuth clientId and clientSecret provisioned
              3. MTLS private key generated: openssl genrsa -out sandbox-mtls.key 4096
              4. MTLS certificate signing request (CN and other attributes are ignored): openssl req -new -key sandbox-mtls.key -out sandbox-mtls.csr
              5. Valid MTLS certificate downloaded from OP API Admin as file "sandbox-mtls.crt" by uploading the certificate signing request (CSR) from the previous step

              Add generated certificates and keys to resources folder.
            */

            const crypto = require('crypto');
            const https = require('https');
            const axios = require('axios');
            const fs = require('fs');

            const API_SERVER = "https://api.sandbox.corporate-api.op.fi";

            const clientId = "TODO your oauth client id";
            const clientSecret = "TODO your oauth client secret";

            const mtlsKey = fs.readFileSync('TODO your encrypted mTLS private key filename');
            const mtlsCertificate = fs.readFileSync('TODO your mTLS certificate filename');
            const mtlsKeyPassphrase = "TODO your encrypted MTLS private key passphrase";

            // Main application logic
            (async () => {
              console.log("Getting access token..");
              // Get access token
              const token = await getAccessToken();
              console.log("response: " + token);
            })();

            // Function for retrieving access token
            async function getAccessToken() {
              const agent = new https.Agent({
                key: mtlsKey,
                cert: mtlsCertificate,
                passphrase: mtlsKeyPassphrase
              });

              try {
                // Call access token endpoint
                const response = await axios.post(`${API_SERVER}/corporate-oidc/v1/token`,
                                                  `grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`, {
                  headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  httpsAgent: agent
                });
                return response.data.access_token;
              } catch (error) {
                console.error("Error getting access token:", error);
              }
            }
        - lang: PHP
          source: |
            <?php
            /******************************************************************************

              OP Corporate Banking API Token management - Generate access token PHP code example

              This is an example PHP script for using Generate access token endpoint.

              Note, This code assumes that you have the guzzlehttp/guzzle package installed
              for making HTTP requests! You can install it with Composer:

                composer require guzzlehttp/guzzle

                (Make sure you have installed php curl extension.)

              Steps for registering the required keys and certificates
              1. Valid Corporate API contract created in OP API Admin
              2. OAuth clientId and clientSecret provisioned
              3. MTLS private key generated: openssl genrsa -out sandbox-mtls.key 4096
              4. MTLS certificate signing request (CN and other attributes are ignored): openssl req -new -key sandbox-mtls.key -out sandbox-mtls.csr
              5. Valid MTLS certificate downloaded from OP API Admin as file "sandbox-mtls.crt" by uploading the certificate signing request (CSR) from the previous step

            *******************************************************************************/

            require 'vendor/autoload.php';

            use GuzzleHttp\Client;
            use GuzzleHttp\Exception\GuzzleException;
            use GuzzleHttp\RequestOptions;

            $apiUrl = 'api.sandbox.corporate-api.op.fi';

            // OAuth credentials
            $clientId = 'TODO: Your client id';
            $clientSecret = 'TODO: Your client secret';
            $mtlsCert = 'TODO: Your MTLS cert file name / path';
            $mtlsKey = 'TODO: Your encrypted mTLS private key file name / path';
            $mtlsKeyPassPhrase = 'TODO: Your encrypted mTLS private key pass phrase';

            // Initialize client with MTLS
            $client = new Client([
                'base_uri' => "https://$apiUrl",
                'cert' => $mtlsCert,
                'ssl_key' => array($mtlsKey, $mtlsKeyPassPhrase)
            ]);

            // #########
            // Get token
            // #########
            echo "Getting access token\n";
            try {
                $response = $client->post('/corporate-oidc/v1/token', [
                    'form_params' => [
                        'grant_type' => 'client_credentials',
                        'client_id' => $clientId,
                        'client_secret' => $clientSecret
                    ]
                ]);
                $data = json_decode((string)$response->getBody(), true);
                $accessToken = $data['access_token'];
                echo "Access token is: $accessToken\n\n";
            } catch (GuzzleException $e) {
                echo $e->getMessage();
            }

            ?>
        - lang: Python
          label: Python
          source: |
            """
            OP Corporate Banking API Token management - Generate access token Python example script

            Note, This code assumes that you have the python and requests library installed
            for making HTTP requests.

            Steps for registering the required keys and certificates
            1. Valid Corporate API contract created in OP API Admin
            2. OAuth clientId and clientSecret provisioned
            3. MTLS private key generated: openssl genrsa -out sandbox-mtls.key 4096
            4. MTLS certificate signing request (CN and other attributes are ignored):
                openssl req -new -key sandbox-mtls.key -out sandbox-mtls.csr
            5. Valid MTLS certificate downloaded from OP API Admin as file "sandbox-mtls.crt"
                by uploading the certificate signing request (CSR) from the previous step
            """

            import base64
            import json
            import ssl
            import time
            import uuid
            import requests
            from cryptography.hazmat.backends import default_backend
            from cryptography.hazmat.primitives import serialization, hashes
            from cryptography.hazmat.primitives.asymmetric import padding

            REST_TIMEOUT = 20
            API_HOST = 'https://api.sandbox.corporate-api.op.fi'

            # OAuth credentials
            CLIENT_ID = 'TODO: your oauth client id'
            CLIENT_SECRET = 'TODO: your oauth client secret'

            # TLS credentials and signing key
            TLS_KEY = 'TODO: your private key filename'
            TLS_CERTIFICATE = 'TODO: your TLS certificate filename'

            # Get access token
            print('Getting access token')
            token_url = f'{API_HOST}/corporate-oidc/v1/token'
            token_headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
            token_payload = {'grant_type': 'client_credentials', 'client_id': CLIENT_ID,
                             'client_secret': CLIENT_SECRET}
            response = requests.post(token_url, headers=token_headers, data=token_payload,
                                     cert=(TLS_CERTIFICATE, TLS_KEY), timeout=REST_TIMEOUT)
            token = response.json()['access_token']
            print(f'Access token is: {token}')
      responses:
        '200':
          description: Access token generated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/generateAccessTokenResponse'
        '400':
          description: 'Bad Request. Invalid or missing request headers, parameters and/or payload.'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/errorMessage'
              examples:
                grantTypeInvalid:
                  value:
                    error: grant_type_invalid
        '401':
          description: Unauthorized. Client is not authorized to generate an access token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/errorMessage'
              examples:
                grantTypeInvalid:
                  value:
                    error: grant_type_invalid
        '403':
          description: Forbidden. Client is not allowed to generate an access token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/errorMessage'
              examples:
                contractFrozen:
                  description: 'Contract frozen, please activate in OP API Admin'
                  value:
                    error: contract_freezed
                contractTerminated:
                  description: 'Contract terminated, please activate in OP API Admin'
                  value:
                    error: contract_freezed
                invalidCertificate:
                  description: 'TLS certificate invalid, please check'
                  value:
                    error: invalid_cert
                invalidCredentials:
                  description: 'Client ID or client secret invalid, please check'
                  value:
                    error: invalid_credentials
                missingCredentials:
                  description: 'Client ID or client secret missing, please check'
                  value:
                    error: missing_credentials
        '500':
          description: Internal Server Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/errorMessage'
              examples:
                Internal server error:
                  description: 'Internal server error, please try again later'
                  value:
                    error: internal_server_error
        '503':
          description: Service unavailable
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/errorMessage'
              examples:
                Service unavailable:
                  description: 'Service unavailable, please try again later'
                  value:
                    error: Service unavailable
components:
  schemas:
    generateAccessTokenRequest:
      required:
        - grant_type
        - client_id
        - client_secret
      type: object
      properties:
        grant_type:
          type: string
          description: 'Access token grant type, to be set always as ''client_credentials''.'
          enum:
            - client_credentials
          example: client_credentials
        client_id:
          type: string
          description: Client ID (to be retrieved from OP API Admin)
        client_secret:
          type: string
          description: Client secret (to be retrieved from OP API Admin)
      additionalProperties: false
      description: Access token generation request
    generateAccessTokenResponse:
      required:
        - access_token
        - token_type
        - expires_in
      type: object
      properties:
        access_token:
          type: string
          description: Access token
          example: eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZDQkMtSFM1MTIiLCJraWQiOiIxOGIxY2Y3NThjMWQ0ZWM2YmRhNjU4OTM1N2FiZGQ4NSIsInR5cCI6IkpXVCIsImN0eSI6IkpXVCJ9.gCbxP78o3DgpDTUQbuHniuGgYpATqgGkRGy7paC6hRrz7N7eIa6sAOWDO9Fhnj-c8ocMl4cF4Jb_mv5qRPCh9r57PBqx7jOhMIMPTwJGpjcyBaqtHlZlu1vupY5tQ3Y2jGz1Ti4BnywaeEHPyIPQJtN7F7hIAORzj7IY4sIKkVXtQJZgaKW8pEHq_GCqj8i5aaiM0uJnRG3GOh3livp9Npjv9doqp3gyPa1zjrg2H1RsOGn0j2QMGvtuVfkuNwF-SoPKFECyHOq0ZK1oH2sTO8-JwvHflbIZQr5xWTpS8q7MbUXEuqURtrg0Tj-2z6tdaOLT4b3UeDufK2ar3bBfRD4-nRALtoY0ekcMyGFOS7o1Mxl3hy5sIG-EySyWeuBVy68aDWDpi9qZoQuY1TbxxakjncCOGu_Gh1l1m_mK2l_IdyXCT_GCfzFq4ZTkPZ5eydNBAPZuxBLUb4BrMb5iDdZjT7AgGOlRre_wIRHmmKm8W9nDeQQRmbIXO23JuOw9.BDCarfq2r_Uk8DHNfsNwSQ.4DuQx1cfJXadHnudrVaBss45zxyd6iouuSzZUyOeM4ikF_7hDOgwmaCma-Z97_QZBJ5DzVn9SJhKUTAqpVR3BRGAxJ_HAXU5jaTjXqbvUaxsh7Z5TgZ9eck0FIoe1lkwv51xEvYqqQ_Xojr4MAEmLuME_9ArCK9mNaMADIzOj4VoQtaDP1l26ytocc-oENifBRYGu28LbJLkyQKzyQy6FuAOtWjLM0WCXV7-o_dvj6qfeYHNBD7YBSxyqdgD8dcxMBNd2sK73YsZPHEa0V1-8zz7hm3bH3tZelpwPWScqLLW_SUH586c0FVeI6ggvqzjfLZ_Y6eQibVSdXfOtJBk22QrLsuCXbRK8G1w9t23Pwu8ukUAw4v0l7HeaW_0SJyKSPQANRP83MyFbK7fmzTYaW9TYN2JrKN-PLpd2dIFSm2Ga_EfaCwNJBm4RDMzDNrf-O0AissvYyHb0WaALiCiFCogliYqLzRB6xDb-b4964M.J7WDOFLRRPJ7lLpTfN2mOiXLDg5xtaF-sLQ4mOeN5oc
        token_type:
          type: string
          description: Access token type. Always 'Bearer'.
          example: Bearer
        expires_in:
          type: integer
          description: Access token validity time (in seconds)
          example: 900
      additionalProperties: false
      description: Access token generation response
    errorMessage:
      required:
        - error
      type: object
      properties:
        error:
          type: string
          description: Human readable explanation about the error. API consumers shouldn't rely on the value of this field in the computational processes