davramenko/pipedrive

Pipedrive REST client for PHP

v1.0.1 2024-01-10 13:01 UTC

This package is not auto-updated.

Last update: 2024-10-03 14:16:21 UTC


README

Pipedrive is a global sales-first CRM and intelligent revenue management platform for small businesses. Check out www.pipedrive.com for more details.

This is the official Pipedrive API wrapper-client for PHP based apps, distributed by Pipedrive Inc freely under the MIT licence. It provides convenient access to the Pipedrive API, allowing you to operate with entities such as deals, persons, organizations, products and more.

⚠️ With version 5 of the SDK, we have moved to an open-source SDK generator called OpenAPI Generator. This enables us to better respond to any issues you might have with our SDK.

Please use the issues page for reporting bugs or feedback.

Installation and usage

Requirements

PHP 7.4+ and later.

Composer

composer require davramenko/pipedrive

Manual Installation

Download the files and include autoload.php:

<?php
require_once('/path/to/pipedrive/vendor/autoload.php');

Tests

To run the unit tests:

composer install
composer test

Getting started

Please follow the installation procedure and then run the following:

With a pre-set API token

<?php

use Pipedrive\Configuration;

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

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

$apiInstance = new Pipedrive\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:

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\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\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\Api\DealsApi;
use Pipedrive\Configuration;

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

session_start();

$config = (new Pipedrive\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\Configuration;

session_start();

$config = (new Pipedrive\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/v1

Documentation for models

Documentation for authorization

api_key

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

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

Author

About this package

This PHP package is automatically generated by the OpenAPI Generator project:

  • API version: 1.0.0
  • Build package: org.openapitools.codegen.languages.PhpClientCodegen