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

# Credit Applications

> Get started with Credit Applications with our step-by-step guide.

export const HeroContent = ({children, withGrid}) => <div>
    <div className="not-prose relative bg-gray-50/50 rounded-xl overflow-hidden dark:bg-gray-800/25">
      {withGrid && <div className="absolute grid content-center inset-0 bg-grid-neutral-200/20 [mask-image:linear-gradient(0deg,#fff,rgba(255,255,255,0.6))] dark:bg-grid-white/5 dark:[mask-image:linear-gradient(0deg,rgba(255,255,255,0.1),rgba(255,255,255,0.5))]" style={{
  backgroundPosition: '10px 10px',
  color: '#070712'
}}></div>}
      <div className="relative rounded-xl overflow-hidden flex justify-center">{children}</div>
      <div className="absolute inset-0 pointer-events-none border border-black/5 rounded-xl dark:border-white/5"></div>
    </div>
  </div>;

export const StoryBoard = ({children}) => <div className="p-6 bg-gray-100/50 dark:bg-gray-800/25 rounded">
    <p className="text-base py-2 leading-6">{children}</p>
  </div>;

export const CustomCallout = ({children, variant, icon}) => <>
    {variant === 'tip' && <div className="my-4 px-5 py-4 overflow-hidden rounded-xl border border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10">
        <div className="flex items-start space-x-3">
          {icon && <div className="mt-0.5 w-4">
              <svg width="11" height="14" viewBox="0 0 11 14" fill="currentColor" xmlns="http://www.w3.org/2000/svg" className="text-emerald-600 dark:text-emerald-400/80 w-3.5 h-auto" aria-label="CustomTip">
                <path d="M3.12794 12.4232C3.12794 12.5954 3.1776 12.7634 3.27244 12.907L3.74114 13.6095C3.88471 13.8248 4.21067 14 4.46964 14H6.15606C6.41415 14 6.74017 13.825 6.88373 13.6095L7.3508 12.9073C7.43114 12.7859 7.49705 12.569 7.49705 12.4232L7.50055 11.3513H3.12521L3.12794 12.4232ZM5.31288 0C2.52414 0.00875889 0.5 2.26889 0.5 4.78826C0.5 6.00188 0.949566 7.10829 1.69119 7.95492C2.14321 8.47011 2.84901 9.54727 3.11919 10.4557C3.12005 10.4625 3.12175 10.4698 3.12261 10.4771H7.50342C7.50427 10.4698 7.50598 10.463 7.50684 10.4557C7.77688 9.54727 8.48281 8.47011 8.93484 7.95492C9.67728 7.13181 10.1258 6.02703 10.1258 4.78826C10.1258 2.15486 7.9709 0.000106649 5.31288 0ZM7.94902 7.11267C7.52078 7.60079 6.99082 8.37878 6.6077 9.18794H4.02051C3.63739 8.37878 3.10743 7.60079 2.67947 7.11294C2.11997 6.47551 1.8126 5.63599 1.8126 4.78826C1.8126 3.09829 3.12794 1.31944 5.28827 1.3126C7.2435 1.3126 8.81315 2.88226 8.81315 4.78826C8.81315 5.63599 8.50688 6.47551 7.94902 7.11267ZM4.87534 2.18767C3.66939 2.18767 2.68767 3.16939 2.68767 4.37534C2.68767 4.61719 2.88336 4.81288 3.12521 4.81288C3.36705 4.81288 3.56274 4.61599 3.56274 4.37534C3.56274 3.6515 4.1515 3.06274 4.87534 3.06274C5.11719 3.06274 5.31288 2.86727 5.31288 2.62548C5.31288 2.38369 5.11599 2.18767 4.87534 2.18767Z"></path>
              </svg>
            </div>}
          <div className="flex-1 text-sm prose text-wrap text-emerald-900 dark:text-emerald-200">
            {children}
          </div>
        </div>
      </div>}
    {variant === 'note' && <div className="my-4 px-5 py-4 overflow-hidden rounded-xl border border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10">
        <div className="flex items-start space-x-3">
          {icon && <div className="mt-0.5 w-4">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" xmlns="http://www.w3.org/2000/svg" className="w-4 h-4 text-sky-500" aria-label="CustomNote">
                <path fill-rule="evenodd" clip-rule="evenodd" d="M7 1.3C10.14 1.3 12.7 3.86 12.7 7C12.7 10.14 10.14 12.7 7 12.7C5.48908 12.6974 4.0408 12.096 2.97241 11.0276C1.90403 9.9592 1.30264 8.51092 1.3 7C1.3 3.86 3.86 1.3 7 1.3ZM7 0C3.14 0 0 3.14 0 7C0 10.86 3.14 14 7 14C10.86 14 14 10.86 14 7C14 3.14 10.86 0 7 0ZM8 3H6V8H8V3ZM8 9H6V11H8V9Z"></path>
              </svg>
            </div>}
          <div className="flex-1 text-sm prose text-wrap text-sky-900 dark:text-sky-200">
            {children}
          </div>
        </div>
      </div>}
    {variant === 'info' && <div className="my-4 px-5 py-4 overflow-hidden rounded-xl border border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10">
        <div className="flex items-start space-x-3">
          {icon && <div className="mt-0.5 w-4">
              <svg viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" className="flex-none w-5 h-5 text-zinc-400 dark:text-zinc-300" aria-label="CustomInfo">
                <path d="M8 0C3.58125 0 0 3.58125 0 8C0 12.4187 3.58125 16 8 16C12.4187 16 16 12.4187 16 8C16 3.58125 12.4187 0 8 0ZM8 14.5C4.41563 14.5 1.5 11.5841 1.5 8C1.5 4.41594 4.41563 1.5 8 1.5C11.5844 1.5 14.5 4.41594 14.5 8C14.5 11.5841 11.5844 14.5 8 14.5ZM9.25 10.5H8.75V7.75C8.75 7.3375 8.41563 7 8 7H7C6.5875 7 6.25 7.3375 6.25 7.75C6.25 8.1625 6.5875 8.5 7 8.5H7.25V10.5H6.75C6.3375 10.5 6 10.8375 6 11.25C6 11.6625 6.3375 12 6.75 12H9.25C9.66406 12 10 11.6641 10 11.25C10 10.8359 9.66563 10.5 9.25 10.5ZM8 6C8.55219 6 9 5.55219 9 5C9 4.44781 8.55219 4 8 4C7.44781 4 7 4.44687 7 5C7 5.55313 7.44687 6 8 6Z"></path>
              </svg>
            </div>}
          <div className="flex-1 text-sm prose text-wrap text-zinc-900 dark:text-zinc-200">
            {children}
          </div>
        </div>
      </div>}
    {variant === 'warning' && <div className="my-4 px-5 py-4 overflow-hidden rounded-xl border border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10">
        <div className="flex items-start space-x-3">
          {icon && <div className="mt-0.5 w-4">
              <svg className="flex-none w-5 h-5 text-amber-400 dark:text-amber-300/80" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-label="CustomWarning">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
              </svg>
            </div>}
          <div className="flex-1 text-sm prose text-wrap text-amber-900 dark:text-amber-200">
            {children}
          </div>
        </div>
      </div>}
    {variant === 'check' && <div className="my-4 px-5 py-4 overflow-hidden rounded-xl border border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10">
        <div className="flex items-start space-x-3">
          {icon && <div className="mt-0.5 w-4">
              <svg className="text-green-600 dark:text-green-400/80 w-3.5 h-auto" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" aria-label="CustomCheck">
                <path d="M438.6 105.4C451.1 117.9 451.1 138.1 438.6 150.6L182.6 406.6C170.1 419.1 149.9 419.1 137.4 406.6L9.372 278.6C-3.124 266.1-3.124 245.9 9.372 233.4C21.87 220.9 42.13 220.9 54.63 233.4L159.1 338.7L393.4 105.4C405.9 92.88 426.1 92.88 438.6 105.4H438.6z"></path>
              </svg>
            </div>}
          <div className="flex-1 text-sm prose text-wrap text-emerald-900 dark:text-emerald-200">
            {children}
          </div>
        </div>
      </div>}
  </>;

