> ## Documentation Index
> Fetch the complete documentation index at: https://moneykit.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Developing with MoneyKit

> Learn how to integrate MoneyKit into your application.

## API Keys and Environments

There are two different MoneyKit API environments that both live within a single URL, and each environment will have its own pair of API keys for authenticating your requests.

<Note>
  The environment you use will be determined by which pair of API keys you use to authenticate your API request.
</Note>

### MoneyKit API URL

`api.moneykit.com`

### Environments

<AccordionGroup>
  <Accordion title="Sandbox" icon="flask">
    The Sandbox environment allows you to get testing quickly, providing three different test institutions that return rich data.

    #### Credentials Bank

    The Credentials Bank allows you to test a standard credential entry linking flow.

    **Test credentials:**

    * Username: `user_good`
    * Password: `pass_good`

    #### Instant Bank

    Instant Bank will get you testing the fastest, bypassing any credential entry and linking instantly.

    #### OAuth Bank

    The OAuth Bank will help to get your OAuth flow setup and tested in the sandbox environment, so you’re ready to redirect live institutions back to your application when the time comes.
  </Accordion>

  <Accordion title="Live" icon="rocket" defaultOpen>
    The Live environment allows for linking with live banks, **this is the environment you want to use with your production application.**

    For testing the Live environment, you can request a pair of trial API keys. Trial keys contain a limited number of live links that can be created free of charge. When you hit the limit of free links you can create with your Trial keys, you can disconnect those links to get testing again.
  </Accordion>
</AccordionGroup>

## Front End SDKs

MoneyKit’s front end SDK for linking bank accounts is called **Connect**.

**Connect SDK is currently available for:**

<CardGroup cols={3}>
  <Card title="iOS" icon="apple" href="https://github.com/moneykit/moneykit-ios">
    Swift
  </Card>

  <Card title="Web" icon="react" href="https://github.com/moneykit/connect-js">
    React
  </Card>

  <Card title="React Native" icon="react" href="https://github.com/moneykit/moneykit-react-native">
    iOS • Android • Expo
  </Card>
</CardGroup>

The Connect SDK will take in your various configurations for the bank linking experience like your theme and product
requirements, and will keep you informed of the end user’s linking experience through event callbacks.

A successful linking experience will return you a temporary `exchangeable_token` in the success callback, that you will then exchange with the MoneyKit API for a long-lived `link_id`.

## Creating your first MoneyKit Link

A [Link](/links/get-link-details) is what is created when one of your end users successfully links their bank accounts with your MoneyKit integration.

<Tip>
  Every Link has a `link_id`, and this is what you will use to identify those accounts when fetching product data from
  the MoneyKit API.{" "}
</Tip>

From a developer perspective, it only takes 5 steps to create a link and then fetch data for it.

1. Create a Bearer token to authenticate your requests to `api.moneykit.com`
2. Create a `link_session_token` with your custom configurations for the linking session
3. Pass the `link_session_token` to the **Connect SDK** in your front end application to launch the linking experience
4. Pass the temporary `exchangeable_token` received from the SDK’s success callback to the MoneyKit API to receive a `link_id` for the new [Link](/links/get-link-details).
5. Use the `link_id` with your requests to the MoneyKit product endpoints to fetch data for the link

**Below is a walkthrough of these five steps including code examples.**

