Search by

chartmogul / chartmogul-php

jhearnkeith-chartmogul

ChartMogul API PHP Client

Package info

github.com/chartmogul/chartmogul-php

pkg:composer/chartmogul/chartmogul-php

Statistics

Installs: 1 692 665

Dependents: 0

Suggesters: 0

Stars: 18

Open Issues: 0


README

Official ChartMogul API PHP Client

chartmogul-php provides convenient PHP bindings for ChartMogul's API.

Build Status

Installation | Configuration | Usage | Development | Contributing | Security | License


Installation

This library requires PHP 7.1 or above.

For older PHP versions (< 7.4) use 1.x.x releases of this library.

For PHP version >=7.4 use the latest releases (6.x.x) of the library.

The library doesn't depend on any concrete HTTP client libraries. Follow the instructions here to find out how to include a HTTP client.

Here's an example with Guzzle HTTP client:

composer require chartmogul/chartmogul-php:^6.0 php-http/guzzle7-adapter:^1.0 http-interop/http-factory-guzzle:^1.0

Security Best Practices

  • Always commit composer.lock to version control so all environments use identical dependency trees.
  • Run composer audit regularly (or in CI) to detect known vulnerabilities in dependencies.
  • Verify releases against the GitHub Releases page, which includes changelog notes for each version.

Configuration

Setup the default configuration with your ChartMogul api key:

require('./vendor/autoload.php');

ChartMogul\Configuration::getDefaultConfiguration()
    ->setApiKey('<YOUR_API_KEY>');

Test your authentication

print_r(ChartMogul\Ping::ping()->data);

Usage

try {
  $dataSources = ChartMogul\DataSource::all();
} catch(\ChartMogul\Exceptions\ForbiddenException $e){
  // handle authentication exception
} catch(\ChartMogul\Exceptions\ChartMogulException $e){
    echo $e->getResponse();
    echo $e->getStatusCode();
}

$ds = $dataSources->first();
var_dump($ds->uuid); // access Datasource properties
$dsAsArray = $ds->toArray(); // convert to array
$ds->destroy();

All array results are wrapped with Doctrine\Common\Collections\ArrayCollection for ease of access. See Exceptions for a list of exceptions thrown by this library.

Available methods in Import API:

Data Sources

Create Datasources

$ds = ChartMogul\DataSource::create([
  'name' => 'In-house Billing'
]);

Get a Datasource

ChartMogul\DataSource::retrieve($uuid);

Include extra fields:

ChartMogul\DataSource::retrieve($uuid, [
    'with_processing_status' => true,
    'with_auto_churn_subscription_setting' => true,
    'with_invoice_handling_setting' => true
]);

List Datasources

ChartMogul\DataSource::all();

Include extra fields:

ChartMogul\DataSource::all([
    'with_processing_status' => true,
    'with_auto_churn_subscription_setting' => true,
    'with_invoice_handling_setting' => true
]);

Delete a Datasource

$dataSources = ChartMogul\DataSource::all();
$ds = $dataSources->last();
$ds->destroy();

Customers

Import a Customer

ChartMogul\Customer::create([
    "data_source_uuid" => $ds->uuid,
    "external_id" => "cus_0003",
    "name" => "Adam Smith",
    "email" => "adam@smith.com",
    "country" => "US",
    "city" => "New York",
    "lead_created_at" => "2016-10-01T00:00:00.000Z",
    "free_trial_started_at" => "2016-11-02T00:00:00.000Z"
]);

List Customers

ChartMogul\Customer::all([
  'page' => 1,
  'data_source_uuid' => $ds->uuid
]);

Find Customer By External ID

ChartMogul\Customer::findByExternalId([
    "data_source_uuid" => "ds_fef05d54-47b4-431b-aed2-eb6b9e545430",
    "external_id" => "cus_0001"
]);

Delete A Customer

$cus = ChartMogul\Customer::all()->last();
$cus->destroy();

Get a Customer

ChartMogul\Customer::retrieve($uuid);

Get a Customer with Overrides and Historical Values

ChartMogul\Customer::retrieve($uuid, null, [
    'with_overrides' => true,
    'attributes_with_history' => 'company,custom.channel'
]);

Search for Customers

ChartMogul\Customer::search('adam@smith.com');

Merge Customers

ChartMogul\Customer::merge([
    'customer_uuid' => $cus1->uuid
], [
    'customer_uuid' => $cus2->uuid
]);

// alternatively:
ChartMogul\Customer::merge([
    'external_id' => $cus1->external_id,
    'data_source_uuid' => $ds->uuid
], [
    'external_id' => $cus2->external_id,
    'data_source_uuid' => $ds->uuid
]);

Unmerge Customers

ChartMogul\Customer::unmerge(
    $cus->uuid,
    $cus->external_id,
    $ds->uuid,
    ["tasks", "opportunities", "notes"]
);

Update a Customer

