Send leads from your AI-built app to Pipedrive: API token vs OAuth, persons, deals and webhooks

Disclaimer: Die Inhalte, die du auf dieser Seite siehst, wurden mit Hilfe von KI übersetzt. Wenn du Feedback zur Übersetzung hast, kontaktiere uns bitte.

Key takeaways:

  1. Use an API token for an integration with your own Pipedrive company; use OAuth when other Pipedrive companies will install your app.

  2. Call Pipedrive only from server code. Search for the person by email and the organization by name before creating anything, and store the Pipedrive IDs you get back.

  3. Custom fields are 40-character hash keys that differ per Pipedrive account. Look them up, keep them in configuration, never hard-code another account's keys.

  4. Pipedrive webhooks are not signed: protect the endpoint with HTTP basic auth, re-read the record through the API, and skip events you have already processed.

To send leads from an app built with Lovable, Bolt, Cursor or Claude Code to Pipedrive, run the Pipedrive calls in a server function (for example a Supabase Edge Function), authenticate with an API token if the integration only serves your own Pipedrive company, and search before you create. The function finds or creates the organization, finds or creates the person by email, then creates a lead or a deal linked to both. This guide shows that flow in TypeScript against Pipedrive's API v2, plus custom fields, webhooks back into your app, and the rate limits you will meet.

Every endpoint and field below was checked against Pipedrive's API reference and developer guides as of November 2026.

API token or OAuth: which one do you need?

  • API token. Right when you connect your own app to your own Pipedrive company: a sign-up form, a booking flow, an internal tool. The token is sent in the x-api-token header on every request (authentication docs). It acts as the user who owns it, so create a dedicated Pipedrive user for the integration if your plan allows, rather than using the CEO's personal token.
  • OAuth 2.0. Required when you build an app that other Pipedrive companies install, including Marketplace apps. Users authorize at https://oauth.pipedrive.com/oauth/authorize, you exchange the code at https://oauth.pipedrive.com/oauth/token, and you call the API on the api_domain returned with the token. Access tokens expire after 60 minutes; refresh tokens expire if unused for 60 days (OAuth guide). OAuth apps also get higher burst limits.

Rule of thumb: one company, your own data, API token. Many companies, or you are selling the integration, OAuth.

What should the architecture look like?

  1. The user submits a form in your React app. The app saves it in your own database first (a leads table), so nothing is lost if Pipedrive is slow or down.
  2. A server function reads the saved row and syncs it to Pipedrive. Trigger it right after the insert, from a database webhook, or from a scheduled job that picks up unsynced rows.
  3. The function writes the Pipedrive IDs (person, organization, lead or deal) back onto your row. That row is your duplicate guard and your audit trail.

Never call Pipedrive from the browser: the token would be public, and anyone could write into your CRM.

supabase secrets set PIPEDRIVE_API_TOKEN=...
supabase secrets set PIPEDRIVE_COMPANY_DOMAIN=yourcompany

Which API version should you use?

Use API v2 where it exists. Pipedrive lists Persons, Organizations, Deals and Search (plus Activities, Products, Pipelines, Stages and the field endpoints) as available in v2, and says the matching v1 endpoints get a grace period of at least one year after deprecation (API v2 overview). Creating a lead is still a v1 endpoint; v2 has lead search but no lead create at the time of writing. On your company domain, v2 paths start with /api/v2/ and v1 paths with /api/v1/.

A small, safe Pipedrive client

// supabase/functions/_shared/pipedrive.ts
const BASE = `https://${Deno.env.get('PIPEDRIVE_COMPANY_DOMAIN')}.pipedrive.com`;
const TOKEN = Deno.env.get('PIPEDRIVE_API_TOKEN')!;

export class RetryLater extends Error {}

export async function pd(path: string, init: RequestInit = {}) {
  const res = await fetch(`${BASE}${path}`, {
    ...init,
    headers: {
      'x-api-token': TOKEN,
      'Content-Type': 'application/json',
      ...(init.headers ?? {}),
    },
  });
  if (res.status === 429) throw new RetryLater('Pipedrive rate limit reached');
  const json = await res.json();
  if (!res.ok || json.success === false) {
    throw new Error(`Pipedrive ${res.status} on ${path}: ${JSON.stringify(json)}`);
  }
  return json;
}

How do you create a person, organization and deal without duplicates?

