Skip to content

Latest commit

 

History

History
572 lines (473 loc) · 32.4 KB

README.md

File metadata and controls

572 lines (473 loc) · 32.4 KB

Pipedrive client for API v2

Getting started

Please follow the installation procedure and then run the following:

With a pre-set API token

<?php

use Pipedrive\versions\v2\Configuration;

require_once('/path/to/client/vendor/autoload.php');

// Configure API key authorization: api_key
$config = (new Pipedrive\versions\v2\Configuration())->setApiKey('api_token', 'YOUR_API_KEY');

$apiInstance = new Pipedrive\versions\v2\Api\ActivitiesApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
    new GuzzleHttp\Client(),
    $config
);

try {
    $result = $apiInstance->getActivities();
    echo '<pre>';
    print_r($result);
    echo '</pre>';
} catch (Exception $e) {
    echo 'Exception when calling ActivitiesApi->getActivities: ', $e->getMessage(), PHP_EOL;
}

?>

With OAuth 2.0

In order to setup authentication in the API client, you need the following information:

Parameter Description
oAuthClientId OAuth 2.0 Client ID
oAuthClientSecret OAuth 2.0 Client Secret
oAuthRedirectUri OAuth 2.0 Redirection endpoint or Callback Uri

The API client can be initialized as following:

$oAuthClientId = 'oAuthClientId'; // OAuth 2 Client ID
$oAuthClientSecret = 'oAuthClientSecret'; // OAuth 2 Client Secret
$oAuthRedirectUri = 'https://example.com/oauth/callback'; // OAuth 2 Redirection endpoint or Callback Uri

$config = (new Pipedrive\versions\v2\Configuration());
$config->setClientId($oAuthClientId);
$config->setClientSecret($oAuthClientSecret);
$config->setOauthRedirectUri($oAuthRedirectUri);

$dealsApiInstance = new DealsApi(null, $config);

You must now authorize the client.

Authorizing your client

Your application must obtain user authorization before it can execute an endpoint call. The SDK uses OAuth 2.0 authorization to obtain a user's consent to perform an API request on the user's behalf.

1. Obtain user consent

To obtain user consent, you must redirect the user to the authorization page. The getAuthorizationPageUrl() method creates the URL to the authorization page when you have clientID and OAuthRedirect set in $config

$authUrl = $config->getAuthorizationPageUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));

2. Handle the OAuth server response

Once the user responds to the consent request, the OAuth 2.0 server responds to your application's access request by redirecting the user to the redirect URI specified in Configuration.

If the user approves the request, the authorization code will be sent as the code query string:

https://example.com/oauth/callback?code=XXXXXXXXXXXXXXXXXXXXXXXXX

If the user does not approve the request, the response contains an error query string:

https://example.com/oauth/callback?error=access_denied

3. Authorize the client using the code

After the server receives the code, it can exchange this for an access token. The access token is an object containing information for authorizing client requests and refreshing the token itself.

try {
    $config->authorize($_GET['code']);
} catch (Exception $ex) {
    // handle exception
}

Refreshing the token

An access token may expire after sometime. To extend its lifetime, you must refresh the token.

if ($configuration->getExpiresAt() < time()) {
    try {
        $config->refreshToken();
    } catch (Exception $ex) {
        // handle exception
    }
}

If a token expires, the SDK will attempt to automatically refresh the token before the next endpoint call requiring authentication.

Storing an access token for reuse

It is recommended that you store the access token for reuse.

You can store the access token in the $_SESSION global or any other persistent storage:

// store token
$_SESSION['access_token'] = $config->getAccessToken();

However, since the SDK will attempt to automatically refresh the token when it expires, it is recommended that you register a token update callback to detect any change to the access token.

$config->setOAuthTokenUpdateCallback(function ($token) {
    $_SESSION['token'] = $token;
});

The token update callback will be fired upon authorization as well as token refresh.

Creating a client from a stored token

To authorize a client from a stored access token, just set the access token in Configuration along with the other configuration parameters before creating the client:

// load token later...
$config->setAccessToken($_SESSION['token']->access_token);

// If you want to set all of the OAuth2 related fields at once from the token gotten from Pipedrive OAuth server
// you can use the updateOAuthRelatedFields() function
$config->updateOAuthRelatedFields($_SESSION['token']);
// This will set the access token, expiresIn, expiresAt, scope and host attributes in the Configuration class
// In order to get automatic access token refreshing, you will still need the client ID, client secret and redirectURI