<Accordion title="Walkthrough" icon="book">
  ### 1. Create a Bearer token for API request authentication

  Create an `access_token` to use MoneyKit.
  POST your `client_id` and `client_secret` to [/auth/token](/authentication/auth-token) to receive an `access_token` for API authentication.

  <CodeGroup>
    ```bash Request
    curl --request POST \
      --url "https://api.moneykit.com/auth/token" \
      --header "accept: application/json" \
      --header "content-type: application/x-www-form-urlencoded"
      --data "grant_type: client_credentials"
      --data "client_id: production_YKI24W"
      --data "client_secret: MKR239dj393"
    ```

    ```json Response
    {
      "access_token": "52ea3d1b4f9a53fffb67",
      "token_type": "bearer",
      "expires_in": 3600
    }
    ```
  </CodeGroup>

  ### 2. Create a `link_session_token`

  A `link_session_token` is required for opening MoneyKit Connect in your front end application.
  POST your session settings to [/link-session](/link-session/create-link-session) to create a `link_session_token`.

  <CodeGroup>
    ```bash Request
    curl --request POST \
      --url 'https://api.moneykit.com/link-session' \
      --header 'accept: application/json' \
      --header 'content-type: application/json'
      --header 'Authorization: Bearer { 52ea3d1b4f9a53fffb67 }'
      --data 'settings: {'products':['account_numbers','transactions'],'countries':['US']}'
      --data 'customer_user: {'id': test_user_1}'
      --data 'redirect_uri: finwizard://oauth'
      --data 'webhook: https://finwizard.com/moneykit/hook'
    ```

    ```json Response
    {
      "link_session_token": "c7318ff7-257c-490e-8242-03a815b223b7"
    }
    ```
  </CodeGroup>

  ### 3. Launch the Connect SDK with your `link_session_token`

  * Open MoneyKit Connect with the `link_session_token`. To use MoneyKit Connect in your iOS app:
  * Install MoneyKit Connect via package manager or manual linking.
  * Create a `MKConfiguration` with the `link_session_token`.
  * Create a `MKLinkHandler` with the previously initialized `MKConfiguration`. The handler must be retained for the duration of the Money Link flow.
  * Open MoneyKit Connect by calling `presentInstitutionSelectionFlow(using:)` on the handler object. This will usually be done in a button's target action.
  * Use the `onSuccess` configuration callback to determine the link type and for new links extract the `MKExchangeableToken` from the linked institution.

  ```swift
  import UIKit
  import MoneyKit
  class StartViewController: UIViewController {

      let linkSessionToken: String = "c7318ff7-257c-490e-8242-03a815b223b7"
      var moneykitLinkHandler: MKLinkHandler?
      func presentMoneyKitConnect() {
          do {
              let config =  try MKConfiguration(

              sessionToken: linkSessionToken,
              onSuccess: { [self] successType in
                  switch successType {
                  case let .linked(linkedInstitution):
                      print("ready to exchange token")
                      exchangeTokenForLinkId(exchangeableToken: linkedInstitution.token)
                  case let .relinked(relinkedInstitution):
                      print("Did relink \(relinkedInstitution.institution.name) in MoneyKit ")
                  @unknown default:
                      print("unknown mk link success type")
                  }
              },
              onExit: {
                  print("MoneyKit flow was dismissed")
              },
              onEvent: { eventType in
                  print("MoneyKit event: \(eventType.name)")
              },
              onError: { errorType in
                  print("MoneyKit event: \(errorType.name)")
              })

              moneykitLinkHandler = MKLinkHandler(configuration: config)
              let presentationMethod = MKPresentationMethod.modal(presentingViewController: self)
              moneykitLinkHandler?.presentInstitutionSelectionFlow(using: presentationMethod)

          } catch let error {
              print("MoneyKit error: \(error.localizedDescription)")
          }
       }

      func exchangeTokenForLinkId(exchangeableToken: MKExchangeableToken) {
          print("MoneyKit exchangable_token: \(exchangeableToken.value)")
          // Pass the MKExchangeableToken to your server and call
          // POST /exchange-token to exchange it for a link_id
      }

       public func handleCallback(url: URL) {
          if let moneykitLinkHandler = moneykitLinkHandler {
              moneykitLinkHandler.continueFlow(from: url)
          }
      }
  }
  ```

  ### 4. Swap `exchangeable_token` for a `link_id`

  Exchange for `link_id`. POST the `exchangeable_token` from the successful link session to [/link-session/exchange-token](/link-session/exchange-token) in order to receive the `link_id` for the [link](/links/get-link-details).

  <CodeGroup>
    ```bash Request
    curl --request POST \
      --url 'https://api.moneykit.com/link-session/exchange-token' \
      --header 'accept: application/json' \
      --header 'content-type: application/json'
      --header 'Authorization: Bearer { 52ea3d1b4f9a53fffb67 }'
      --data 'exchangeable_token: { your_exchangeable_token }'
    ```

    ```json Response
    {
      "link_id": "mk_eqkWN34UEoa2NxyALG8pcV",
      "link": {
        "link_id": "mk_eqkWN34UEoa2NxyALG8pcV",
        "institution_id": "chase",
        "institution_name": "Chase",
        "provider": "mx",
        "state": "connected",
        "last_synced_at": "2023-02-16T09:14:11",
        "products": {
          "account_numbers": {
            "refreshed_at": "2023-02-16T09:14:11",
            "last_attempted_at": "2023-02-16T09:14:11"
          },
          "transactions": {
            "refreshed_at": "2023-02-16T09:14:11",
            "last_attempted_at": "2023-02-16T09:14:11"
          }
        }
      }
    }
    ```
  </CodeGroup>

  ### 5. Use the `link_id` with requests to MoneyKit API product endpoints

  Use the `link_id` to fetch data (for example, [/accounts](/accounts/get-link-accounts), [/transactions](/transactions/get-link-transactions)) for the link.