Pipedrive will happily create a second "Jane Doe" with the same email. Duplicates are your job to prevent. Search first, using exact matching:

import { pd } from './pipedrive.ts';

export async function findOrCreateOrganization(name: string): Promise<number> {
  const q = new URLSearchParams({ term: name, fields: 'name', exact_match: 'true', limit: '1' });
  const found = await pd(`/api/v2/organizations/search?${q}`);
  if (found.data.items.length > 0) return found.data.items[0].item.id;

  const created = await pd('/api/v2/organizations', {
    method: 'POST',
    body: JSON.stringify({ name }),
  });
  return created.data.id;
}

export async function findOrCreatePerson(input: {
  name: string; email: string; phone?: string; orgId?: number;
}): Promise<number> {
  const q = new URLSearchParams({ term: input.email, fields: 'email', exact_match: 'true', limit: '1' });
  const found = await pd(`/api/v2/persons/search?${q}`);
  if (found.data.items.length > 0) return found.data.items[0].item.id;

  const created = await pd('/api/v2/persons', {
    method: 'POST',
    body: JSON.stringify({
      name: input.name,
      org_id: input.orgId,
      emails: [{ value: input.email, primary: true, label: 'work' }],
      phones: input.phone ? [{ value: input.phone, primary: true, label: 'work' }] : undefined,
    }),
  });
  return created.data.id;
}

Then create either a deal (goes straight into a pipeline stage) or a lead (lands in the Leads Inbox for qualification):

// Deal: API v2
const deal = await pd('/api/v2/deals', {
  method: 'POST',
  body: JSON.stringify({
    title: `${company} - website sign-up`,
    person_id: personId,
    org_id: orgId,
    pipeline_id: Number(Deno.env.get('PIPEDRIVE_PIPELINE_ID')),
    stage_id: Number(Deno.env.get('PIPEDRIVE_STAGE_ID')),
    value: 0,
    currency: 'EUR',
    origin_id: 'my-app-signup', // marks which integration created it
  }),
});

// Lead: API v1. Needs a person_id or an organization_id.
const lead = await pd('/api/v1/leads', {
  method: 'POST',
  body: JSON.stringify({
    title: `${company} - website sign-up`,
    person_id: personId,
    organization_id: orgId,
    origin_id: 'my-app-signup',
  }),
});

Get pipeline and stage IDs once from GET /api/v2/pipelines and GET /api/v2/stages and keep them in configuration. Note that v2 deals use org_id while v1 leads use organization_id, and a lead's value is an object such as { "amount": 200, "currency": "EUR" }.

Search alone is not a full duplicate guard. Two submissions with the same email in the same second can both miss and both create. Close the gap on your side:

  • Store the Pipedrive person ID per email in your own table with a unique constraint, and check it before searching.
  • Process sync jobs one at a time (a queue or a scheduled job), not in parallel per request.
  • Before creating a deal or lead, check that your source row has no deal or lead ID yet. Write the ID back right after creating it.

How do custom fields work?

Every custom field has a key that is a random 40-character hash, for example dcf558aac1ae4e8c4f849ba5e668430d8df9be12. Keys differ between Pipedrive accounts, even for fields with the same name (custom fields guide). Find them either in Pipedrive under Company settings → Data fields ("Copy API key" on the field's menu) or via GET /api/v2/personFields, /api/v2/organizationFields and /api/v2/dealFields, where each field's field_code is the key.

In API v2 you send them inside a custom_fields object:

await pd(`/api/v2/persons/${personId}`, {
  method: 'PATCH',
  body: JSON.stringify({
    custom_fields: {
      [Deno.env.get('PD_FIELD_SIGNUP_SOURCE')!]: 'AI app trial',
    },
  }),
});

To clear a value, send null. For multi-option fields, null clears the selection; an empty array is rejected. For option and monetary fields, read an existing record first to see the exact value format your account expects. Keep the keys in environment variables, so a staging and a production Pipedrive account can have different ones.

How do Pipedrive webhooks work, and how do you secure them?

Webhooks let Pipedrive tell your app when something changes, for example when a deal is won so your app can activate the customer. Create them in Settings → Tools and apps → Webhooks or through the API:

await pd('/api/v1/webhooks', {
  method: 'POST',
  body: JSON.stringify({
    name: 'Deal changes to my app',
    subscription_url: 'https://<project-ref>.supabase.co/functions/v1/pipedrive-webhook',
    event_action: 'change', // create | change | delete | *
    event_object: 'deal',
    version: '2.0',
    http_auth_user: Deno.env.get('PD_WEBHOOK_USER'),
    http_auth_password: Deno.env.get('PD_WEBHOOK_PASSWORD'),
  }),
});

What Pipedrive's webhooks v2 guide tells you to expect:

  • No signature. Pipedrive does not sign webhook requests. The protection available is HTTP basic auth on your URL. Check it on every request, and treat the payload as a hint: re-read the record through the API before acting on it.
  • Payload. meta holds the event details (action, entity, entity_id, id, timestamp, attempt, change_source, user_id and more). data is the current state, previous holds the old values of changed fields.
  • Retries. A non-2xx response or a response slower than 10 seconds is a failure. Pipedrive retries three more times, after 3, 30 and 150 seconds. If nothing is delivered successfully for three consecutive days, the webhook is deleted. After 10 failed first attempts a webhook is banned for 30 minutes, and events during the ban are lost.
  • Limits. Up to 40 webhooks per user.
// supabase/functions/pipedrive-webhook/index.ts  (verify_jwt = false in config.toml)
import { createClient } from 'npm:@supabase/supabase-js@2';
import { pd } from '../_shared/pipedrive.ts';

const admin = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!);
const expectedAuth =
  'Basic ' + btoa(`${Deno.env.get('PD_WEBHOOK_USER')}:${Deno.env.get('PD_WEBHOOK_PASSWORD')}`);