$result = ChartMogul\Customer::update([
    'customer_uuid' => $cus1->uuid
], [
    'name' => 'New Name'
]);

Connect Subscriptions

ChartMogul\Customer::connectSubscriptions("cus_5915ee5a-babd-406b-b8ce-d207133fb4cb", [
    "subscriptions" => [
        [
            "data_source_uuid" => "ds_ade45e52-47a4-231a-1ed2-eb6b9e541213",
            "external_id" => "d1c0c885-add0-48db-8fa9-0bdf5017d6b0",
        ],
        [
            "data_source_uuid" => "ds_ade45e52-47a4-231a-1ed2-eb6b9e541213",
            "external_id" => "9db5f4a1-1695-44c0-8bd4-de7ce4d0f1d4",
        ],
    ]
]);

OR (Recommended)

use ChartMogul\Metrics\Customers\Subscription;

// Fetch customer subscriptions
$subscriptions = $customer->subscriptions();

// Connect subscriptions
Subscription::connect(
    "ds_ade45e52-47a4-231a-1ed2-eb6b9e541213",  // data source UUID
    "cus_5915ee5a-babd-406b-b8ce-d207133fb4cb",  // customer UUID
    $subscriptions->entries  // array of Subscription objects
);

OR (Deprecated)

$subscription1->connect("cus_5915ee5a-babd-406b-b8ce-d207133fb4cb", $subscriptions);

Disconnect Subscriptions

ChartMogul\Customer::disconnectSubscriptions("cus_5915ee5a-babd-406b-b8ce-d207133fb4cb", [
    "subscriptions" => [
        [
            "data_source_uuid" => "ds_ade45e52-47a4-231a-1ed2-eb6b9e541213",
            "external_id" => "d1c0c885-add0-48db-8fa9-0bdf5017d6b0",
        ],
        [
            "data_source_uuid" => "ds_ade45e52-47a4-231a-1ed2-eb6b9e541213",
            "external_id" => "9db5f4a1-1695-44c0-8bd4-de7ce4d0f1d4",
        ],
    ]
]);

OR (Recommended)

use ChartMogul\Metrics\Customers\Subscription;

// Fetch customer subscriptions
$subscriptions = $customer->subscriptions();

// Disconnect subscriptions
Subscription::disconnect(
    "ds_ade45e52-47a4-231a-1ed2-eb6b9e541213",  // data source UUID
    "cus_5915ee5a-babd-406b-b8ce-d207133fb4cb",  // customer UUID
    $subscriptions->entries  // array of Subscription objects
);

OR (Deprecated)

$subscription1->disconnect("cus_5915ee5a-babd-406b-b8ce-d207133fb4cb", $subscriptions);

Customer Attributes

Retrieve Customer's Attributes

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$customer->attributes;

Tags

Add Tags to a Customer

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$tags = $customer->addTags("important", "Prio1");

Add Tags Using Array (Alternative)

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$tagsArray = ["important", "Prio1", "enterprise"];
$tags = $customer->addTags($tagsArray);

Add Tags to Customers with email

$customers = ChartMogul\Customer::search('adam@smith.com');

foreach ($customers->entries as $customer) {
    $customer->addTags('foo', 'bar', 'baz');
}

Remove Tags from a Customer

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$tags = $customer->removeTags("important", "Prio1");

Remove Tags Using Array (Alternative)

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$tagsToRemove = ["important", "Prio1"];
$tags = $customer->removeTags($tagsToRemove);

Custom Attributes

Add Custom Attributes to a Customer

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$custom = $customer->addCustomAttributes(
    ['type' => 'String', 'key' => 'channel', 'value' => 'Facebook'],
    ['type' => 'Integer', 'key' => 'age', 'value' => 8 ]
);

Add Custom Attributes Using Array (Alternative)

$customer = ChartMogul\Customer::retrieve($cus->uuid);

// Build attributes array dynamically
$attributes = [];
if (!empty($channel)) {
    $attributes[] = ['type' => 'String', 'key' => 'channel', 'value' => $channel];
}
if (!empty($age)) {
    $attributes[] = ['type' => 'Integer', 'key' => 'age', 'value' => $age];
}

$custom = $customer->addCustomAttributes($attributes);

Add Custom Attributes to Customers with email

$customers = ChartMogul\Customer::search('adam@smith.com');

foreach ($customers->entries as $customer) {
    $customer->addCustomAttributes(
        ['type' => 'String', 'key' => 'channel', 'value' => 'Facebook'],
        ['type' => 'Integer', 'key' => 'age', 'value' => 8 ]
    );
}

Update Custom Attributes of a Customer

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$custom = $customer->updateCustomAttributes(
    ['type' => 'String', 'key' => 'channel', 'value' => 'Twitter'],
    ['type' => 'Integer', 'key' => 'age', 'value' => 18]
);

