luketowers / php-shopify-api
Shopify API 的 PHP 封装器
v1.1.0
2024-06-01 08:47 UTC
Requires
- php: >=7.0
- guzzlehttp/guzzle: ~6.0|~7.0
This package is auto-updated.
Last update: 2024-08-31 09:15:52 UTC
README
这是一个围绕 Shopify API 的简单 PHP 封装器。
安装
通过在项目目录中运行 composer require luketowers/php-shopify-api
,使用 Composer 进行安装。
用法
为了使用此封装库,您需要提供凭证以访问 Shopify 的 API。
您可能需要一个访问令牌来访问您正在尝试访问的商店(如果使用 公开应用程序)或 私有应用程序 的 API 密钥和密钥。
示例
执行 API 调用
use LukeTowers\ShopifyPHP\Shopify; // Initialize the client $api = new Shopify('exampleshop.myshopify.com', 'mysupersecrettoken'); // Get all products $result = $api->call('GET', 'admin/products.json'); // Get the products with ids of '632910392' and '921728736' with only the 'id', 'images', and 'title' fields $result = $api->call('GET', 'admin/products.json', [ 'ids' => '632910392,921728736', 'fields' => 'id,images,title', ]); // Create a new "Burton Custom Freestyle 151" product $result = $api->call('POST', 'admin/products.json', [ 'product' => [ "title" => "Burton Custom Freestyle 151", "body_html" => "<strong>Good snowboard!</strong>", "vendor" => "Burton", "product_type" => "Snowboard", "tags" => 'Barnes & Noble, John's Fav, "Big Air"', ], ]);
使用私有应用程序 API 凭证对 API 请求进行身份验证
use LukeTowers\ShopifyPHP\Shopify; $api = new Shopify($data['shop'], [ 'api_key' => '...', 'secret' => '...', ]);
使用访问令牌对 API 请求进行身份验证
use LukeTowers\ShopifyPHP\Shopify; $storedToken = ''; // Retrieve the stored token for the shop in question $api = new Shopify('exampleshop.myshopify.com', $storedToken);
为商店请求 access_token
use LukeTowers\ShopifyPHP\Shopify; function make_authorization_attempt($shop, $scopes) { $api = new Shopify($shop, [ 'api_key' => '...', 'secret' => '...', ]); $nonce = bin2hex(random_bytes(10)); // Store a record of the shop attempting to authenticate and the nonce provided $storedAttempts = file_get_contents('authattempts.json'); $storedAttempts = $storedAttempts ? json_decode($storedAttempts) : []; $storedAttempts[] = ['shop' => $shop, 'nonce' => $nonce, 'scopes' => $scopes]; file_put_contents('authattempts.json', json_encode($storedAttempts)); return $api->getAuthorizeUrl($scopes, 'https://example.com/handle/shopify/callback', $nonce); } header('Location: ' . make_authorization_attempt('exampleshop.myshopify.com', ['read_product'])); die();
处理 Shopify 对授权请求的响应
use LukeTowers\ShopifyPHP\Shopify; function check_authorization_attempt() { $data = $_GET; $api = new Shopify($data['shop'], [ 'api_key' => '...', 'secret' => '...', ]); $storedAttempt = null; $attempts = json_decode(file_get_contents('authattempts.json')); foreach ($attempts as $attempt) { if ($attempt->shop === $data['shop']) { $storedAttempt = $attempt; break; } } return $api->authorizeApplication($storedAttempt->nonce, $data); } $response = check_authorization_attempt(); if ($response) { // Store the access token for later use $response->access_token; }