Agent toolkit quickstart guide

Last updated: Apr 24th, 6:55pm

Introduction

PayPal's agent toolkit supports the integration of PayPal APIs into agentic workflows using OpenAI's Agents SDKVercel's AI SDKModel 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.

    1npm 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.

      1PAYPAL_CLIENT_ID=your-paypal-client-id
      2PAYPAL_CLIENT_SECRET=your-paypal-client-secret
      3OPENAI_API_KEY=your-openai-api-key

      Initialization

      Initialize the agent toolkit. 

        1import { PayPalAgentToolkit } from '@paypal/agent-toolkit/ai-sdk';
        2
        3const paypalToolkit = new PayPalAgentToolkit({
        4 clientId: process.env.PAYPAL_CLIENT_ID,
        5 clientSecret: process.env.PAYPAL_CLIENT_SECRET,
        6 configuration: {
        7 actions: {
        8 invoices: { create: true, list: true },
        9 orders: { create: true, get: true },
        10 // Add other tools/modules you need
        11 },
        12 },
        13});
        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. 

          1npx create-next-app@latest paypal-integration --typescript
          2cd paypal-integration
          3npm install

          Create a chat interface

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

            1import React, { useState } from 'react';
            2
            3const Home: React.FC = () => {
            4 const [message, setMessage] = useState('');
            5 const [chat, setChat] = useState<{ sender: 'user' | 'agent'; text: string }[]>([]);
            6
            7 const handleSendMessage = async () => {
            8 setChat((prevChat) => [...prevChat, { sender: 'user', text: message }]);
            9 const response = await fetch('/api/chat', {
            10 method: 'POST',
            11 headers: { 'Content-Type': 'application/json' },
            12 body: JSON.stringify({ message }),
            13 });
            14 const data = await response.json();
            15 setChat((prevChat) => [...prevChat, { sender: 'agent', text: data.response }]);
            16 setMessage('');
            17 };
            18
            19 return (
            20 <div>
            21 <h1>PayPal Chat Interface</h1>
            22 <div>
            23 {chat.map((c, index) => (
            24 <div key={index} className={c.sender}>
            25 {c.sender}: {c.text}
            26 </div>
            27 ))}
            28 </div>
            29 <input
            30 type="text"
            31 value={message}
            32 onChange={(e) => setMessage(e.target.value)}
            33 />
            34 <button onClick={handleSendMessage}>Send</button>
            35 </div>
            36 );
            37};
            38
            39export 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.

              1import { NextRequest, NextResponse } from 'next/server';
              2import { openai } from '@ai-sdk/openai';
              3import { generateText } from 'ai';
              4import { PayPalAgentToolkit } from '@paypal/agent-toolkit/ai-sdk';
              5
              6const paypalToolkit = new PayPalAgentToolkit({
              7 clientId: process.env.PAYPAL_CLIENT_ID,
              8 clientSecret: process.env.PAYPAL_CLIENT_SECRET,
              9 configuration: {
              10 actions: {
              11 orders: { create: true, get: true },
              12 invoices: { create: true, list: true },
              13 // Extend with other actions as needed
              14 },
              15 },
              16});
              17
              18export async function POST(req: NextRequest) {
              19 try {
              20 const { message } = await req.json();
              21
              22 // Define System Prompt for controlling behavior
              23 const systemPrompt = 'This is a PayPal agent. You are tasked with handling PayPal orders and providing relevant information.';
              24
              25 const { text: response } = await generateText({
              26 model: openai('gpt-4o'),
              27 tools: paypalToolkit.getTools(),
              28 maxSteps: 10,
              29 prompt: message,
              30 system: systemPrompt,
              31 });
              32
              33 return NextResponse.json({ response });
              34 } catch (error) {
              35 const errorMessage = error instanceof Error
              36 ? error.message
              37 : 'An unknown error occurred';
              38
              39 return NextResponse.json(
              40 { error: errorMessage },
              41 { status: 500 }
              42 );
              43 }
              44}
              4

              Start the application

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

              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: 

              If you accept cookies, we’ll use them to improve and customize your experience and enable our partners to show you personalized PayPal ads when you visit other sites. Manage cookies and learn more