// Set other configuration, then instantiate client
$activitiesApiInstance = new ActivitiesApi(null, $config);

Revoke token

When there is a need for an application to indicate to the authorization server that user token should be invalidated, use the revokeToken method with provided hint argument value:

$config = (new Pipedrive\versions\v2\Configuration());
$config->updateOAuthRelatedFields(/* ... */);

When configuration is set, just call the method:

// this will revoke all user tokens
$config->revokeToken('refresh_token');

/* OR */

// this will revoke only access token
$config->revokeToken('access_token');

Complete example with OAuth

In this example, the index.php will first check if an access token is available for the user. If one is not set, it redirects the user to authcallback.php which will obtain an access token and redirect the user back to the index.php page. Now that an access token is set, index.php can use the client to make authorized calls to the server.

index.php

<?php

use Pipedrive\versions\v2\Api\DealsApi;
use Pipedrive\versions\v2\Configuration;

require_once('../../sdks/php/vendor/autoload.php');

session_start();

$config = (new Pipedrive\versions\v2\Configuration());
$config->setOauthRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/authcallback.php');
$config->setClientSecret('YOUR_CLIENT_SECRET');
$config->setClientId('YOUR_CLIENT_ID');

//$usersApiInstance = new UsersApi(null, $config);
$dealsApiInstance = new DealsApi(null, $config);

// check if a token is available
if (isset($_SESSION['token']) && $_SESSION['token']) {
    // set access token in configuration
    $config->updateOAuthRelatedFields($_SESSION['token']);

    try {
        $dealsResponse = $dealsApiInstance->getDeals();
        echo '<pre>';
        print_r($dealsResponse);
        echo '</pre>';
    } catch (Exception $e) {
        echo 'Exception when trying to get deals data', $e, PHP_EOL;
    }
} else {
    header('Location: ' . filter_var($config->getAuthorizationPageUrl(), FILTER_SANITIZE_URL));
}

authcallback.php

<?php
require_once('../../sdks/php/vendor/autoload.php');

use Pipedrive\versions\v2\Configuration;

session_start();

$config = (new Pipedrive\versions\v2\Configuration());

$config->setOauthRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/authcallback.php');
$config->setClientSecret('YOUR_CLIENT_SECRET');
$config->setClientId('YOUR_CLIENT_ID');
$config->setAuthorizationPageUrl('https://oauth.pipedrive.com/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Fauthcallback.php');

$config->setOAuthTokenUpdateCallback(function ($token) {
    $_SESSION['token'] = $token;
});

// if authorization code is absent, redirect to authorization page
if (!isset($_GET['code'])) {
    header('Location: ' . filter_var($config->getAuthorizationPageUrl(), FILTER_SANITIZE_URL));
} else {
    try {
        $config->authorize($_GET['code']);

        // resume user activity
        $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    } catch (Exception $ex) {
        print_r($ex);
    }
}

Documentation for API endpoints

All URIs are relative to https://api.pipedrive.com/api/v2