Update Custom Attributes Using Array (Alternative)

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$attributeUpdates = [
    ['type' => 'String', 'key' => 'channel', 'value' => 'Twitter'],
    ['type' => 'Integer', 'key' => 'age', 'value' => 18]
];
$custom = $customer->updateCustomAttributes($attributeUpdates);

Remove Custom Attributes from a Customer

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$tags = $customer->removeCustomAttributes("age", "channel");

Remove Custom Attributes Using Array (Alternative)

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$attributesToRemove = [
    ['key' => 'age'],
    ['key' => 'channel']
];
$tags = $customer->removeCustomAttributes($attributesToRemove);

Send Custom Attribute Overrides

Setting an attribute's flag to true overrides its value with what the request writes. While overridden, the attribute is protected from data-source syncs and from API writes that don't carry a flag for it — those are skipped silently and the response returns the overridden value; a remove keeps the attribute and the response message names it.

To change an overridden value, send the write with the flag again: true keeps the override at the new value, false removes it. Setting a flag to false removes an existing override and restores the most recent value from the edit history (on a create it does nothing).

The WithOverrides methods return the whole response, including the overrides object. On these endpoints (and retrieveAttributes) it has namespaces at the top level, e.g. ['custom' => ['channel' => true]] — there is no attributes wrapper in $result['overrides']. Customer responses and addCustomAttributesByEmail entries use the wrapped shape instead (['company' => true, 'attributes' => ['custom' => [...]]]), and the SDK keeps the customer object in that shape by syncing each call's overrides into $customer->overrides['attributes'].

An override is only accepted for an attribute that already exists on the account and has history tracking enabled; otherwise the call returns a 422 (not_found / not_trackable), before anything is written. A brand-new key therefore takes two steps:

$customer = ChartMogul\Customer::retrieve($cus->uuid);

// New key: add it first, then override it
$customer->addCustomAttributes(['type' => 'String', 'key' => 'channel', 'value' => 'Facebook']);
$result = $customer->updateCustomAttributesWithOverrides(
    ['channel' => 'Facebook'],
    ['custom' => ['channel' => true]]
);

// A key the account already knows can be written and overridden in one call
$result = $customer->addCustomAttributesWithOverrides(
    [['type' => 'String', 'key' => 'channel', 'value' => 'Facebook']],
    ['custom' => ['channel' => true]]
);

$result = $customer->updateCustomAttributesWithOverrides(
    ['channel' => 'Twitter'],
    ['custom' => ['channel' => true]]
);

$result = $customer->removeCustomAttributesWithOverrides(
    ['age'],
    ['custom' => ['age' => false]]
);

// The by-email request takes the same direct shape, but each returned entry
// carries customer-shaped overrides (['attributes' => ['custom' => [...]]]),
// unlike the calls above
ChartMogul\Customer::addCustomAttributesByEmail(
    'adam@smith.com',
    [['type' => 'String', 'key' => 'channel', 'value' => 'Facebook']],
    null,
    ['custom' => ['channel' => true]]
);

Retrieve a Customer's Attributes with Overrides

The two query params are independent. Unlike Customer::retrieve, attributes_with_history here accepts only custom attribute names (custom.<key>, case-sensitive); a bare field name like company returns a 422. History entries come back newest first.

$customer = ChartMogul\Customer::retrieve($cus->uuid);
$attributes = $customer->retrieveAttributes([
    'with_overrides' => true,
    'attributes_with_history' => 'custom.channel'
]);

List Contacts from a customer

$customer = ChartMogul\Customer::retrieve($uuid);
$contacts = $customer->contacts([
  'cursor' => 'aabbccdd...'
]);

Create a Contact from a customer

$customer = ChartMogul\Customer::retrieve($uuid);
$new_customer = $customer->createContact([
  "data_source_uuid" => "ds_00000000-0000-0000-0000-000000000000",
  "first_name" => "Adam",
  "last_name" => "Smith",
]);

List Entity Notes for a customer

$customer = ChartMogul\Customer::retrieve($uuid);
$notes = $customer->entityNotes([
  'cursor' => 'aabbccdd...'
]);

Create an Entity Note for a customer

$customer = ChartMogul\Customer::retrieve($uuid);
$new_note = $customer->createEntityNote([
  'type' => 'note',
  'text' => 'This is a note'
]);

List Customer Notes from a customer (Deprecated)

Note: $customer->notes() and $customer->createNote() are deprecated and emit an E_USER_DEPRECATED warning. Use $customer->entityNotes() and $customer->createEntityNote() instead.

$customer = ChartMogul\Customer::retrieve($uuid);
$customer_notes = $customer->notes([
  'cursor' => 'aabbccdd...'
]);

Create a Customer Note from a customer (Deprecated)

$customer = ChartMogul\Customer::retrieve($uuid);
$new_customer_note = $customer->createNote([
  'type' => 'note',
  'text' => 'This is a note'
]);

List Opportunities from a customer