</Accordion>

## Open Connect Directly to an Institution’s Login Screen

In some cases you might want to bypass the Connect institution search screen, and launch the **Connect SDK** directly to a specific institution’s login screen.

To do this you want to **include the `institution_id` in your request** to `https://api.moneykit.com/link-session`.

```bash
curl --request POST \
  --url 'https://api.moneykit.com/link-session' \
  --header 'accept: application/json' \
  --header 'content-type: application/json'
  --header 'Authorization: Bearer { 52ea3d1b4f9a53fffb67 }'
  --data 'settings: {'products':['account_numbers','transactions'],'countries':['US']}'
  --data 'customer_user: {'id': test_user_1}'
  --data 'redirect_uri: finwizard://oauth'
  --data 'institution_id: chase' # <--- Include the institution_id
  --data 'webhook: https://finwizard.com/moneykit/hook'
```

## Re-authenticate a broken Link

If you receive an `auth_expired` error with one of your Links, this means the Link needs to be re-authenticated by the owner of those accounts. In order to launch the **Connect SDK** directly to that institution for a re-authentication flow, just include the respective `link_id` in your request to `https://api.moneykit.com/link-session`.

<Note>
  When re-authenticating a Link, there will be no `exchangable_token` returned by the Connect SDK success callback, and
  thus no need to call the MoneyKit exchange endpoint. Once the user successfully authenticates their accounts, you will
  be able to resume using the existing `link_id`.
</Note>

```bash
curl --request POST \
  --url 'https://api.moneykit.com/link-session' \
  --header 'accept: application/json' \
  --header 'content-type: application/json'
  --header 'Authorization: Bearer { 52ea3d1b4f9a53fffb67 }'
  --data 'settings: {'products':['account_numbers','transactions'],'countries':['US']}'
  --data 'customer_user: {'id': test_user_1}'
  --data 'redirect_uri: finwizard://oauth'
  --data 'existing_link_id: mk_gVLxQ8wapHsCpF4DwCadAw' # <--- Include the link_id as existing_link_id
  --data 'webhook: https://finwizard.com/moneykit/hook'
```

## Handle OAuth redirect

In order to successfully complete an OAuth linking experience, you will need to pass a redirect\_uri with your request to `https://api.moneykit.com/link-session`. Whatever URI you include is where MoneyKit will return the end user after they successfully complete an OAuth Link.

<Warning>
  It is imperative that the page in your application that is redirected to has implemented the `continue()` method for
  the **Connect SDK**. This ensures that the OAuth flow is completed.
</Warning>

### iOS Example

#### Scene Delegate code to handle incoming redirect

```swift
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    private var startViewController: StartViewController!

    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        if let urlContext = URLContexts.first {
            startViewController.handleCallback(url: urlContext.url)
        }
    }
}
```

#### ViewController using the Connect SDK to continue the OAuth flow

```swift
public func handleCallback(url: URL) {
    if let moneykitLinkHandler = moneykitLinkHandler {
        moneykitLinkHandler.continueFlow(from: url)
    }
}
```

### Web Example

Coming soon.

### React Native Example

Coming soon.