Class Method HTTP request Description
ActivitiesApi addActivity POST /activities Add a new activity
ActivitiesApi deleteActivity DELETE /activities/{id} Delete an activity
ActivitiesApi getActivities GET /activities Get all activities
ActivitiesApi getActivity GET /activities/{id} Get details of an activity
ActivitiesApi updateActivity PATCH /activities/{id} Update an activity
BetaApi addActivity POST /activities Add a new activity
BetaApi addDeal POST /deals Add a new deal
BetaApi addDealProduct POST /deals/{id}/products Add a product to a deal
BetaApi addOrganization POST /organizations Add a new organization
BetaApi addPerson POST /persons Add a new person
BetaApi deleteActivity DELETE /activities/{id} Delete an activity
BetaApi deleteAdditionalDiscount DELETE /deals/{id}/discounts/{discount_id} Delete a discount from a deal
BetaApi deleteDeal DELETE /deals/{id} Delete a deal
BetaApi deleteDealProduct DELETE /deals/{id}/products/{product_attachment_id} Delete an attached product from a deal
BetaApi deleteInstallment DELETE /deals/{id}/installments/{installment_id} Delete an installment from a deal
BetaApi deleteOrganization DELETE /organizations/{id} Delete a organization
BetaApi deletePerson DELETE /persons/{id} Delete a person
BetaApi getActivities GET /activities Get all activities
BetaApi getActivity GET /activities/{id} Get details of an activity
BetaApi getAdditionalDiscounts GET /deals/{id}/discounts List discounts added to a deal
BetaApi getDeal GET /deals/{id} Get details of a deal
BetaApi getDealProducts GET /deals/{id}/products List products attached to a deal
BetaApi getDeals GET /deals Get all deals
BetaApi getDealsProducts GET /deals/products Get deal products of several deals
BetaApi getInstallments GET /deals/installments List installments added to a list of deals
BetaApi getOrganization GET /organizations/{id} Get details of a organization
BetaApi getOrganizations GET /organizations Get all organizations
BetaApi getPerson GET /persons/{id} Get details of a person
BetaApi getPersons GET /persons Get all persons
BetaApi postAdditionalDiscount POST /deals/{id}/discounts Add a discount to a deal
BetaApi postInstallment POST /deals/{id}/installments Add an installment to a deal
BetaApi searchDeals GET /deals/search Search deals
BetaApi searchItem GET /itemSearch Perform a search from multiple item types
BetaApi searchItemByField GET /itemSearch/field Perform a search using a specific field from an item type
BetaApi searchLeads GET /leads/search Search leads
BetaApi searchOrganization GET /organizations/search Search organizations
BetaApi searchPersons GET /persons/search Search persons
BetaApi updateActivity PATCH /activities/{id} Update an activity
BetaApi updateAdditionalDiscount PATCH /deals/{id}/discounts/{discount_id} Update a discount added to a deal
BetaApi updateDeal PATCH /deals/{id} Update a deal
BetaApi updateDealProduct PATCH /deals/{id}/products/{product_attachment_id} Update the product attached to a deal
BetaApi updateInstallment PATCH /deals/{id}/installments/{installment_id} Update an installment added to a deal
BetaApi updateOrganization PATCH /organizations/{id} Update a organization
BetaApi updatePerson PATCH /persons/{id} Update a person
DealsApi addDeal POST /deals Add a new deal
DealsApi addDealProduct POST /deals/{id}/products Add a product to a deal
DealsApi deleteAdditionalDiscount DELETE /deals/{id}/discounts/{discount_id} Delete a discount from a deal
DealsApi deleteDeal DELETE /deals/{id} Delete a deal
DealsApi deleteDealProduct DELETE /deals/{id}/products/{product_attachment_id} Delete an attached product from a deal
DealsApi deleteInstallment DELETE /deals/{id}/installments/{installment_id} Delete an installment from a deal
DealsApi getAdditionalDiscounts GET /deals/{id}/discounts List discounts added to a deal
DealsApi getDeal GET /deals/{id} Get details of a deal
DealsApi getDealProducts GET /deals/{id}/products List products attached to a deal
DealsApi getDeals GET /deals Get all deals
DealsApi getDealsProducts GET /deals/products Get deal products of several deals
DealsApi getInstallments GET /deals/installments List installments added to a list of deals
DealsApi postAdditionalDiscount POST /deals/{id}/discounts Add a discount to a deal
DealsApi postInstallment POST /deals/{id}/installments Add an installment to a deal
DealsApi searchDeals GET /deals/search Search deals
DealsApi updateAdditionalDiscount PATCH /deals/{id}/discounts/{discount_id} Update a discount added to a deal
DealsApi updateDeal PATCH /deals/{id} Update a deal
DealsApi updateDealProduct PATCH /deals/{id}/products/{product_attachment_id} Update the product attached to a deal
DealsApi updateInstallment PATCH /deals/{id}/installments/{installment_id} Update an installment added to a deal
ItemSearchApi searchItem GET /itemSearch Perform a search from multiple item types
ItemSearchApi searchItemByField GET /itemSearch/field Perform a search using a specific field from an item type
LeadsApi searchLeads GET /leads/search Search leads
OrganizationsApi addOrganization POST /organizations Add a new organization
OrganizationsApi deleteOrganization DELETE /organizations/{id} Delete a organization
OrganizationsApi getOrganization GET /organizations/{id} Get details of a organization
OrganizationsApi getOrganizations GET /organizations Get all organizations
OrganizationsApi searchOrganization GET /organizations/search Search organizations
OrganizationsApi updateOrganization PATCH /organizations/{id} Update a organization
PersonsApi addPerson POST /persons Add a new person
PersonsApi deletePerson DELETE /persons/{id} Delete a person
PersonsApi getPerson GET /persons/{id} Get details of a person
PersonsApi getPersons GET /persons Get all persons
PersonsApi searchPersons GET /persons/search Search persons
PersonsApi updatePerson PATCH /persons/{id} Update a person
PipelinesApi addPipeline POST /pipelines Add a new pipeline
PipelinesApi deletePipeline DELETE /pipelines/{id} Delete a pipeline
PipelinesApi getPipeline GET /pipelines/{id} Get one pipeline
PipelinesApi getPipelines GET /pipelines Get all pipelines
PipelinesApi updatePipeline PATCH /pipelines/{id} Update a pipeline
ProductsApi addProduct POST /products Add a product
ProductsApi addProductVariation POST /products/{id}/variations Add a product variation
ProductsApi deleteProduct DELETE /products/{id} Delete a product
ProductsApi deleteProductVariation DELETE /products/{id}/variations/{product_variation_id} Delete a product variation
ProductsApi getProduct GET /products/{id} Get one product
ProductsApi getProductVariations GET /products/{id}/variations Get all product variations
ProductsApi getProducts GET /products Get all products
ProductsApi searchProducts GET /products/search Search products
ProductsApi updateProduct PATCH /products/{id} Update a product
ProductsApi updateProductVariation PATCH /products/{id}/variations/{product_variation_id} Update a product variation
StagesApi addStage POST /stages Add a new stage
StagesApi deleteStage DELETE /stages/{id} Delete a stage
StagesApi getStage GET /stages/{id} Get one stage
StagesApi getStages GET /stages Get all stages
StagesApi updateStage PATCH /stages/{id} Update stage details