$customer = ChartMogul\Customer::retrieve($uuid);
$opportunities = $customer->opportunities([
  'cursor' => 'aabbccdd...'
]);

Create an Opportunity from a customer

$customer = ChartMogul\Customer::retrieve($uuid);
$new_opportunity = $customer->createOpportunity([
  'owner' => 'owner@example.com',
  'pipeline' => 'Sales',
  'pipeline_stage' => 'Qualified',
  'estimated_close_date' => '2022-03-30',
  'currency' => 'USD',
  'amount_in_cents' => 10000,
  'type' => 'one-time',
  'forecast_category' => 'Best Case',
  'win_likelihood' => 80,
  'custom' => [{key: 'custom_key', value: 'custom_value'}]
]);

List Tasks for a customer

$customer = ChartMogul\Customer::retrieve($customer_uuid);
$tasks = $customer->tasks([
  'cursor' => 'aabbccdd...'
]);

Create a Task for a customer

$customer = ChartMogul\Customer::retrieve($customer_uuid);
$new_task = $customer->createTask([
  'assignee' => 'customer@example.com',
  'task_details' => 'This is some task details text.',
  'due_date' => '2025-04-30T00:00:00Z',
  'completed_at' => '2025-04-20T00:00:00Z',
]);

Customer Notes

Note: ChartMogul\CustomerNote (the /v1/customer_notes API) is deprecated and every method emits an E_USER_DEPRECATED warning. Use ChartMogul\EntityNote (the /v1/notes API, see Entity Notes) instead. The behaviour and endpoint of CustomerNote are unchanged.

List Customer Notes

$customer_notes = ChartMogul\CustomerNote::all([
    'customer_uuid' => $uuid,
    'cursor' => 'aabbccdd...'
])

Create a Customer Note

$customer_note = ChartMogul\CustomerNote::create([
    'customer_uuid' => $uuid,
    'type' => 'note',
    'text' => 'This is a note'
])

Get a Customer Note

$customer_note = ChartMogul\CustomerNote::retrieve($note_uuid)

Update a Customer Note

$updated_customer_note = ChartMogul\CustomerNote::update([
    'note_uuid' => $note_uuid
], [
  'text' => 'This is a new note'
]);

Delete a Customer Note

$customer_note = ChartMogul\CustomerNote::retrieve($note_uuid)
$customer_note->destroy();

Entity Notes

Entity notes can be attached to a customer or to a contact. Each note exposes customer_uuid (null for contact notes) and, where available, associated_object (customer or contact) and associated_object_uuid.

List Entity Notes

$notes = ChartMogul\EntityNote::all([
    'customer_uuid' => $customer_uuid, // or 'contact_uuid' => $contact_uuid
    'type' => 'note',                  // 'note' or 'call'
    'author_email' => 'john@example.com',
    'per_page' => 50,
    'cursor' => 'aabbccdd...'
]);

Create an Entity Note for a customer

$note = ChartMogul\EntityNote::create([
    'customer_uuid' => $customer_uuid,
    'type' => 'note',
    'author_email' => 'john@example.com',
    'text' => 'This is a note'
]);

Create an Entity Note for a contact

$note = ChartMogul\EntityNote::create([
    'associated_object_identifier' => [
        'associated_object' => 'contact',
        'method' => 'uuid',
        'value' => $contact_uuid
    ],
    'type' => 'call',
    'call_duration' => 120,
    'text' => 'Call with the contact'
]);

Get an Entity Note

$note = ChartMogul\EntityNote::retrieve($note_uuid);

Update an Entity Note

$updated_note = ChartMogul\EntityNote::update([
    'note_uuid' => $note_uuid
], [
    'text' => 'This is a new note'
]);

If the request contains nothing to update, the API responds with 304 Not Modified and an empty EntityNote (all properties null) is returned.

Delete an Entity Note

$note = ChartMogul\EntityNote::retrieve($note_uuid);
$note->destroy();

Contacts

List Contacts

$contacts = ChartMogul\Contact::all([
  'customer_uuid' => $customer_uuid,
  'data_source_uuid' => $data_source_uuid,
  'email' => 'adam@example.com',
  'customer_external_id' => 'customer_001',
  'external_id' => 'contact_001',
  'cursor' => 'aabbccdd...'
]);

Create a Contact

$new_contact = ChartMogul\Contact::create([
  "customer_uuid" => "cus_00000000-0000-0000-0000-000000000000",
  "data_source_uuid" => "ds_00000000-0000-0000-0000-000000000000",
  "first_name" => "Adam",
  "last_name" => "Smith",
  "email" => "adam@example.com",
  "last_seen" => "2025-01-01T00:00:00Z",
]);

customer_uuid and data_source_uuid are optional, so a contact can be created without a customer. In responses customer_uuid and data_source_uuid may be null.

Get a Contact

$contact = ChartMogul\Contact::retrieve($uuid);

Get a Contact with Overrides and Historical Values

