Quickstart

PayPal's agent toolkit supports the integration of PayPal APIs into agentic workflows using OpenAI's Agents SDK, Vercel's AI SDK, Model Context Protocol (MCP), LangChain, and CrewAI.

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.

1

Set up the server

Complete these steps to set up the server and begin your integration.

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.

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.

.env.local
PAYPAL_CLIENT_ID=your-paypal-client-id
PAYPAL_CLIENT_SECRET=your-paypal-client-secret
OPENAI_API_KEY=your-openai-api-key

Initialization

Initialize the agent toolkit.

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
    },
  },
});

For a complete list of the tools that PayPal's agent toolkit includes, see the list of available tools in the Agent toolkit documentation.

2

Build the front end

Using the Next.js framework, complete the following tasks.

Install Next.js

If you don't have a Next.js app already, create one.

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.

app/page.tsx
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;
3

Test the integration

After you finish the integration, test it by setting up an API route.

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

app/api/chat/route.ts
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 }
    );
  }
}
4

Start the application

To start the application, execute npm run dev, and visit http://localhost:3000.

5

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.

  1. Create an OpenAI account, and complete all registration steps.

  2. Generate your API keys:

    1. Log into OpenAI, and navigate to the API Keys section of your account.

    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.

Best practices

To have the best integration experience, follow these tips:

  • 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:

Was this helpful?