Documentation for models

Documentation for authorization

api_key

  • Type: API key
  • API key parameter name: api_token
  • Location: URL query string

basic_authentication

  • Type: HTTP basic authentication

oauth2

  • Type: OAuth
  • Flow: accessCode
  • Authorization URL: https://oauth.pipedrive.com/oauth/authorize
  • Scopes:
  • base: Read settings of the authorized user and currencies in an account
  • deals:read: Read most of the data about deals and related entities - deal fields, products, followers, participants; all notes, files, filters, pipelines, stages, and statistics. Does not include access to activities (except the last and next activity related to a deal)
  • deals:full: Create, read, update and delete deals, its participants and followers; all files, notes, and filters. It also includes read access to deal fields, pipelines, stages, and statistics. Does not include access to activities (except the last and next activity related to a deal)
  • mail:read: Read mail threads and messages
  • mail:full: Read, update and delete mail threads. Also grants read access to mail messages
  • activities:read: Read activities, its fields and types; all files and filters
  • activities:full: Create, read, update and delete activities and all files and filters. Also includes read access to activity fields and types
  • contacts:read: Read the data about persons and organizations, their related fields and followers; also all notes, files, filters
  • contacts:full: Create, read, update and delete persons and organizations and their followers; all notes, files, filters. Also grants read access to contacts-related fields
  • products:read: Read products, its fields, files, followers and products connected to a deal
  • products:full: Create, read, update and delete products and its fields; add products to deals
  • projects:read: Read projects and its fields, tasks and project templates
  • projects:full: Create, read, update and delete projects and its fields; add projects templates and project related tasks
  • users:read: Read data about users (people with access to a Pipedrive account), their permissions, roles and followers
  • recents:read: Read all recent changes occurred in an account. Includes data about activities, activity types, deals, files, filters, notes, persons, organizations, pipelines, stages, products and users
  • search:read: Search across the account for deals, persons, organizations, files and products, and see details about the returned results
  • admin: Allows to do many things that an administrator can do in a Pipedrive company account - create, read, update and delete pipelines and its stages; deal, person and organization fields; activity types; users and permissions, etc. It also allows the app to create webhooks and fetch and delete webhooks that are created by the app
  • leads:read: Read data about leads and lead labels
  • leads:full: Create, read, update and delete leads and lead labels
  • phone-integration: Enables advanced call integration features like logging call duration and other metadata, and play call recordings inside Pipedrive
  • goals:read: Read data on all goals
  • goals:full: Create, read, update and delete goals
  • video-calls: Allows application to register as a video call integration provider and create conference links
  • messengers-integration: Allows application to register as a messengers integration provider and allows them to deliver incoming messages and their statuses