$contact = ChartMogul\Contact::retrieve($uuid, null, [
    'with_overrides' => true,
    'attributes_with_history' => 'title,phone'
]);

Delete A Contact

$contact = ChartMogul\Contact::retrieve($uuid);
$contact->destroy();

Update a Contact

$updated_contact = ChartMogul\Contact::update([
    'contact_uuid' => $uuid
], [
    'first_name' => 'New Name',
    'last_seen' => '2025-01-01T00:00:00Z'
]);

Update a Contact with Overrides

Contact overrides follow the same rules as customer overrides: an overridden field is protected from data-source syncs and from API writes that don't carry its flag (a later Contact::update without the flag is reverted), and false removes the override, restoring the most recent edit-history value. Contact custom attribute overrides are not yet implemented by the API — a custom attribute key in contact overrides is rejected as not_overridable. Write responses always include the contact's current overrides; $customer->createContact([...]) accepts overrides the same way.

$updated_contact = ChartMogul\Contact::update([
    'contact_uuid' => $uuid
], [
    'title' => 'CTO',
    'overrides' => ['title' => true]
]);

Merge Contacts

$merged_contact = ChartMogul\Contact::merge($into_contact_uuid, $from_contact_uuid);

List Tasks for a contact

$contact = ChartMogul\Contact::retrieve($uuid);
$tasks = $contact->tasks([
  'cursor' => 'aabbccdd...'
]);

Create a Task for a contact

$contact = ChartMogul\Contact::retrieve($uuid);
$new_task = $contact->createTask([
  'assignee' => 'customer@example.com',
  'task_details' => 'Call the contact back.',
  'due_date' => '2025-04-30T00:00:00Z',
]);

List Entity Notes for a contact

$contact = ChartMogul\Contact::retrieve($uuid);
$notes = $contact->entityNotes([
  'cursor' => 'aabbccdd...'
]);

Create an Entity Note for a contact

$contact = ChartMogul\Contact::retrieve($uuid);
$new_note = $contact->createEntityNote([
  'type' => 'note',
  'text' => 'This is a contact note'
]);

The contact helpers send associated_object_identifier for the contact unless the data already contains customer_uuid or associated_object_identifier.

Opportunities

List Opportunities

$opportunities = ChartMogul\Opportunity::all([
    'cursor' => 'aabbccdd...'
])

Create an Opportunity

$opportunity = ChartMogul\Opportunity::create([
    'customer_uuid' => $uuid,
    'owner' => 'test1@example.org',
    'pipeline' => 'New business 1',
    'pipeline_stage' => 'Discovery',
    'estimated_close_date' => '2023-12-22',
    'currency' => 'USD',
    'amount_in_cents' => 100,
    'type' => 'recurring',
    'forecast_category' => 'pipeline',
    'win_likelihood' => 3,
    'custom' => [{ 'key': 'from_campaign', 'value': true }]
])

Get an Opportunity

$opportunity = ChartMogul\Opportunity::retrieve($opportunity_uuid)

Update an Opportunity

$updated_opportunity = ChartMogul\Opportunity::update($opportunity_uuid, [
  'estimated_close_date' => '2024-12-22',
]);

Delete an Opportunity

$opportunity = ChartMogul\Opportunity::retrieve($opportunity_uuid)
$opportunity->destroy();

Tasks

List Tasks

$tasks = ChartMogul\Task::all([
    'customer_uuid' => $customer_uuid, // or 'contact_uuid' => $contact_uuid
    'assignee' => 'customer@example.com',
    'due_date_on_or_after' => '2025-04-01T00:00:00Z',
    'due_date_on_or_before' => '2025-04-30T00:00:00Z',
    'completed' => false,
    'cursor' => 'aabbccdd...'
])

Create a Task

$task = ChartMogul\Task::create([
    'customer_uuid' => $customer_uuid,
    'task_details' => 'This is some task details text.',
    'assignee' => 'customer@example.com',
    'due_date' => '2025-04-30T00:00:00Z',
    'completed_at' => '2025-04-20T00:00:00Z',
])

Create a Task for a contact

$task = ChartMogul\Task::create([
    'associated_object_identifier' => [
        'associated_object' => 'contact',
        'method' => 'uuid',
        'value' => $contact_uuid
    ],
    'task_details' => 'Call the contact back.',
    'assignee' => 'customer@example.com',
    'due_date' => '2025-04-30T00:00:00Z',
])

Tasks expose customer_uuid (null for contact tasks) and, where available, associated_object (customer or contact) and associated_object_uuid.

Get a Task

$task = ChartMogul\Task::retrieve($task_uuid)

Update a Task

$updated_task = ChartMogul\Task::update([
    'uuid' => $task_uuid
], [
  'task_details' => 'This is some other task details text.'
]);

If the request contains nothing to update, the API responds with 304 Not Modified and an empty Task (all properties null) is returned.

Delete a Task