const INTEGRATION_USER_ID = Number(Deno.env.get('PD_INTEGRATION_USER_ID'));

Deno.serve(async (req) => {
  if (req.headers.get('Authorization') !== expectedAuth) {
    return new Response('Unauthorized', { status: 401 });
  }
  const { meta } = await req.json();

  // Ignore changes our own integration made, to avoid sync loops.
  if (meta.user_id === INTEGRATION_USER_ID) return new Response('ok');

  // Deduplicate on the event id (unique constraint on pipedrive_events.id).
  const { error } = await admin.from('pipedrive_events').insert({ id: String(meta.id) });
  if (error?.code === '23505') return new Response('ok'); // already processed
  if (error) return new Response('db error', { status: 500 });

  if (meta.entity === 'deal') {
    // Do not trust the payload: read the current deal from the API.
    const { data: deal } = await pd(`/api/v2/deals/${meta.entity_id}`);
    if (deal.status === 'won') {
      // Activate the customer in your app.
    }
  }
  return new Response('ok');
});

If the work after the dedupe insert can fail, either delete the event row on failure (so the retry is processed) or move the work to a queue. Keep the handler well under 10 seconds.

What are Pipedrive's rate limits?

Pipedrive uses two limits (rate limiting docs):

  • A daily token budget per company: 30,000 base tokens × plan multiplier × number of seats (plus purchased top-ups). Each endpoint costs tokens by complexity; search and list calls cost more than single reads or writes. The budget resets at midnight server time. When it is spent, requests return 429 until the reset.
  • Burst limits per token, in a rolling 2-second window. They depend on plan and on whether you use an API token or OAuth (OAuth is higher). The Search API is limited to 10 requests per 2 seconds on every plan.

Read x-ratelimit-remaining and x-ratelimit-reset on responses, back off on 429, and don't keep hammering: Pipedrive says clients that keep sending high volume after 429s can get a 403. Practical savings: cache organization and person IDs in your database so repeat submissions skip the search, and don't poll Pipedrive when a webhook can tell you about changes.

How do you test without touching your real CRM?

  • Request a Pipedrive developer sandbox account: a separate company account for building and testing apps. Its custom field keys, pipeline IDs and stage IDs will differ from production, which is a good test of keeping them in configuration. Pipedrive may delete sandbox accounts that stay inactive.
  • Run the sync function locally with supabase functions serve and a sandbox token.
  • Test the duplicate cases on purpose: the same email twice, two submissions at once, a company name with different capitalization.
  • For webhooks, expose your local function through a tunnel, make a change in the sandbox, and check that a retried delivery (same meta.id) is skipped.

