moltin/php-sdk

此包已被弃用,不再维护。未建议替代包。
此包的最新版本(2.0.2)没有可用的许可证信息。

Moltin PHP SDK 是一个简单易用的接口,用于API,帮助您快速高效地启动。

2.0.2 2017-10-11 09:11 UTC

README

这是与 moltin 交互的官方PHP SDK。

注意: master 设计用于访问API的 V2。如果您想访问API的旧版 V1,请使用最新的 1.x.x 标签

安装

您可以通过手动安装或将其添加到您的 composer.json 中来安装此包。

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

实例化SDK客户端

将配置传递给客户端

$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);

或在构造后进行配置

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

注意:如果您不确定您的 client_idclient_secret 是什么,请选择您的账户中的 商店 并复制它们。

企业客户

如果您是企业客户,并且拥有自己的带有自己域名的基础设施,您可以配置客户端以使用您的域。

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

或者通过将 api_endpoint 字段添加到传递给构造函数的 $config 数组中。

使用客户端

多个资源

返回您的资源列表(根据您的商店配置限制为100个)

// 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();

通过ID获取单个资源

通过ID获取资源

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

获取分类/品牌/集合树

分类、品牌和集合可以嵌套以创建树结构(参见 CategoryRelationships 示例)。

您可以使用 tree 方法检索项目完整树,而不是必须构建它们。

$moltin->categories->tree();

限制和偏移结果

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

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

排序结果

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

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

过滤结果

当调用支持它的资源时,可以 过滤结果(例如, /v2/products)。

一个简单的过滤器,获取所有有库存的产品可能如下所示

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

一个更复杂的过滤器,以找到数字、草稿且库存大于20的产品可能如下所示

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

传递给 filter 方法的 array 应包含 API 过滤器所需满足的所有条件,并允许您使用同一类型的多个过滤器(如上所示)。

有关过滤器操作的更多信息,请参阅 API 参考

包含数据

要将其他数据包含在您的请求中(例如获取类别时包含产品),请在资源上调用 with() 方法。

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

创建关系

// 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', []);

请求特定货币

对于支持 X-MOLTIN-CURRENCY 标头的调用,您可以在客户端指定它。

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

处理文件

v2/files 端点发送 POST 请求允许您上传文件并将其远程存储。

要使用 SDK 创建文件,您需要在磁盘上拥有该文件。

// 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']);

集成

$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');

获取日志

// 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();

网关

您可以使用 SDK 管理您的支付网关。

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

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

购物车、订单和支付

为了简化您处理购物车、订单和支付的方式,我们提供了一些实用函数。

购物车

向购物车添加项目

$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)

如果没有提供购物车引用,我们将从 $_COOKIE 中获取它。您可以在实例化客户端时通过传递配置来更改在 $_COOKIE 中使用的名称。

因此这是一个有效的调用(尽管如果从上面的示例继续操作,购物车将是一个新的购物车)

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

获取购物车项目

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

更新购物车中项目的数量

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

从购物车中删除项目

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

订单

将购物车转换为订单(然后可以进行支付)

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

支付

当您从结账方法获取到 Moltin\Entities\Order 对象时,您可以为此订单进行支付。

$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);

现在您可以检查响应($payment)以查看您的支付发生了什么。

您还可以为大多数支付网关设置测试详情,请参阅它们的详细信息,并查看有关 cart -> order -> pay 的更多信息 示例

处理异常

除了可能由于调用而发生的错误外,还可能抛出其他异常。要处理它们,只需将您的调用包裹在 try-catch 块中即可。

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

内部,可能会引发几个自定义异常 - 有关更多信息,请参阅 Exceptions 目录。

示例

examples 目录中,有一些使用 SDK 的命令行实现。要使用示例,您需要

  • 使用 composer install 安装依赖项
  • examples/.env.tmpl 复制到 examples/.env 并将其中的凭据添加到其中。
  • 运行您想要的示例文件,例如: php ./ProductList.php

默认情况下,对于成功的调用,我们将在命令行上以表格形式显示数据。然而,您可以使用标志来查看响应

php ./ProductList.php format=json

测试

phpunit

生成覆盖率报告

phpunit --coverage-html ./ignore