Provides an API wrapper for interacting with remote CiviCRM instances via APIv4.

Overview

civicrm-api

civicrm-api is a Composer package that allows developers to interact with a CiviCRM instance using the REST API v4 functionality within CiviCRM.

This code is intended to be used outside of a CiviCRM deployment environment. As such, the codebase adheres to PSR-12 coding standards instead of Drupal/Wordpress/CiviCRM coding standards.

Installation

To install the library, run the following command:

composer require circle-interactive/civicrm-api

Requirements

  1. The CiviCRM server must be running on v5.47 or later.

In this release, the /civicrm/ajax/* endpoints were exposed as web services as part of currently ongoing efforts to expose REST endpoints via the standard CiviCRM routing system. Click here to learn more.

  1. Your application must use an HTTP client that is PSR-18 compliant.

If your application uses an HTTP client that is not compliant with PSR-18, it will be necessary to write a decorator class that implements a sendRequest method.

How to Use

NB: As you can see from the examples, this library does not deserialize responses. This is by design.

Calling code is responsible for response deserialization and handling the data from that response.

Guzzle Example



declare(strict_types=1);

// Require Composer autoloader
require __DIR__ . '/vendor/autoload.php';

// Define the desired type of authentication and key
$authType = \Circle\CiviCRM\AuthenticationTypes::BEARER_API_KEY;
$authKey = 'MYKEYGOESHERE'; // best practices dictate using an environment variable here!

// Configure Guzzle to point at the root URL for the CiviCRM site
// note we DO NOT include the /civicrm section of the URI in the base_uri field
$guzzleOptions = ['base_uri' => 'https://my.civicrm.site']; 
// Instantiate a new Guzzle client
$guzzleClient = new GuzzleHttp\Client($guzzleOptions);

// Instantiate a new CiviCRM API client, passing the Guzzle client as a parameter
$civicrm = new \Circle\CiviCRM\Client($guzzleClient, $authType, $authKey);

// Make request to retrieve all Contacts
$contactsResponse = $civicrm->get('Contact');
// Note that the full API response object is returned to the caller
$contactsJson = $contactsResponse->getBody()->getContents();
// Decode the response
$contacts = json_decode($contactsJson, TRUE);
$contactsArray = $contacts['values'];

var_dump($contactsArray);

Symfony HTTP Client Example



declare(strict_types=1);

// Require Composer autoloader
require __DIR__ . '/vendor/autoload.php';

// Define the desired type of authentication and key
$authType = \Circle\CiviCRM\AuthenticationTypes::BEARER_API_KEY;
$authKey = 'MYKEYGOESHERE'; // best practices dictate using an environment variable here!

// Instantiate a new Symfony HTTP client
$symfonyClient = \Symfony\Component\HttpClient\HttpClient::createForBaseUri('https://my.civicrm.site');
$psr18client = new \Symfony\Component\HttpClient\Psr18Client($symfonyClient);

// Instantiate a new CiviCRM API client, passing the PSR18-compatible Symfony HTTP client as a parameter
$civicrm = new \Circle\CiviCRM\Client($psr18client, $authType, $authKey);

// Make request to retrieve all Activities
$activityResponse = $civicrm->get('Activity');
// Note that the full API response object is returned to the caller
$activityJson = $activityResponse->getBody()->getContents();
// Decode the response
$activities = json_decode($activityJson, TRUE);
$activitiesArray = $activities['values'];

var_dump($activitiesArray);

NB: Use correct, case-specific Entity names when interacting with the API (for example: "activity" will return an error, use "Activity" instead)

Available Functions

The examples make use of the get method exposed by this library. However, this is not the only available method. The list of available methods is as follows:

  1. getActions
  2. getFields
  3. get
  4. create
  5. update
  6. save
  7. delete
  8. replace

As well as the above, the library also exposes the request method. This allows for arbitrary combinations of Entity, action, and params. An example of usage of this method can be seen below:

$civicrm = new \Circle\CiviCRM\Client($psr18client, $authType, $authKey);
$myCustomResponse = $civicrm->request('CustomEntity', 'customaction', ['my' => 'custom', 'params']);

This would be useful in the following (non-exhaustive list of) situations:

  • Your CiviCRM instance contains custom entities
  • You want to perform an entity-specific action (for example: MailSettings.testConnection, or Setting.set)

Available Authentication Methods

This library uses the X-Civi-Auth Header when making requests to CiviCRM instances. As such, the following authentication methods are available:

Type of Authentication Library Mapping
Basic Authentication Circle\CiviCRM\AuthenticationTypes::BASIC
API Key Authentication Circle\CiviCRM\AuthenticationTypes::BEARER_API_KEY
JWT Authentication Circle\CiviCRM\AuthenticationTypes::BEARER_JWT

Any other form of authentication is unsupported by this library.

NB: When creating a Client object, only pass the Authentication Key (ie: MYKEY).

Do not pass the Bearer or Basic keywords (ie: Bearer MYKEY or Basic MYKEY)as these are put in place by the library.

Note on Basic Authentication

When using Basic Authentication, the key is a base64 encoded string: B64(USER:PASSWORD). You will need to provide the Base64 encoded string as the $authKey parameter to the Circle\CiviCRM\Client constructor.

Contributing

If you find a bug or other issue within this library, please raise an issue in this Github repository.

To run tests, run composer test. The library uses Pest for automated testing, and adheres to PHPStan Level 6.

Resources

Support

The technical team at Circle Interactive are responsible for the maintenance of this library. Circle offer CiviCRM implementations for third-sector clients of any kind, no matter the size.

License

This package is licensed with AGPL-3.0, as is CiviCRM.

You might also like...
QuidPHP/Core is a PHP library that provides an extendable platform to create dynamic applications

QuidPHP/Core About QuidPHP/Core is a PHP library that provides an extendable platform to create dynamic applications. It is part of the QuidPHP packag

The API & platform builder, build your apps 10x faster even more, it's open source & 100% free !
The API & platform builder, build your apps 10x faster even more, it's open source & 100% free !

The API & platform builder, build your apps 10x faster, even more. It's open source & 100% free ! Try live demo Why badaso ? 100% FREE - No need for e

This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 4.0.0 platform. It allows you to query some other server information
This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 4.0.0 platform. It allows you to query some other server information

QueryServer This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 4.0.0 platform. I

Provide a module to industrialize API REST call with dependency injection using Guzzle library
Provide a module to industrialize API REST call with dependency injection using Guzzle library

Zepgram Rest Technical module to industrialize API REST call with dependency injection using Guzzle library. Provides multiple features to make your l

Simple searching for postcodes to retrieve geographic information. Support for various API providers and a unified address/output format.

Postcode Search Simple searching for postcodes to retrieve geographic information. Support for various API providers and a unified address/output form

nextcloud app that replicates basic gpodder.net api

nextcloud-gpodder Nextcloud app that replicates basic gpodder.net api This app serves as synchronization endpoint for AntennaPod: https://github.com/A

Translate laravel resource, vendor, folder or file from google translation without requiring any api information
Translate laravel resource, vendor, folder or file from google translation without requiring any api information

⚡ ⚡ ⚡ Laravel Go Translate Translate laravel resource, vendor, folder or file from google translation without requiring any api information. Table of

Quick and dirty PHP script to turn a Twitter feed into an RSS feed using Twitter's v2 API

Twitter to RSS Quick and dirty PHP script that turns a given Twitter feed into a RSS feed using Twitter's API v2 (the free version!) Does some basic l

Facebook & Instagram Ads API for Laravel
Facebook & Instagram Ads API for Laravel

Laravel Facebook Ads Get ads infos (campaigns, ads, insights, etc...) from Facebook & Instagram Ads API Supported Facebook API version: = v3.0 Instal

Comments
  • "values" key is hardcoded in parameter passing

    Something similar to the following:

    $results = civicrm_api4('CustomField', 'create', [
      'values' => [
        'is_searchable' => TRUE, 
        'is_required' => TRUE,
      ],
      'chain' => [
        'name_me_0' => ['ACL', '', []],
      ],
    ]);
    

    wouldn't work because the HTTP request hardcodes "values"

    https://github.com/circle-interactive/civicrm-api/blob/ad199a0c4d368a612f3725053ab6278dc9b58f21/CiviCRM/Http/Requests/CiviRequest.php#L54

    opened by MattTrim1 0
  • Docs

    Docs

    As it stands, the README contains a lot of information and is not necessarily digestible on first glance.

    It may be good to consider how we can extract the useful information into a more useful format. Perhaps a docs micro-site?

    On the note of docs, the following items (off the top of my head) need addressing:

    • Create Contributing guide
    • Document the $headers param in the Client constructor
    opened by MattTrim1 0
Releases(v1.2.0)
  • v1.2.0(Apr 6, 2022)

    Provides the ability for a consumer to define custom headers that should be transmitted in the request.

    NB: All Headers passed into the client will be applied to every request made with the Client instance that contains the custom headers.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Apr 5, 2022)

  • v1.0.0(Apr 4, 2022)

Owner
Circle Interactive
Circle Interactive is a small, friendly digital agency based at the foot of the Avon Gorge in Bristol.
Circle Interactive
Retrieve MySejahtera App's data from MySejahtera API and show to users via web browser. Written in PHP

MySejahtera-PHP-Web Retrieve MySejahtera App's data from MySejahtera API and show to users via web browser. Written in PHP. Disclaimer This web app is

Sam Sam 3 Oct 21, 2022
Laravel wrapper for the Fathom Analytics API

Please note: This package is still a work in progress and the Fathom API is also only in early access. Do not use this package in your production envi

Marc Reichel 12 Sep 19, 2022
Phantom Analyzer scans websites for spy pixels. It runs via Laravel Vapor using Browsershot.

Phantom Analyzer Phantom Analyzer was a tool we launched during Halloween 2020. It's a much simpler version of Blacklight by The Markup and we had so

Fathom Analytics 105 Dec 18, 2022
Belajar laravel 8 via YouTube....

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

null 1 Nov 6, 2021
Rafa Cake and Bakery is a web-based application project that aims to introduce Rafa Cake and Bakery, introduce what products are sold and can also order them via Whatsapp.

Rafa-cake-and-bakery Rafa Cake and Bakery is a web-based application project that aims to introduce Rafa Cake and Bakery, introduce what products are

Aan Evian Nanda 2 Jun 19, 2022
Provides access to Cloudflare Images API for Laravel projects

Cloudflare Images Provides access to Cloudflare Images API for Laravel projects Table of contents Installation Configuration Using Installation To get

Dmytro 20 Dec 16, 2022
Simple and lightweight OOP wrapper for PHP's low-level sockets extension (ext-sockets)

clue/socket-raw Simple and lightweight OOP wrapper for PHP's low-level sockets extension (ext-sockets). PHP offers two networking APIs, the newer stre

Christian Lück 321 Dec 15, 2022
A simple wrapper for PHP Intervention Library to provide a more simple interface and convenient way to convert images to webp

This package is a simple wrapper for PHP Intervention Library to provide a more simple interface and convenient way to convert images to webp - next generation format - extension, and resize them to render only needed sizes.

eyad hamza 18 Jun 28, 2022
DooTask is a lightweight open source online project task management tool that provides various document collaboration tools, online mind mapping, online flowcharting, project management, task distribution, instant IM, file management and other tools.

DooTask is a lightweight open source online project task management tool that provides various document collaboration tools, online mind mapping, online flowcharting, project management, task distribution, instant IM, file management and other tools.

kuaifan 3k Jan 5, 2023
ViMbAdmin project provides a web based virtual mailbox administration system to allow mail administrators to easily manage domains, mailboxes and aliases.

ViMbAdmin project (vim-be-admin) provides a web based virtual mailbox administration system to allow mail administrators to easily manage domains, mailboxes and aliases.

Open Solutions 464 Jan 1, 2023