$task = ChartMogul\Task::retrieve($task_uuid)
$task->destroy();

Plans

Import a Plan

ChartMogul\Plan::create([
    "data_source_uuid" => $ds->uuid,
    "name" => "Bronze Plan",
    "interval_count" => 1,
    "interval_unit" => "month",
    "external_id" => "plan_0001"
]);

Get a Plan by UUID

ChartMogul\Plan::retrieve($uuid);

List Plans

$plans = ChartMogul\Plan::all([
  'page' => 1
]);

Delete A Plan

$plan = ChartMogul\Plan::all()->last();
$plan->destroy();

Update A Plan

$plan = ChartMogul\Plan::update(["plan_uuid" => $plan->uuid], [
            "name" => "Bronze Monthly Plan",
            "interval_count" => 1,
            "interval_unit" => "month"
]);

Subscription Events

List Subscriptions Events

$subscription_events = ChartMogul\SubscriptionEvent::all();

Create Subscription Event

ChartMogul\SubscriptionEvent::create(['subscription_event' => [
    "external_id" => "evnt_026",
    "customer_external_id" => "cus_0003",
    "data_source_uuid" => $ds->uuid,
    "event_type" => "subscription_start_scheduled",
    "event_date" => "2022-03-30",
    "effective_date" => "2022-04-01",
    "subscription_external_id" => "sub_0001",
    "plan_external_id" => "plan_0001",
    "currency" => "USD",
    "amount_in_cents" => 1000
    "quantity" => 1
]]);

Delete Subscription Event

ChartMogul\SubscriptionEvent::destroyWithParams(['subscription_event' => [
    "id" => "some_event_id"
]]);

Update Subscription Event

ChartMogul\SubscriptionEvent::updateWithParams(['subscription_event' => [
    "id" => "some_event_id",
    "currency" => "EUR",
    "amount_in_cents" => "100"
]]);

Plan Groups

Create a Plan Group

ChartMogul\PlanGroup::create([
    "name" => "Bronze Plan",
    "plans" => [$plan_uuid_1, $plan_uuid_2],
]);

Get a Plan Group by UUID

ChartMogul\PlanGroup::retrieve($uuid);

List Plan Groups

$plan_groups = ChartMogul\PlanGroup::all([
  'page' => 1
]);

Delete A Plan Group

$plan_group = ChartMogul\PlanGroup::all()->last();
$plan_group->destroy();

Update A Plan Group

$plan_group = ChartMogul\PlanGroup::update(
  ["plan_group_uuid" => $plan_group->uuid],
  [
  "name" => "A new plan group name",
  "plans" => [$plan_uuid_1, $plan_uuid_2]
]);

List Plans In A Plan Group

$plan_group_plans = ChartMogul\PlanGroups\Plan::all(
  ["plan_group_uuid" => $plan_group->uuid]
);

Invoices

Import Invoices

$plan = ChartMogul\Plan::all()->first();
$cus = ChartMogul\Customer::all()->first();

$line_item_1 = new ChartMogul\LineItems\Subscription([
    'subscription_external_id' => "sub_0001",
    'subscription_set_external_id' => 'set_0001',
    'plan_uuid' =>  $plan->uuid,
    'service_period_start' =>  "2015-11-01 00:00:00",
    'service_period_end' =>  "2015-12-01 00:00:00",
    'amount_in_cents' => 5000,
    'quantity' => 1,
    'discount_code' => "PSO86",
    'discount_amount_in_cents' => 1000,
    'tax_amount_in_cents' => 900,
    'transaction_fees_currency' => "EUR",
    'discount_description' => "5 EUR"
]);

$line_item_2 = new ChartMogul\LineItems\OneTime([
    "description" => "Setup Fees",
    "amount_in_cents" => 2500,
    "quantity" => 1,
    "discount_code" => "PSO86",
    "discount_amount_in_cents" => 500,
    "tax_amount_in_cents" => 450,
    "transaction_fees_currency" => "EUR",
    "discount_description" => "2 EUR"
]);

$transaction = new ChartMogul\Transactions\Payment([
    "date" => "2015-11-05T00:14:23.000Z",
    "result" => "successful"
]);

$invoice = new ChartMogul\Invoice([
    'external_id' => 'INV0001',
    'date' =>  "2015-11-01 00:00:00",
    'currency' => 'USD',
    'due_date' => "2015-11-15 00:00:00",
    'line_items' => [$line_item_1, $line_item_2],
    'transactions' => [$transaction]
]);

$ci = ChartMogul\CustomerInvoices::create([
    'customer_uuid' => $cus->uuid,
    'invoices' => [$invoice]
]);

List Customer Invoices

$ci = ChartMogul\CustomerInvoices::all([
    'customer_uuid' => $cus->uuid,
    'page' => 1,
    'per_page' => 200
]);

List Invoices

$invoices = ChartMogul\Invoice::all([
    'external_id' => 'my_invoice',
    'page' => 1,
    'per_page' => 200
]);

