# Quickstart

PayPal's agent toolkit supports the integration of PayPal APIs into agentic workflows using [OpenAI's Agents SDK](https://github.com/openai/openai-agents-python), [Vercel's AI SDK](https://sdk.vercel.ai/), [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction), [LangChain](https://www.langchain.com/), and [CrewAI](https://www.crewai.com/).&#x20;

This guide provides a step-by-step process for setting up the server, building a basic conversational front-end interface using Next.js, and testing the integration. It also includes best practices to follow for secure and efficient usage.

{% stepper %}
{% step %}

## Set up the server

Complete these steps to set up the server and begin your integration.&#x20;

### Installation

Ensure that Node.js version 18 or later is installed, then run the following command to install PayPal's agent toolkit and other necessary packages.

```sh
npm install @paypal/agent-toolkit @ai-sdk/openai ai
```

### Configuration

Create a local environment (`.env.local`) file in your project root, and add your PayPal API and OpenAI [credentials](https://github.com/openai/openai-agents-python).

{% code title=".env.local" %}

```
PAYPAL_CLIENT_ID=your-paypal-client-id
PAYPAL_CLIENT_SECRET=your-paypal-client-secret
OPENAI_API_KEY=your-openai-api-key
```

{% endcode %}

### Initialization

Initialize the agent toolkit.&#x20;

{% code lineNumbers="true" %}

```javascript
import { PayPalAgentToolkit } from '@paypal/agent-toolkit/ai-sdk';

const paypalToolkit = new PayPalAgentToolkit({
  clientId: process.env.PAYPAL_CLIENT_ID,
  clientSecret: process.env.PAYPAL_CLIENT_SECRET,
  configuration: {
    actions: {
      invoices: { create: true, list: true },
      orders: { create: true, get: true },
      // Add other tools/modules you need
    },
  },
});
```

{% endcode %}

{% hint style="info" %}
For a complete list of the tools that PayPal's agent toolkit includes, see the list of [available tools](/agent-toolkit-and-mcp-server/available-tools.md) in the [Agent toolkit documentation](/agent-toolkit-and-mcp-server/agent-toolkit/quickstart.md).
{% endhint %}
{% endstep %}

{% step %}

## Build the front end

Using the Next.js framework, complete the following tasks.&#x20;

### Install Next.js

If you don't have a Next.js app already, create one.&#x20;

```sh
npx create-next-app@latest paypal-integration --typescript
cd paypal-integration
npm install
```

### Create a chat interface

Modify `app/page.tsx` to create a chat interface for interacting with the PayPal agent.

{% code title="app/page.tsx" lineNumbers="true" %}

```javascript
import React, { useState } from 'react';

const Home: React.FC = () => {
  const [message, setMessage] = useState('');
  const [chat, setChat] = useState<{ sender: 'user' | 'agent'; text: string }[]>([]);

  const handleSendMessage = async () => {
    setChat((prevChat) => [...prevChat, { sender: 'user', text: message }]);
    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message }),
    });
    const data = await response.json();
    setChat((prevChat) => [...prevChat, { sender: 'agent', text: data.response }]);
    setMessage('');
  };

  return (
    <div>
      <h1>PayPal Chat Interface</h1>
      <div>
        {chat.map((c, index) => (
          <div key={index} className={c.sender}>
            {c.sender}: {c.text}
          </div>
        ))}
      </div>
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
      />
      <button onClick={handleSendMessage}>Send</button>
    </div>
  );
};

export default Home;
```

{% endcode %}
{% endstep %}

{% step %}

## Test the integration

After you finish the integration, test it by setting up an API route.&#x20;

Execute this code in `app/api/chat/route.ts`.

{% code title="app/api/chat/route.ts" lineNumbers="true" %}

```javascript
import { NextRequest, NextResponse } from 'next/server';
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
import { PayPalAgentToolkit } from '@paypal/agent-toolkit/ai-sdk';

const paypalToolkit = new PayPalAgentToolkit({
  clientId: process.env.PAYPAL_CLIENT_ID,
  clientSecret: process.env.PAYPAL_CLIENT_SECRET,
  configuration: {
    actions: {
      orders: { create: true, get: true },
      invoices: { create: true, list: true },
      // Extend with other actions as needed
    },
  },
});

export async function POST(req: NextRequest) {
  try {
    const { message } = await req.json();

    // Define System Prompt for controlling behavior
    const systemPrompt = 'This is a PayPal agent. You are tasked with handling PayPal orders and providing relevant information.';

    const { text: response } = await generateText({
      model: openai('gpt-4o'),
      tools: paypalToolkit.getTools(),
      maxSteps: 10,
      prompt: message,
      system: systemPrompt,
    });

    return NextResponse.json({ response });
  } catch (error) {
    const errorMessage = error instanceof Error
        ? error.message
        : 'An unknown error occurred';

    return NextResponse.json(
        { error: errorMessage },
        { status: 500 }
    );
  }
}
```

{% endcode %}
{% endstep %}

{% step %}

## Start the application

To start the application, execute `npm run dev`, and visit `http://localhost:3000`. &#x20;
{% endstep %}

{% step %}

## Get OpenAI API keys

Complete the following steps to generate and store your OpenAI keys to use in your integration with PayPal's agent toolkit.&#x20;

1. Create an [OpenAI](https://platform.openai.com/signup) account, and complete all registration steps.&#x20;
2. Generate your API keys:&#x20;
   1. Log into OpenAI, and navigate to the [API Keys](https://platform.openai.com/account/api-keys) section of your account.&#x20;
   2. Select Create a new secret key.
   3. Save the generated key securely. You use this key in your `env.local` file for your agent toolkit integration.&#x20;
      {% endstep %}
      {% endstepper %}

## Best practices

To have the best integration experience, follow these tips:&#x20;

* **Sandbox environment:** Always use the sandbox environment for initial testing to avoid real transactions.
* **API keys:** Keep client ID, client secret, and API keys secure. Do not hard-code them in your source files.
* **Environment variables:** Use environment variables to manage sensitive data.
* **Error handling:** Implement robust error handling to ensure reliable integration.
* **System prompts:** Use well-defined system prompts to control the behavior of the agent effectively.

## Additional resources

For more information about the concepts covered here, see these additional documents:&#x20;

* [PayPal Developer Documentation](https://developer.paypal.com/docs/api/overview/)
* [GitHub examples](https://github.com/paypal/agent-toolkit/tree/main/typescript/examples)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://paypal.gitbook.com/agent-toolkit-and-mcp-server/agent-toolkit/quickstart.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
