arslanramay / php-shopify-api
使用 Guzzle 简单的 PHP API 包装器,用于 Shopify
v1.0.0
2024-06-05 09:53 UTC
Requires
- php: ^8.1
- guzzlehttp/guzzle: ^7.0
README
使用 Guzzle 简单的 PHP API 包装器为 Shopify Shopify API。
安装
通过在项目目录中运行 composer require arslanramay/php-shopify-api
使用 Composer 安装。
用法
为了使用此包装库,您需要提供访问 Shopify API 的凭证。
您可能需要一个访问令牌来访问您正在尝试访问的商店(如果使用的是 公开应用程序),或者需要一个 API 密钥和密钥来访问 私有应用程序。
代码示例
发起 API 请求
use arslanramay\ShopifyPHP\Shopify; // Initialize the client $shopify = new Shopify('exampleshop.myshopify.com', 'mysupersecrettoken'); // Get all products $result = $shopify->call('GET', 'admin/products.json'); // Get the products with ids of '9326553104669' and '9339160002845' with only the 'id', 'images', and 'title' fields $result = $shopify->call('GET', 'admin/products.json', [ 'ids' => '9326553104669,9339160002845', 'fields' => 'id,images,title', ]); // Create a new product with title "Kerastase Shampoo 150ml" $result = $shopify->call('POST', 'admin/products.json', [ 'product' => [ "title" => "Kerastase Shampoo 150ml", "body_html" => "<strong>Good shampoo for hair!</strong>", "vendor" => "Kerastase", "product_type" => "Shampoo", "tags" => 'Shampoo, Kerastase, "Hair Care"', ], ]);
使用私有应用程序 API 凭证进行 API 请求的身份验证
use arslanramay\ShopifyPHP\Shopify; $shopify = new Shopify($data['shop'], [ 'api_key' => '...', 'secret' => '...', ]);
使用访问令牌进行 API 请求的身份验证
use arslanramay\ShopifyPHP\Shopify; $storedToken = ''; // Retrieve the stored token for the shop in question $shopify = new Shopify('exampleshop.myshopify.com', $storedToken);
请求商店的访问令牌
use arslanramay\ShopifyPHP\Shopify; function make_authorization_attempt($shop, $scopes) { $shopify = 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 $shopify->getAuthorizeUrl($scopes, 'https://example.com/handle/shopify/callback', $nonce); } header('Location: ' . make_authorization_attempt('exampleshop.myshopify.com', ['read_product'])); die();
处理 Shopify 对授权请求的响应
use arslanramay\ShopifyPHP\Shopify; function check_authorization_attempt() { $data = $_GET; $shopify = 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 $shopify->authorizeApplication($storedAttempt->nonce, $data); } $response = check_authorization_attempt(); if ($response) { // Store the access token for later use $response->access_token; }