Retrieve an Invoice

$invoice = ChartMogul\Invoice::retrieve('inv_uuid');

Update an Invoice Status

ChartMogul\Invoice::updateStatus(
    'ds_35542640-d9f1-11ed-9c30-7727168c74a5', // data_source_uuid
    'inv_0001',                                  // invoice_external_id
    ['status' => 'voided']
);

Disable an Invoice

ChartMogul\Invoice::disable('inv_565c73b2-85b9-49c9-a25e-2b7df6a677c9', true);
// Re-enable:
ChartMogul\Invoice::disable('inv_565c73b2-85b9-49c9-a25e-2b7df6a677c9', false);

Line Items

Retrieve a Line Item

$lineItem = ChartMogul\LineItem::retrieve('li_592f4699-107b-41b9-b7bc-a2aa2ca7a67b');

Update a Line Item

$lineItem = ChartMogul\LineItem::update(
    ['line_item_uuid' => 'li_592f4699-107b-41b9-b7bc-a2aa2ca7a67b'],
    ['amount_in_cents' => 5000]
);

Delete a Line Item

$lineItem = new ChartMogul\LineItem(['uuid' => 'li_592f4699-107b-41b9-b7bc-a2aa2ca7a67b']);
$lineItem->destroy();

Disable a Line Item

ChartMogul\LineItem::disable('li_592f4699-107b-41b9-b7bc-a2aa2ca7a67b', true);
// Re-enable:
ChartMogul\LineItem::disable('li_592f4699-107b-41b9-b7bc-a2aa2ca7a67b', false);

Retrieve a Line Item by External ID

$lineItem = ChartMogul\LineItem::retrieveByExternalId(
    'ds_1fm3eaac-62d0-31ec-clf4-4bf0mbe81aba',
    'il_1Srh42DZd9drsue4U2FQKjsb'
);

Update a Line Item by External ID

$lineItem = ChartMogul\LineItem::updateByExternalId(
    'ds_1fm3eaac-62d0-31ec-clf4-4bf0mbe81aba',
    'il_1Srh42DZd9drsue4U2FQKjsb',
    ['amount_in_cents' => 5000]
);

Delete a Line Item by External ID

ChartMogul\LineItem::destroyByExternalId(
    'ds_1fm3eaac-62d0-31ec-clf4-4bf0mbe81aba',
    'il_1Srh42DZd9drsue4U2FQKjsb'
);

Transactions

Create a Transaction

ChartMogul\Transactions\Refund::create([
    "invoice_uuid" => $ci->invoices[0]->uuid,
    "date" => "2015-12-25 18:10:00",
    "result" => "successful"
]);

The same can be done with Payment class.

Retrieve a Transaction

$transaction = ChartMogul\Transaction::retrieve('tr_0e4de894-83c3-44d8-b406-2b0f89e67fda');

Update a Transaction

$transaction = ChartMogul\Transaction::update(
    ['transaction_uuid' => 'tr_0e4de894-83c3-44d8-b406-2b0f89e67fda'],
    ['date' => '2026-02-01T00:00:00Z']
);

Delete a Transaction

$transaction = new ChartMogul\Transaction(['uuid' => 'tr_0e4de894-83c3-44d8-b406-2b0f89e67fda']);
$transaction->destroy();

Disable a Transaction

ChartMogul\Transaction::disable('tr_0e4de894-83c3-44d8-b406-2b0f89e67fda', true);
// Re-enable:
ChartMogul\Transaction::disable('tr_0e4de894-83c3-44d8-b406-2b0f89e67fda', false);

Retrieve a Transaction by External ID

$transaction = ChartMogul\Transaction::retrieveByExternalId(
    'ds_1fm3eaac-62d0-31ec-clf4-4bf0mbe81aba',
    'ch_3St2vHDZd9drsue42v3rkVMC'
);

Update a Transaction by External ID

$transaction = ChartMogul\Transaction::updateByExternalId(
    'ds_1fm3eaac-62d0-31ec-clf4-4bf0mbe81aba',
    'ch_3St2vHDZd9drsue42v3rkVMC',
    ['date' => '2026-02-01T00:00:00Z']
);

Delete a Transaction by External ID

ChartMogul\Transaction::destroyByExternalId(
    'ds_1fm3eaac-62d0-31ec-clf4-4bf0mbe81aba',
    'ch_3St2vHDZd9drsue42v3rkVMC'
);

Subscriptions

List Customer Subscriptions

$subscriptions = $cus->subscriptions();

Note: The following methods are deprecated. Use ChartMogul\Metrics\Customers\Subscription::connect() and ChartMogul\Metrics\Customers\Subscription::disconnect() instead. See the Connect/Disconnect Subscriptions section above for recommended usage.

Cancel Customer Subscriptions