<HeroContent withGrid>
  <img class="block" src="https://mintcdn.com/drivly/26Ex-nQxnySgQw-c/images/services/CreditApp.png?fit=max&auto=format&n=26Ex-nQxnySgQw-c&q=85&s=d4246d8c368a289a58debc7b760e30d7" alt="Credit Application Form" width="3377" height="1594" data-path="images/services/CreditApp.png" />
</HeroContent>

## Prerequisites

Before diving into the integration process, ensure you have the following:

1. [Sign up](https://drivly.typeform.com/applyforaccess) for a Drivly account
2. Create a [DRIVLY\_API\_KEY](/developers/auth)
3. Have a basic understanding of REST APIs
4. A secure environment for handling sensitive data

<Warning>Always perform Credit Application operations server-side to secure API keys.</Warning>

***

## Overview

The Credit Application process enables users to secure auto loans, providing them with information on loan amounts and interest rates. This guide covers various scenarios, including applications for primary applicants and co-applicants, with or without trade-ins.

***

## Implementation Options

You can implement the Credit Application API using either the Drivly SDK or the API:

<Accordion title="Drivly SDK">
  Follow the steps below to set up using the SDK.

  <Steps>
    <Step title="To get started, you will need to install the Drivly SDK.">
      <CodeGroup>
        ```bash Yarn theme={null}
        yarn add @drivly/commerce
        ```

        ```bash NPM theme={null}
        npm install @drivly/commerce
        ```

        ```bash PnPM theme={null}
        pnpm install @drivly/commerce
        ```

        ```bash Bun theme={null}
        bun add @drivly/commerce
        ```

        ```bash CDN theme={null}
        <script src="https://unpkg.com/@drivly/commerce"></script>
        ```
      </CodeGroup>

      <br />

      {' '}
    </Step>

    <Step title="Create a singleton instance of the SDK.">
      We will use the `DRIVLY_API_KEY` and will start in `sandbox`.

      ```javascript sdk.ts theme={null}
      import { SDK } from '@drivly/commerce'

      export const sdk = SDK({
        apiKey: process.env.DRIVLY_API_KEY as string,
        environment: 'sandbox',
      })
      ```

      <Note>Now, we can export the `sdk` to use in our application</Note>
    </Step>

    <Step title="Make a function to CREATE the Credit Application.">
      ```javascript credit.action.ts theme={null}
      'use server' // Next JS specific for server actions

      import { CreditApplication } from '@drivly/commerce'
      import { sdk } from './sdk'

      type CreditData = Omit<CreditApplication, 'id' | 'createdAt' | 'updatedAt'>

      export const createCreditApp = async (data: CreditData) => {
        try {
          // Change to 'Production' for live applications
          const environment = 'Development'

          const result = await sdk?.commerce.creditApplications.create({
            doc: { environment, ...data },
          })

          console.log(result)
        } catch (error) {
          console.error(error)
        }
      }
      ```
    </Step>

    <Step title="We might need to CREATE a Trade, we will need a few more functions.">
      In cases where a trade-in is involved, we need to create a trade record for the vehicle being traded.

      <CodeGroup>
        ```javascript trade.action.ts theme={null}
        'use server' // Next JS specific for server actions

        import { sdk } from './sdk'
        import { createLienholder, getLienholderId } from './lienholder.action'
        import { CreateTradeParams } from './shared.param.types'
        import { createCommerceVehicle, getCommerceVehicleId } from './vehicle.action'

        export const createTrade = (params: CreateTradeParams) => {
          try {
            const { data, id: creditApplication } = params
            const { lienholder: companyName, payoff, odometer, ...rest } = data
            let lienholder: string | undefined

            if (companyName) {
              const prevLien = await getLienholderId({ companyName })

              lienholder =
                prevLien !== 'Lienholder not found'
                  ? prevLien
                  : await createLienholder({ data: { companyName } })
            }

            const prevVehicleId = await getCommerceVehicleId(rest.vin as string)

            const vehicle =
              prevVehicleId !== 'Vehicle not found'
                ? prevVehicleId
                : await createCommerceVehicle({ data: rest })

            if (vehicle === 'Failed to create vehicle') throw new Error(vehicle)
            if (lienholder === 'Lienholder not created') throw new Error(lienholder)

            const result = await sdk?.commerce.trades.create({
              doc: {
                creditApplication, // Credit Application ID
                lienholder, // Lienholder ID
                odometer,
                tradeInPayoffBalance: payoff,
                vehicle, // Vehicle ID
              },
              depth: 0,
            })

            if (!result) throw new Error('Trade not created')

            return result.doc.id
          } catch (error) {
            console.error(error)
          }
        }
        ```

        ```javascript lienholder.action.ts theme={null}
        'use server' // Next JS specific for server actions

        import { sdk } from '../sdk'
        import { CreateLienholderParams, GetLienholderParams } from './shared.param.types'

        export async function createLienholder(params: CreateLienholderParams) {
          try {
            const {
              data: { companyName, companyType = ['Lender'] },
            } = params

            const result = await sdk?.commerce.customers.create({
              doc: { companyName, companyType },
            })

            if (!result?.doc) throw new Error('Lienholder not created')

            return result.doc.id
          } catch (error) {
            console.error(error)
          }
        }

        export async function getLienholderId(params: GetLienholderParams) {
          try {
            const { companyName } = params

            const result = await sdk?.commerce.customers.find({
              where: { companyName: { equals: companyName } },
            })

            if (!result?.docs?.[0]) throw new Error('Lienholder not found')

            return result.docs[0].id
          } catch (error) {
            console.error(error)
          }
        }
        ```

        ```javascript vehicle.action.ts theme={null}
        'use server' // Next JS specific for server actions

        import { sdk } from '../sdk'
        import { CreateCommerceVehicleParams } from './shared.param.types'

        export async function getCommerceVehicleId(vin: string) {
          try {
            const result = await sdk?.commerce.vehicles.find({
              where: { vin: { equals: vin } },
            })

            if (!result?.docs?.[0]?.id) throw new Error('Vehicle not found')

            return result.docs[0].id
          } catch (error) {
            console.error(error)
          }
        }

        export async function createCommerceVehicle(params: CreateCommerceVehicleParams) {
          try {
            const { data } = params

            const result = await sdk?.commerce.vehicles.create({ doc: data })

            if (!result) throw new Error('Failed to create vehicle')

            return result.doc.id
          } catch (error) {
            console.error(error)
          }
        }
        ```

        ```typescript shared.param.types.ts theme={null}
        import { Customer } from '@drivly/commerce'

        export interface CreateCommerceVehicleParams {
          data: {
            vin?: string | undefined
            year?: string | undefined
            make?: string | undefined
            model?: string | undefined
            trim?: string | undefined
          }
        }

        export interface CreateTradeParams {
          id: string
          data: {
            vin?: string | undefined
            year?: string | undefined
            make?: string | undefined
            model?: string | undefined
            trim?: string | undefined
            odometer?: number | undefined
            payoff?: string | undefined
            lienholder?: string | undefined
          }
        }

        export interface CreateLienholderParams {
          data: Omit<Customer, 'id' | 'createdAt' | 'updatedAt'>
        }

        export interface GetLienholderParams {
          companyName: string
        }
        ```
      </CodeGroup>
    </Step>
  </Steps>
</Accordion>

<Accordion title="Use the API">
  We can use `https://commerce.driv.ly/api/creditApplications` to create and manage Credit Applications.

  <Steps>
    <Step title="Create an environment variable for your API Key.">
      ```bash .env theme={null}
      DRIVLY_API_KEY='YOUR_API_KEY'
      ```
    </Step>

    <Step title="Make a function to CREATE the Credit Application.">
      ```javascript credit.action.ts theme={null}
      import { CreditApplication } from '@drivly/commerce'

      type CreditData = Omit<CreditApplication, 'id' | 'createdAt' | 'updatedAt'>

      const url = 'https://commerce.driv.ly/api/creditApplications'

      export const createCreditApp = async (data: CreditData) => {
        try {
          // Change to 'Production' for live applications
          const environment = 'Development'

          const response = await fetch(url, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              Authorization: `${process.env.DRIVLY_API_KEY}`,
            },
            body: JSON.stringify({ environment, ...data }),
          }).then((res) => res.json())

          console.log(response)
        } catch (error) {
          console.error(error)
        }
      }
      ```
    </Step>

    <Step title="We might need to CREATE a Trade, we will need a few more functions.">
      In cases where a trade-in is involved, we need to create a trade record for the vehicle being traded.

      <CodeGroup>
        ```javascript trade.action.ts theme={null}
        import { createLienholder, getLienholderId } from './lienholder.action'
        import { CreateTradeParams } from './shared.param.types'
        import { createCommerceVehicle, getCommerceVehicleId } from './vehicle.action'

        const url = 'https://commerce.driv.ly/api/trades'

        export const createTrade = (params: CreateTradeParams) => {
          try {
            const { data, id: creditApplication } = params
            const { lienholder: companyName, payoff, odometer, ...rest } = data
            let lienholder: string | undefined

            if (companyName) {
              const prevLien = await getLienholderId({ companyName })

              lienholder =
                prevLien !== 'Lienholder not found'
                  ? prevLien
                  : await createLienholder({ data: { companyName } })
            }

            const prevVehicleId = await getCommerceVehicleId(rest.vin as string)

            const vehicle =
              prevVehicleId !== 'Vehicle not found'
                ? prevVehicleId
                : await createCommerceVehicle({ data: rest })

            if (vehicle === 'Failed to create vehicle') throw new Error(vehicle)
            if (lienholder === 'Lienholder not created') throw new Error(lienholder)

            const response = await fetch(url, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `${process.env.DRIVLY_API_KEY}`,
              },
              body: JSON.stringify({
                creditApplication, // Credit Application ID
                lienholder, // Lienholder ID
                odometer,
                tradeInPayoffBalance: payoff,
                vehicle, // Vehicle ID
              }),
            }).then((res) => res.json())

            if (!response?.doc) throw new Error('Trade not created')

            return response.doc.id
          } catch (error) {
            console.error(error)
          }
        }
        ```

        ```javascript lienholder.action.ts theme={null}
        import { CreateLienholderParams, GetLienholderParams } from './shared.param.types'

        const url = 'https://commerce.driv.ly/api/customers'

        export async function createLienholder(params: CreateLienholderParams) {
          try {
            const {
              data: { companyName, companyType = ['Lender'] },
            } = params

            const response = await fetch(url, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `${process.env.DRIVLY_API_KEY}`,
              },
              body: JSON.stringify({ companyName, companyType }),
            }).then((res) => res.json())

            if (!response?.doc) throw new Error('Lienholder not created')

            return response.doc.id
          } catch (error) {
            console.error(error)
          }
        }

        export async function getLienholderId(params: GetLienholderParams) {
          try {
            const { companyName } = params

            const response = await fetch(`${url}?where[companyName][equals]=${companyName}`, {
              method: 'GET',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `${process.env.DRIVLY_API_KEY}`,
              },
            }).then((res) => res.json())

            if (!response?.docs?.[0]) throw new Error('Lienholder not found')

            return response.docs[0].id
          } catch (error) {
            console.error(error)
          }
        }
        ```

        ```javascript vehicle.action.ts theme={null}
        import { CreateCommerceVehicleParams } from './shared.param.types'

        const url = 'https://commerce.driv.ly/api/vehicles'

        export async function getCommerceVehicleId(vin: string) {
          try {
            const response = await fetch(`${url}?where[vin][equals]=${vin}`, {
              method: 'GET',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `${process.env.DRIVLY_API_KEY}`,
              },
            }).then((res) => res.json())

            if (!response?.docs?.[0]) throw new Error('Vehicle not found')

            return response.docs[0].id
          } catch (error) {
            console.error(error)
          }
        }

        export async function createCommerceVehicle(params: CreateCommerceVehicleParams) {
          try {
            const { data } = params

            const response = await fetch(url, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                Authorization: `${process.env.DRIVLY_API_KEY}`,
              },
              body: JSON.stringify(data),
            }).then((res) => res.json())

            if (!response?.doc) throw new Error('Failed to create vehicle')

            return response.doc.id
          } catch (error) {
            console.error(error)
          }
        }
        ```

        ```typescript shared.param.types.ts theme={null}
        import { Customer } from '@drivly/commerce'

        export interface CreateCommerceVehicleParams {
          data: {
            vin?: string | undefined
            year?: string | undefined
            make?: string | undefined
            model?: string | undefined
            trim?: string | undefined
          }
        }

        export interface CreateTradeParams {
          id: string
          data: {
            vin?: string | undefined
            year?: string | undefined
            make?: string | undefined
            model?: string | undefined
            trim?: string | undefined
            odometer?: number | undefined
            payoff?: string | undefined
            lienholder?: string | undefined
          }
        }

        export interface CreateLienholderParams {
          data: Omit<Customer, 'id' | 'createdAt' | 'updatedAt'>
        }

        export interface GetLienholderParams {
          companyName: string
        }
        ```
      </CodeGroup>
    </Step>
  </Steps>
</Accordion>

***

## Handling Use Cases

The following scenarios will cover various Credit Application use cases including primary applicants, co-applicants, and trade-ins.

### Primary Applicant

<StoryBoard>
  Danny found the car of his dreams. He wants to secure a loan to buy the car. He goes to your
  website and fills out a form to find out how much of a loan he can secure.
</StoryBoard>

When a user, such as Danny, wishes to secure a loan for his dream car, follow these steps:

<Steps>
  <Step title="Direct the user to the Credit Application Form on your Website.">
    Make sure the form includes fields for the primary applicant's personal, residence, employment, and vehicle information.

    <Note>
      Also include fields for the application type, finance amount, pre-approval ID and has
      co-applicant.
    </Note>

    <ResponseField name="primaryApplicant" type="Applicant Object">
      <Accordion title="Applicant Properties">
        <ResponseField name="firstName" type="string" />

        <ResponseField name="lastName" type="string" />

        <ResponseField name="birthDate" type="string" />

        <ResponseField name="emailAddress" type="string" />

        <ResponseField name="cellPhone" type="string" />

        <ResponseField name="ssn" type="string" />

        <ResponseField name="relationshipType" type="enum<string> | null">
          Available options: `SPOUSE`, `RELATIVE`, `FRIEND`, or `null` (for primary applicant)
        </ResponseField>

        <ResponseField name="currentResidence | previousResidence" type="Residence Object">
          <Warning>
            If current monthsAtResidence \< 24, previousResidence is REQUIRED
          </Warning>

          <Accordion title="Residence Properties">
            <ResponseField name="monthlyPaymentAmount" type="number" />

            <ResponseField name="monthsAtResidence" type="number" />

            <ResponseField name="ownershipStatus" type="enum<string>">
              Available options: `RENT`, `OWN`, `RELATIVE_OWNED`
            </ResponseField>

            <ResponseField name="address" type="Address Object">
              <Accordion title="Address Properties">
                <ResponseField name="lineOne" type="string" />

                <ResponseField name="lineTwo" type="string" />

                <ResponseField name="city" type="string" />

                <ResponseField name="state" type="enum<string>">
                  Available options: `AL`, `AK`, `AZ`, `AR`, `CA`, `CO`, `CT`, `DE`, `FL`, `GA`, `HI`,
                  `ID`, `IL`, `IN`, `IA`, `KS`, `KY`, `LA`, `ME`, `MD`, `MA`, `MI`, `MN`, `MS`, `MO`,
                  `MT`, `NE`, `NV`, `NH`, `NJ`, `NM`, `NY`, `NC`, `ND`, O`H`, `OK`, `OR`, `PA`, `RI`,
                  `SC`, `SD`, `TN`, `TX`, `UT`, `VT`, `VA`, `WA`, `WV`, `WI`, `WY`
                </ResponseField>

                <ResponseField name="postalCode" type="string" />
              </Accordion>
            </ResponseField>
          </Accordion>
        </ResponseField>

        <ResponseField name="currentEmployment | previousEmployment" type="Employment Object">
          <Warning>
            If currentEmployment monthsAtEmployer \< 24, previousEmployment is REQUIRED
          </Warning>

          <Accordion title="Employment Properties">
            <ResponseField name="yearlyIncomeAmount" type="number" />

            <ResponseField name="monthsAtEmployer" type="number" />

            <ResponseField name="employmentType" type="enum<string>">
              Available options: `FULL_TIME`, `PART_TIME`, `SELF_EMPLOYED`, `UNEMPLOYED`, `RETIRED`
            </ResponseField>

            <ResponseField name="employerName" type="string" />

            <ResponseField name="employmentPosition" type="string" />

            <ResponseField name="employmentAddress" type="Address Object">
              <Accordion title="Address Properties">
                <ResponseField name="lineOne" type="string" />

                <ResponseField name="lineTwo" type="string" />

                <ResponseField name="city" type="string" />

                <ResponseField name="state" type="enum<string>">
                  Available options: `AL`, `AK`, `AZ`, `AR`, `CA`, `CO`, `CT`, `DE`, `FL`, `GA`, `HI`,
                  `ID`, `IL`, `IN`, `IA`, `KS`, `KY`, `LA`, `ME`, `MD`, `MA`, `MI`, `MN`, `MS`, `MO`,
                  `MT`, `NE`, `NV`, `NH`, `NJ`, `NM`, `NY`, `NC`, `ND`, O`H`, `OK`, `OR`, `PA`, `RI`,
                  `SC`, `SD`, `TN`, `TX`, `UT`, `VT`, `VA`, `WA`, `WV`, `WI`, `WY`
                </ResponseField>

                <ResponseField name="postalCode" type="string" />
              </Accordion>
            </ResponseField>
          </Accordion>
        </ResponseField>

        <ResponseField name="additionalIncomeAmount" type="number | null" />

        <ResponseField name="additionalIncomeFrequency" type="enum<string> | null">
          Available options: `WEEKLY`, `BI_WEEKLY`, `TWICE_MONTHLY`, `MONTHLY`, `YEARLY`
        </ResponseField>

        <ResponseField name="additionalIncomeSource" type="string | null" />

        <ResponseField name="terms" type="Terms Object">
          <Accordion title="Terms Properties">
            <ResponseField name="agreeToTerms" type="boolean" />

            <ResponseField name="agreeIP" type="string" />

            <ResponseField name="agreeUserAgent" type="string" />
          </Accordion>
        </ResponseField>
      </Accordion>
    </ResponseField>

    <ResponseField name="vehicle" type="Vehicle Object">
      <Accordion title="Vehicle Properties">
        <ResponseField name="vin" type="string" />

        <ResponseField name="year" type="number" />

        <ResponseField name="make" type="string" />

        <ResponseField name="model" type="string" />

        <ResponseField name="trim" type="string" />

        <ResponseField name="mileage" type="number" />

        <ResponseField name="lien" type="Lien Object">
          <Accordion title="Lien Properties">
            <ResponseField name="lienHolder" type="string | null" />

            <ResponseField name="monthlyPaymentAmount" type="number | null" />

            <ResponseField name="payoffAmount" type="number | null" />

            <ResponseField name="initialTerm" type="number | null" />

            <ResponseField name="remainingTerm" type="number | null" />

            <ResponseField name="originalAmount" type="number | null" />

            <ResponseField name="apr" type="number | null" />
          </Accordion>
        </ResponseField>
      </Accordion>
    </ResponseField>

    <ResponseField name="applicationType" type="enum<string>">
      Available options: `PURCHASE`, `REFINANCE`, `LEASE_BUYOUT`
    </ResponseField>

    <ResponseField name="hasCoApplicant" type="boolean" />

    <ResponseField name="financeAmount" type="number" />

    <ResponseField name="preApproval" type="string" />
  </Step>

  <Step title="Format your Request Body">
    Before sending the request, we need to include the following fields in the request body:

    * `sendTo`: The recipient of the application. Available options: `RouteOne`, `TSG`
    * `state`: Set to `DRAFT` in order to create a new application for processing.
    * `environment`: The application can be submitted in `Production` or `Development`

    ```javascript Example Data theme={null}
    const creditData = {
      sendTo: 'RouteOne',
      state: 'DRAFT',
      environment: 'Production',
      applicationType: 'REFINANCE',
      financeAmount: 65000,
      downPayment: 5000,
      preApproval: '123456',
      primaryApplicant: {
        firstName: 'Danny',
        lastName: 'Turner',
        birthDate: '06/24/1995',
        emailAddress: 'dannyt@gmail.com',
        cellPhone: '561-555-1212',
        ssn: '555-55-5555',
        currentResidence: {
          monthlyPaymentAmount: 3000,
          monthsAtResidence: 36,
          ownershipStatus: 'OWN',
          address: {
            lineOne: '123 Ocean Drive',
            lineTwo: 'Apt 2',
            city: 'Juno Beach',
            state: 'FL',
            postalCode: '33408',
          },
        },
        currentEmployment: {
          yearlyIncomeAmount: 100000,
          monthsAtEmployer: 48,
          employmentType: 'FULL_TIME',
          employerName: 'Loggerhead Marine Life Center',
          employmentPosition: 'Marine Biologist',
          employmentAddress: {
            lineOne: '14200 US-1',
            lineTwo: 'Suite 100',
            city: 'Juno Beach',
            state: 'FL',
            postalCode: '33408',
          },
        },
        terms: {
          agreeToTerms: true,
          agreeIP: '150.80.15.220',
          agreeUserAgent: 'Mozilla/5.0',
        },
      },
      hasCoApplicant: false,
      vehicle: {
        vin: 'W1NKM4HB4RF139674',
        year: 2024,
        make: 'Mercedes-Benz',
        model: 'GLC',
        trim: 'GLC 300 4MATIC',
        mileage: 20,
        lien: {
          lienHolder: null,
          monthlyPaymentAmount: null,
          payoffAmount: null,
          initialTerm: null,
          remainingTerm: null,
          originalAmount: null,
          apr: null,
        },
      },
    }
    ```
  </Step>

  <Step title="Send the Request.">
    Now that we have the data formatted, we can send the request to create the Credit Application.

    ```javascript theme={null}
    import { createCreditApp } from './credit.action'

    const creditAppId = await createCreditApp(creditData)
    console.log(creditAppId)
    ```

    <Warning>Always perform Credit Application operations server-side to secure API keys.</Warning>
  </Step>
</Steps>

***

### Primary and CoApplicant

<StoryBoard>
  Danny's wife Michelle found a car she loves. They want to secure a loan to buy the car. They go to
  your website and fill out a form to find out how much of a loan they can secure.
</StoryBoard>

When both Danny and Michelle want to secure a loan for a car they love, their journey through your website will be slightly different to account for the additional information needed from the co-applicant. Here's how to guide them:

<Steps>
  <Step title="Direct Both Applicants to the Credit Application Form.">
    Ensure your form is set up to handle input from both the primary applicant and the co-applicant. It's crucial to clearly label which sections pertain to each applicant to avoid confusion.

    <Note>Include identical fields for both the primary applicant and the co-applicant.</Note>
  </Step>

  <Step title="Collect and Format Data for Both Applicants.">
    While collecting the data, remember to gather information from both Danny and Michelle, treating Michelle's data as the coApplicant's or vice-versa. The data structure for the coApplicant will mirror that of the primaryApplicant.

    <Note>
      For the `relationshipType` in the coApplicant's data, select the appropriate option that describes
      their relationship to the primary applicant.
    </Note>

    ```javascript Format Data theme={null}
    const creditData = {
      sendTo: 'RouteOne',
      state: 'DRAFT',
      environment: 'Production',
      // Previous fields for primaryApplicant
      coApplicant: {
        // Repeat the fields from primaryApplicant,
        // filling in Michelle's information
      },
      hasCoApplicant: true,
      // Other necessary fields (vehicle, applicationType, etc.)
    }
    ```
  </Step>

  <Step title="Send the Request.">
    Now that we have the data formatted, we can send the request to create the Credit Application.

    ```javascript theme={null}
    import { createCreditApp } from './credit.action'

    const creditAppId = await createCreditApp(creditData)
    console.log(creditAppId)
    ```

    <Warning>Always perform Credit Application operations server-side to secure API keys.</Warning>
  </Step>
</Steps>

***

### Primary with Trade

<StoryBoard>
  Danny is looking to trade-in his 2011 Lincoln Town Car for a 2023 Genesis G80. He wants to secure
  a loan to buy the car and trade-in his old car. He goes to your website and fills out a form to
  find out how much of a loan he can secure.
</StoryBoard>

In cases where Danny is looking to trade in his current vehicle as part of securing a new loan, the process involves an additional step to include trade-in information.

<Steps>
  <Step title="Guide Danny to the Enhanced Credit Application Form.">
    Adjust your form to include a section for vehicle trade-in details.

    <ResponseField name="tradeInVehicle" type="Trade-In Object">
      <Accordion title="Trade-In Properties">
        <ResponseField name="vin" type="string" />

        <ResponseField name="year" type="string" />

        <ResponseField name="make" type="string" />

        <ResponseField name="model" type="string" />

        <ResponseField name="trim" type="string" />

        <ResponseField name="odometer" type="number" />

        <ResponseField name="payoff" type="string" />

        <ResponseField name="lienholder" type="string" />
      </Accordion>
    </ResponseField>

    Ensure the form includes fields for the primary applicant's personal, residence, employment, and vehicle information.
  </Step>

  <Step title="Collect Information Including Trade-In Details.">
    Apart from collecting the standard application information, you'll need to gather details about the vehicle Danny intends to trade.

    ```javascript tradeInData theme={null}
    const tradeInDetails = {
      make: 'Lincoln',
      model: 'Town Car',
      year: '2011',
      payoff: '7000',
      // Additional fields as necessary
    }
    ```
  </Step>

  <Step title="Create a Trade.">
    Before sending the Credit Application, you'll need to create a trade-in record for Danny's vehicle.

    ```javascript theme={null}
    import { createTrade } from './trade.action'

    const tradeInId = await createTrade(tradeInDetails)
    console.log(tradeInId)
    ```

    <Warning>Always perform Credit Application operations server-side to secure API keys.</Warning>
  </Step>

  <Step title="Send the Request with the tradeInId">
    ```javascript theme={null}
    const creditData = {
      sendTo: 'RouteOne',
      state: 'DRAFT',
      environment: 'Production',
      applicationType: 'PURCHASE',
      financeAmount: 65000,
      downPayment: 5000,
      primaryApplicant: {
        // Primary applicant data
      },
      vehicle: {
        // Vehicle data
      },
      trades: [tradeInId],
    }

    const creditAppId = await createCreditApp(creditData)
    console.log(creditAppId)
    ```
  </Step>
</Steps>

***

### Primary and CoApplicant with Trade

<StoryBoard>
  Danny and Michelle are looking to trade-in their 2011 Lincoln Town Car for a 2023 Genesis G80.
  They want to secure a loan to buy the car and trade-in their old car. They go to your website and
  fill out a form to find out how much of a loan they can secure.
</StoryBoard>

For scenarios involving both a primary and a co-applicant intending to trade in a vehicle, combine the steps and considerations from the previous scenarios.

<Steps>
  <Step title="Guide Both Applicants to the Enhanced Credit Application Form.">
    Ensure your form includes sections for both applicants and trade-in details. Ensure clarity and ease of navigation within the form.
  </Step>

  <Step title="Collect Information Including Trade-In Details.">
    Gather information from both Danny and Michelle, including details about the vehicle they intend to trade.
  </Step>

  <Step title="Create a Trade.">
    Before sending the Credit Application, create a trade-in record for the vehicle Danny and Michelle intend to trade.

    ```javascript theme={null}
    import { createTrade } from './trade.action'

    const tradeInId = await createTrade(tradeInDetails)
    console.log(tradeInId)
    ```
  </Step>

  <Step title="Send the Request with the tradeInId">
    ```javascript theme={null}
    const creditData = {
      sendTo: 'RouteOne',
      state: 'DRAFT',
      environment: 'Production',
      applicationType: 'PURCHASE',
      financeAmount: 65000,
      downPayment: 5000,
      primaryApplicant: {
        // Primary applicant data
      },
      coApplicant: {
        // Co-applicant data
      },
      vehicle: {
        // Vehicle data
      },
      trades: [tradeInId],
    }

    const creditAppId = await createCreditApp(creditData)
    console.log(creditAppId)
    ```
  </Step>
</Steps>

***

## Conclusion

Congratulations! You've successfully integrated Credit Applications into your platform.

By following this guide, you've learned how to handle various scenarios, including primary applicants, co-applicants, and trade-ins. You're now equipped to provide a seamless experience for users looking to secure auto loans.

If you have any questions or need further assistance, please don't hesitate to reach out to our [support team](mailto:sales@driv.ly). Happy coding!

***

## Next Steps

Ready to get started with Credit Applications?

<Card icon="book" href="/services/reference/credit-app" title="Credit Application API Reference">
  Explore the Credit Application API to find, create, and manage credit applications.
</Card>
