PHPackages                             moltin/php-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. moltin/php-sdk

AbandonedArchivedLibrary[API Development](/categories/api)

moltin/php-sdk
==============

The Moltin PHP SDK is a simple to use interface for the API to help you get off the ground quickly and efficiently

2.0.2(8y ago)467.3k18[2 issues](https://github.com/moltin/php-sdk/issues)[2 PRs](https://github.com/moltin/php-sdk/pulls)PHPPHP &gt;=5.5.0

Since Oct 17Pushed 7y agoCompare

[ Source](https://github.com/moltin/php-sdk)[ Packagist](https://packagist.org/packages/moltin/php-sdk)[ RSS](/packages/moltin-php-sdk/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (10)Dependencies (5)Versions (17)Used By (0)

moltin PHP SDK
==============

[](#moltin-php-sdk)

This official PHP SDK for interacting with **moltin**.

NOTE: `master` is designed to access `V2` of the API. If you want legacy access to `V1` of the API, please use the most recent `1.x.x` [tag](https://github.com/moltin/php-sdk/releases)

Installation
------------

[](#installation)

You can install the package manually or by adding it to your `composer.json`:

```
{
  "require": {
      "moltin/php-sdk": "^2.0.0"
  }
}

```

Instantiating the SDK Client:
-----------------------------

[](#instantiating-the-sdk-client)

Pass in the configuration to the client:

```
$config = [
    'client_id' => '{your_client_id}',
    'client_secret' => '{your_client_secret}',
    'currency_code' => 'USD',
    'language' => 'en',
    'locale' => 'en_gb',
    'cookie_cart_name' => 'moltin_cart_reference',
    'cookie_lifetime' => '+28 days'
];
$moltin = new Moltin\Client($config);
```

Or configure after construct:

```
$moltin = new Moltin\Client()
            ->setClientID('xxx')
            ->setClientSecret('yyy')
            ->setCurrencyCode('USD')
            ->setLanguage('en')
            ->setLocale('en_gb')
            ->setCookieCartName('moltin_cart_reference')
            ->setCookieLifetime('+28 days');
```

**Note:** if you are unsure what your `client_id` or `client_secret` are, please select the [store in your account](https://accounts.moltin.com) and copy them.

Enterprise Customers
--------------------

[](#enterprise-customers)

If you are an enterprise customer and have your own infrastructure with your own domain, you can configure the client to use your domain:

```
$moltin->setBaseURL('https://api.yourdomain.com');
```

Or by adding the `api_endpoint` field to the `$config` array you pass to the constructor.

Using the client
----------------

[](#using-the-client)

### Multiple Resources

[](#multiple-resources)

To return a list of your resources (limited to 100 depending your store configuration):

```
// return a list of your products
$moltin->products->all();

// return your brands
$moltin->brands->all();

// return your categories
$moltin->categories->all();

// return your collections
$moltin->collections->all();

// return your files
$moltin->files->all();
```

### Single Resource by ID

[](#single-resource-by-id)

Fetch a Resource by ID:

```
$moltin->products->get($productID);
```

### Fetching the category/brand/collection tree

[](#fetching-the-categorybrandcollection-tree)

Categories, brands and collections can be nested to create a tree structure (see the [CategoryRelationships](examples/CategoryRelationships.php) example).

You can retrieve a full tree of the items rather than having to build them by using `tree` method:

```
$moltin->categories->tree();
```

### Limiting and Offsetting Results

[](#limiting-and-offsetting-results)

```
// limit the number of resources returned:
$moltin->products->limit(10)->all();

// offset the results (page 2):
$moltin->products->limit(10)->offset(10)->all();
```

### Sorting Results

[](#sorting-results)

```
// order by `name`:
$moltin->products->sort('name')->all();

// reversed:
$moltin->products->sort('-name')->all();
```

### Filtering Results

[](#filtering-results)

To [filter your results](https://docs.moltin.com/#filtering) when calling resources which support it (e.g. `/v2/products`).

A simple filter to get all products which are in stock may look like this:

```
$moltin->products->filter([
    'gt' => ['stock' => 0]
])->all();
```

A more advanced filter to find products which are digital, drafted and have a stock greater than 20 would look like this:

```
$moltin->products->filter(new \Moltin\Filter([
    'eq' => ['status' => 'draft', 'commodity_type' => 'digital'],
    'gt' => ['stock' => 20]
])->all();
```

The `array` passed to the `filter` method should contain all of the conditions required to be met by the filter on the API and allow you to use several filters of the same type (as demostrated above).

For more information on the filter operations please read the [API reference](https://docs.moltin.com/#filtering).

### Including data

[](#including-data)

To include other data in your request (such as products when getting a category) call the `with()` method on the resource:

```
$response = $moltin->categories->with(['products'])->get($categoryID);
$category = $response->data();
$products = $response->included()->products;
```

### Create Relationships

[](#create-relationships)

```
// create relationships between resources:
$moltin->products->createRelationships($productID, 'categories', [$categoryID]);

// delete a relationship between resources:
$moltin->products->deleteRelationships($productID, 'categories', [$categoryID]);

// (Or an update with an empty array achieves the same result if you're so inclined):
$moltin->products->updateRelationships($productID, 'categories', []);
```

### Requesting a Specific Currency

[](#requesting-a-specific-currency)

For calls that support the `X-MOLTIN-CURRENCY` header, you can specifiy it on the client:

```
$moltin->currency('USD')->products->all();
$moltin->currency('GBP')->products->all();
```

### Working with files

[](#working-with-files)

A `POST` request to the `v2/files` endpoint allows you to upload a file and store it remotely.

To create a file using the SDK, you need to have the file on disk:

```
// create a file from a local disk
$moltin->files->create(['public' => 'true', 'file' => '/path/to/file.jpg']);

// create a file from a URL (note: this will download the file to your local disk then upload)
$moltin->files->create(['public' => 'true', 'file' => 'https://placeholdit.imgix.net/~text?&w=350&h=150']);
```

### Integrations

[](#integrations)

```
$moltin->integrations->all();
$moltin->integrations->create([
    'type' => 'integration',
    'integration_type' => 'webhook',
    'enabled' => true,
    'name' => 'My Webhook Name',
    'description' => 'An example webhook integration from the SDK',
    'observes' => [
        'product.created',
        'product.updated',
        'product.deleted'
    ],
    'configuration' => [
        'url' => 'https://your.domain.com/webhooks',
        'secret' => 'opensesame'
    ]
]);
$moltin->integrations->update('55f33a71-b45a-4c30-a872-6e6a0f442af1', [
    'data' => [
        'id' => '55f33a71-b45a-4c30-a872-6e6a0f442af1',
        'type' => 'integration',
        'integration_type' => 'webhook',
        'enabled' => false,
        'name' => 'Updated Webhook Name',
        'description' => 'An updated example webhook integration from the SDK',
        'observes' => [
            'product.deleted'
        ],
        'configuration' => [
            'url' => 'https://your.domain.com/webhooks',
            'secret' => 'opensesame'
        ]
    ]
]);
$moltin->integrations->get('55f33a71-b45a-4c30-a872-6e6a0f442af1');
$moltin->integrations->delete('55f33a71-b45a-4c30-a872-6e6a0f442af1');
```

#### Getting Logs

[](#getting-logs)

```
// get all integration logs for your store:
$logs = $moltin->integrations->getLogs()->data();

// get all jobs for an integration:
$jobs = $moltin->integrations->getJobs($integrationID)->data();

// get all logs for job:
$logs = $moltin->integrations->getLogs($integrationID, $jobID)->data();
```

### Gateways

[](#gateways)

Your payment gateways can be managed using the SDK.

```
// get all
$gateways = $moltin->gateways->all();

// update
$moltin->gateways->update('stripe', [
    'data' => [
        'enabled': true,
        'login': 'your_stripe_login'
    ]
])
```

### Carts, Orders and Payments

[](#carts-orders-and-payments)

To simplify the way you process carts, orders and payments, we provide some utility functions.

#### Carts

[](#carts)

Adding items to a cart:

```
$cartReference = 'a_unique_refeference'; // supply a custom cart reference
$moltin->cart($cartReference)->addProduct($productID); // adds 1 x $productID
$moltin->cart($cartReference)->addProduct($productID, 3); // adds 3 x $productID (now has 4)
```

When no cart reference is supplied, we will get it from the `$_COOKIE`. You can change the name used in the `$_COOKIE` by passing it in the config when instantiating the client.

This is therefore a valid call (although the cart will be a new one if you follow on from the example above):

```
$moltin->cart()->addProduct($productID);
```

Get the cart items:

```
foreach($moltin->cart()->items() as $item) {
    $cartItemID = $item->id;
    // ... do something
    echo $item->name . "\n";
}
```

Update the quantity of an item in the cart:

```
$moltin->cart()->updateItemQuantity($cartItemID, 2); // now has 2
```

Remove an item from the cart:

```
$moltin->cart()->removeItem($cartItemID);
```

#### Orders

[](#orders)

To convert a cart to an order (which can then be paid):

```
$customer = [
    // ... customer data
];
$billing = [
    // ... billing data
];
$shipping = [
    // ... shipping data
];
$order = $moltin->cart($cartReference)->checkout($customer, $billing, $shipping);
```

#### Payments

[](#payments)

When you have a `Moltin\Entities\Order` object from the checkout method you can take a payment for it:

```
$gatewaySlug = 'stripe'; // the slug of your payment gateway
$paymentMethod = 'purchase'; // the order payment method (purchase is supported for now)
$params = []; // payment params (these will vary depending on the gateway, check out the example for Stripe and the docs for others)
$payment = $order->pay($gatewaySlug, $paymentMethod, $params);
```

You can now check the response (`$payment`) to see what happened with your payment.

You can also setup test details for most payment gateways, please refer to them for their details and check out the [example](examples/Carts.php) for more informatiom on `cart -> order -> pay`.

Handling Exceptions
-------------------

[](#handling-exceptions)

Aside from errors that may occur due to the call, there may be other Exceptions thrown. To handle them, simply wrap your call in a try catch block:

```
try {
    $moltin->products->all();
} catch (Exception $e) {
    // do something with $e
}
```

Internally, there are several custom Exceptions which may be raised - see the [Exceptions](src/Exceptions) directory for more information.

Examples
--------

[](#examples)

In the `examples` directory there are command line implementations using the SDK. To use the examples you will need to:

- Install dependencies with `composer install`
- Copy the `examples/.env.tmpl` to `examples/.env` and add your credentials to it.
- Run the example file you want, for example: `php ./ProductList.php`

By default, for successful calls, we will display the data in a table on the command line. You can, however, use a flag to view the response:

`php ./ProductList.php format=json`

Test
----

[](#test)

```
phpunit
```

Generate a coverage report:

```
phpunit --coverage-html ./ignore
```

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor3

3 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~60 days

Recently: every ~90 days

Total

13

Last Release

3138d ago

Major Versions

v1.x-dev → 2.0.02017-04-06

PHP version history (3 changes)1.0.0PHP &gt;=5.3.0

1.4-betaPHP &gt;=5.4.0

2.0.0PHP &gt;=5.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/a998c3c99f2ab63cb0535744d941499d064eba354b07d611c40aaaea9b28ee16?d=identicon)[moltin](/maintainers/moltin)

---

Top Contributors

[![anthonysterling](https://avatars.githubusercontent.com/u/159960?v=4)](https://github.com/anthonysterling "anthonysterling (37 commits)")[![Axhini](https://avatars.githubusercontent.com/u/20891107?v=4)](https://github.com/Axhini "Axhini (30 commits)")[![zot24](https://avatars.githubusercontent.com/u/678498?v=4)](https://github.com/zot24 "zot24 (24 commits)")[![outrunthewolf](https://avatars.githubusercontent.com/u/814246?v=4)](https://github.com/outrunthewolf "outrunthewolf (21 commits)")[![andrew-waters](https://avatars.githubusercontent.com/u/501976?v=4)](https://github.com/andrew-waters "andrew-waters (9 commits)")[![cheeryfella](https://avatars.githubusercontent.com/u/144487?v=4)](https://github.com/cheeryfella "cheeryfella (6 commits)")[![Jmz](https://avatars.githubusercontent.com/u/465552?v=4)](https://github.com/Jmz "Jmz (5 commits)")[![chrisnharvey](https://avatars.githubusercontent.com/u/619298?v=4)](https://github.com/chrisnharvey "chrisnharvey (3 commits)")[![notrab](https://avatars.githubusercontent.com/u/950181?v=4)](https://github.com/notrab "notrab (2 commits)")[![philipbrown](https://avatars.githubusercontent.com/u/1579059?v=4)](https://github.com/philipbrown "philipbrown (1 commits)")

---

Tags

moltinphpsdk

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/moltin-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/moltin-php-sdk/health.svg)](https://phpackages.com/packages/moltin-php-sdk)
```

###  Alternatives

[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3731.2M42](/packages/tencentcloud-tencentcloud-sdk-php)[convertkit/convertkitapi

Kit PHP SDK for the Kit API

2167.1k1](/packages/convertkit-convertkitapi)[mapado/rest-client-sdk

Rest Client SDK for hydra API

1125.9k2](/packages/mapado-rest-client-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