$subscription = new ChartMogul\Subscription(["uuid" => $subsUUID])
// or use some existing instance of subsctiption, eg. fetched from Customer->subscriptions
$canceldate = '2016-01-01T10:00:00.000Z';
$subscription->cancel($canceldate);

Or set the cancellation dates:

$subscription = new ChartMogul\Subscription(["uuid" => $subsUUID])
$cancellationDates = ['2016-01-01T10:00:00.000Z', '2017-01-01T10:00:00.000Z']
$subscription->setCancellationDates($cancellationDates)

Metrics API

Retrieve all key metrics

ChartMogul\Metrics::all([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
    'interval' => 'month',
    'geo' => 'GB',
    'plans' => $plan->name,
    'filters' => "currency~ANY~'USD'"
]);

Retrieve MRR

ChartMogul\Metrics::mrr([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
    'interval' => 'month',
    'geo' => 'GB',
    'plans' => $plan->name,
    'filters' => "currency~ANY~'USD'"
]);

Retrieve ARR

ChartMogul\Metrics::arr([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
    'interval' => 'month'
]);

Retrieve Average Revenue Per Account (ARPA)

ChartMogul\Metrics::arpa([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
    'interval' => 'month'
]);

Retrieve Average Sale Price (ASP)

ChartMogul\Metrics::asp([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
    'interval' => 'month',
]);

Retrieve Customer Count

ChartMogul\Metrics::customerCount([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
    'interval' => 'month',
]);

Retrieve Customer Churn Rate

ChartMogul\Metrics::customerChurnRate([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
]);

Retrieve MRR Churn Rate

ChartMogul\Metrics::mrrChurnRate([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
]);

Retrieve LTV

ChartMogul\Metrics::ltv([
    'start-date' => '2015-01-01',
    'end-date' => '2015-11-24',
]);

List Customer Subscriptions

ChartMogul\Metrics\Customers\Subscriptions::all([
    "customer_uuid" => $cus->uuid
]);

List Customer Activities

ChartMogul\Metrics\Customers\Activities::all([
    "customer_uuid" => $cus->uuid
]);

List Activities

ChartMogul\Metrics\Activities::all([
    'start-date' => '2020-06-02T00:00:00Z',
    'per-page' => 100
]);

**Create an Activities Export**

```php
ChartMogul\Metrics\ActivitiesExport::create([
    'start-date' => '2020-06-02T00:00:00Z',
    'end-date' =>  '2021-06-02T00:00:00Z'
    'type' => 'churn'
]);

Retrieve an Activities Export

$id = '7f554dba-4a41-4cb2-9790-2045e4c3a5b1';
ChartMogul\Metrics\ActivitiesExport::retrieve($id);

Account

Retrieve Account Details

ChartMogul\Account::retrieve();

Exceptions

The library throws following Exceptions:

  • ChartMogul\Exceptions\ChartMogulException
  • ChartMogul\Exceptions\ConfigurationException
  • ChartMogul\Exceptions\ForbiddenException
  • ChartMogul\Exceptions\NetworkException
  • ChartMogul\Exceptions\NotFoundException
  • ChartMogul\Exceptions\ResourceInvalidException
  • ChartMogul\Exceptions\SchemaInvalidException

A 304 Not Modified response (returned by update calls that contain nothing to change) does not throw; the call returns an empty resource object instead.

The following table describes the public methods of the error object.

Methods Type Description
getMessage() string The error message
getStatusCode() number When the error occurs during an HTTP request, the HTTP status code.
getResponse() array or string HTTP response as array, or raw response if not parsable to array

Rate Limits & Exponential Backoff

The library will keep retrying if the request exceeds the rate limit or if there's any network related error. By default, the request will be retried for 20 times (approximated 15 minutes) before finally giving up.

You can change the retry count using Configuration object:

ChartMogul\Configuration::getDefaultConfiguration()
    ->setApiKey('<YOUR_API_KEY>')
    ->setRetries(15); //0 disables retrying

Development

You need Docker installed locally to use our Makefile workflow.

  • Fork it.
  • Create your feature branch (git checkout -b my-new-feature).
  • Install dependencies: make build.
  • Install Composer vendor dependencies with make composer install
  • Write tests for your new features. Run tests and check test coverage with make test.
  • To run any composer commands or php scripts, use make composer <commands> or make php <script>.
  • If all tests are passed, push to the branch (git push origin my-new-feature).
  • Create a new Pull Request.

Releasing

See RELEASING.md for the full release process.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/chartmogul/chartmogul-php.

Security

Verifying Releases

All releases of this library are published as immutable GitHub Releases with protected tags and as a package on Packagist.

To maximize supply chain security:

  • Commit your composer.lock to version control - it records content hashes for all dependencies, ensuring reproducible and tamper-evident installs
  • Use composer install (not composer update) in CI environments for deterministic builds from the lockfile

License

The library is available as open source under the terms of the MIT License.

The MIT License (MIT)

Copyright (c) 2019 ChartMogul Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.