Common errors

  • 401 Unauthorized: token missing or sent as a query parameter in old code. Send x-api-token as a header.
  • Fields silently ignored: custom field keys copied from another account, or sent at the top level of a v2 body instead of inside custom_fields.
  • Validation errors on v2: v2 validates input more strictly than v1. Emails and phones must be arrays of objects (value, primary, label).
  • Search finds nothing: the term is under 2 characters, not URL-encoded, or you searched the wrong fields.
  • Duplicates: parallel syncs, or no stored mapping between your user and the Pipedrive person.
  • Webhook stopped arriving: it was banned after repeated failures or deleted after three days without a successful delivery. Check the list with GET /api/v1/webhooks.
  • Sync loops: your app updates Pipedrive, the webhook fires, your app updates Pipedrive again. Skip events made by your integration user.

Brief for your AI coding tool

Paste this into Lovable, Claude Code or Cursor and fill in your field names:

Integrate this app with Pipedrive (API v2 where available, v1 for creating leads and webhooks).

Architecture:
- The signup form saves to public.leads first (columns: id, name, email, company, phone,
  pd_person_id, pd_org_id, pd_lead_id, synced_at, sync_error). RLS: clients can insert their own
  row only; they can never read other rows.
- Supabase Edge Function "sync-lead-to-pipedrive" (server only) processes unsynced rows one at a
  time. Auth: x-api-token header, token from secret PIPEDRIVE_API_TOKEN, base URL
  https://{PIPEDRIVE_COMPANY_DOMAIN}.pipedrive.com (paths /api/v2/... and /api/v1/...).
- Flow: findOrCreateOrganization via GET /api/v2/organizations/search (fields=name,
  exact_match=true) then POST /api/v2/organizations; findOrCreatePerson via
  GET /api/v2/persons/search (fields=email, exact_match=true) then POST /api/v2/persons with
  emails: [{ value, primary: true, label: 'work' }] and org_id; create a lead with
  POST /api/v1/leads { title, person_id, organization_id, origin_id: 'my-app-signup' } only if
  pd_lead_id is empty; write all IDs back to the row.
- Custom field keys come from env vars (40-char hashes), sent inside custom_fields.
- On 429: stop, keep the row unsynced, retry later with backoff. Log sync_error on failure.
- Edge Function "pipedrive-webhook" (verify_jwt=false): check HTTP basic auth, dedupe on
  meta.id with a unique table, ignore events where meta.user_id is the integration user,
  re-fetch the entity via the API before acting.

Safety rules:
- Never call Pipedrive from the browser or expose the token in VITE_ variables.
- Never create a person, organization, lead or deal without searching / checking stored IDs first.
- Use the Pipedrive sandbox account token until I confirm production.

When should you bring in a developer?

A one-way "form to Pipedrive" sync is a reasonable DIY project. Get help when:

  • Data must flow both ways and stay consistent (Pipedrive and your app both edit the same customer).
  • Pipedrive needs to connect onward to accounting, invoicing or an ERP, for example when a won deal should become an invoice.
  • You are building an app for other Pipedrive companies: OAuth, token refresh, uninstall handling and Marketplace review.
  • You are hitting rate limits or the daily budget, or importing large volumes of historical data.
  • You already have duplicates or mismatched records and need a cleanup and merge strategy.

We do this work for companies who built the first version themselves: see integrations for vibe-coded apps, or start with a code audit. More on our Pipedrive integration work and integration services. Rocksoft is a software company with teams in Poland and Norwegian-speaking staff, building integrations and custom software for companies in Norway and across Europe.

Related guides

FAQ

Should I create a lead or a deal?

Create a lead if someone needs to qualify the contact first; leads wait in the Leads Inbox and can be converted to deals. Create a deal if the submission is already a sales opportunity that belongs in a pipeline stage.

Can I use Pipedrive's API from Lovable without a backend?

No. The API token gives full access to your CRM as its user. It must stay in a server function, such as a Supabase Edge Function.

Is there an official Node.js SDK?

Yes, Pipedrive publishes the pipedrive package on npm (client-nodejs on GitHub). Plain fetch calls, as in this guide, work just as well in Deno-based Edge Functions and keep the requests easy to read.

Does Pipedrive merge duplicate persons automatically?

Do not rely on it. The API creates what you send. Search by email first and keep your own mapping of users to Pipedrive person IDs.

Why is my webhook payload missing fields?

Webhooks v2 send the standard fields of the entity, and previous only contains fields that changed. Fetch the full record through the API when you need more.

How do I avoid the daily token budget running out?

Cache IDs, avoid repeated searches, batch your syncs, and use webhooks instead of polling. Watch the rate limit headers and log 429 responses so you see the trend before it blocks you.