guzzle 封装api

tech2022-08-28  137

guzzle 封装api

This article was peer reviewed by Deji Akala. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

本文由Deji Akala进行同行评审。 感谢所有SitePoint的同行评审人员使SitePoint内容达到最佳状态!

In this tutorial, you’re going to get started with developing Shopify apps. You’re going to create a simple app that lists out products from a Shopify store. The full source code of the app is available on Github.

在本教程中,您将开始开发Shopify应用程序。 您将创建一个简单的应用程序,其中列出Shopify商店中的产品。 该应用程序的完整源代码可在Github上找到 。

什么是Shopify应用程序? (What are Shopify Apps?)

Shopify apps are a way of extending the functionality of a Shopify store or to provide ecommerce capabilities to websites or mobile apps. Here’s a list of approaches to do this:

Shopify应用程序是扩展Shopify商店功能或为网站或移动应用程序提供电子商务功能的一种方式。 以下是执行此操作的方法列表:

HTTP API – gives web apps the ability to perform different operations in a Shopify store. Things like adding a customer, getting a list of products, or listening for different events. This is done by means of webhooks.

HTTP API –使Web应用程序能够在Shopify商店中执行不同的操作。 诸如添加客户,获取产品列表或监听不同事件之类的事情。 这是通过webhooks来完成的。

JavaScript Buy SDK – allows you to fetch product information, add items to a cart and checkout either from a website or hybrid mobile apps such as those built with Cordova.

JavaScript Buy SDK –允许您从网站或混合移动应用程序(例如使用Cordova构建的移动应用程序)中获取产品信息,将商品添加到购物车以及结帐。

Embedded App SDK – allows you to embed your web app directly into the Shopify admin interface. This is useful for apps that have an admin settings page. Instead of the user having to access it on a separate website, the web app will be loaded as an iframe.

嵌入式应用程序SDK –允许您将Web应用程序直接嵌入Shopify管理界面。 这对于具有管理员设置页面的应用程序很有用。 无需用户在单独的网站上访问它,该Web应用程序将作为iframe加载。

iOS and Android Buy – used for integrating Shopify checkout into your iOS or Android app.

iOS和Android Buy –用于将Shopify结帐集成到您的iOS或Android应用程序中。

Shopify POS App SDK – allows you to embed your web apps directly inside the Shopify POS.

Shopify POS应用程序SDK –允许您将Web应用程序直接嵌入Shopify POS中 。

In this tutorial, you’re going to learn about the HTTP API.

在本教程中,您将学习HTTP API。

注册一个Shopify合作伙伴帐户 (Sign up for a Shopify Partner Account)

The first thing that you need to do is to sign up for a Shopify Partner Account. This allows you to create a development store for testing a Shopify app. You will be asked to fill out a form with things like your company name, business type, email address, website, password and other relevant information.

您需要做的第一件事就是注册一个Shopify合作伙伴帐户 。 这使您可以创建开发商店来测试Shopify应用。 系统将要求您填写表格,其中包含公司名称,业务类型,电子邮件地址,网站,密码和其他相关信息。

If all the information you provided is valid, you should be greeted with the following page:

如果您提供的所有信息都是有效的,则应显示以下页面:

创建开发商店 (Create a Development Store)

The next step is creating a development store which is like a Shopify store. You can add products, store HTML and CSS code for themes, and test purchases through a bogus payment gateway. The only limitation is that you can’t add a custom domain or charge customers in a development store.

下一步是创建类似于Shopify商店的开发商店。 您可以添加产品,存储主题HTML和CSS代码以及通过虚假的支付网关测试购买。 唯一的限制是您不能在开发商店中添加自定义域或向客户收费。

Click the Create a development store button and you will be redirected to the following page:

单击创建开发存储区按钮,您将被重定向到以下页面:

Add the store name, the password for logging in to the store (your Shopify partner email address is the login email), and the kind of store to create. Stick with an Online store for now. This gives you the ability to build custom themes, develop an app, or set up your client’s online store. Once you’re done with filling the form, click the Create Store button to create the development store.

添加商店名称,用于登录商店的密码(您的Shopify合作伙伴电子邮件地址是登录电子邮件)以及要创建的商店的类型。 立即使用在线商店。 这使您能够构建自定义主题,开发应用程序或建立客户的在线商店。 填写完表格后,单击“ 创建商店”按钮以创建开发商店。

设置开发商店 (Setting up the Development Store)

Once the development store is created, you can click the login link in the success alert message to log into the store. You’ll be greeted with the following page once logged in:

创建开发存储区后,您可以单击成功警报消息中的登录链接以登录到存储区。 登录后,您将看到以下页面:

You can start by selecting a product category. I’ve selected Electronics & Gadgets for mine.

您可以从选择产品类别开始。 我选择了我的电子产品和小工具 。

The next thing you can do is add products and customers to the store. You can do this by clicking either on the Products or Customers link in the side-menu. Adding those details will give you some data to work with once you start using the Shopify API.

您可以做的下一件事是将产品和客户添加到商店中。 您可以通过单击侧面菜单中的“ 产品”或“ 客户”链接来执行此操作。 一旦开始使用Shopify API,添加这些详细信息将为您提供一些数据。

The final step in setting up the development store is launching it. If you haven’t already noticed, Shopify doesn’t immediately make your store available to the rest of the world. If you go to https://{your-storename}.myshopify.com you’ll see an opening soon page. You can fix this by clicking on the Online Store link in the side-menu in the admin page. Then, click the select a free theme button to show the free themes that you can use. Select a theme from the list that shows up, then click the Publish theme button to use the theme for your store.

设置开发商店的最后一步是启动它。 如果您尚未注意到,Shopify不会立即将您的商店提供给世界其他地方。 如果您访问https://{your-storename}.myshopify.com ,则会看到“即将开业”页面。 您可以通过点击管理页面侧面菜单中的在线商店链接来解决此问题。 然后,单击选择免费主题按钮以显示您可以使用的免费主题。 从显示的列表中选择一个主题,然后单击“ 发布主题”按钮以将主题用于您的商店。

创建一个应用 (Creating an App)

Now you’re ready to create a new Shopify app. Head over to the Shopify partners website and in the side menu, click on Apps, then click the Create a new app button. This will show you the following interface:

现在,您可以创建一个新的Shopify应用了。 前往Shopify合作伙伴网站,并在侧面菜单中,点击Apps ,然后点击Create a new app按钮。 这将显示以下界面:

Enter the app name, the app URL and the redirect URL. The app URL and redirect URL can be a localhost path. Here’s an example:

输入应用名称,应用URL和重定向URL。 应用程序URL和重定向URL可以是本地主机路径。 这是一个例子:

http://localhost/shopify-tester http://localhost/shopify-tester/login

You can leave all the other fields at their default values, as you won’t really be touching on those in this tutorial. If you’re wondering about the Embedded App SDK and Shopify POS App SDK, you can leave those disabled since you will only be using the HTTP API.

您可以将所有其他字段保留为默认值,因为在本教程中您将不会真正涉及这些字段。 如果您想了解Embedded App SDK和Shopify POS App SDK,可以将其禁用,因为您将仅使用HTTP API。

Once the app is created, it should show you the app dashboard where the API key and secret are displayed. Take note of these because you’ll be using them later when making API requests.

创建应用后,它将向您显示应用仪表板,其中显示了API密钥和密钥。 请注意这些内容,因为稍后将在发出API请求时使用它们。

验证用户 (Authenticating Users)

Now that you have created an app and a development store to test on, it’s time to authenticate users so they can use your app. You might be thinking, why do I need to authenticate if I own the development store and the app? Well, a development store represents a real-world store owned by any Shopify user. This means they won’t have access to your app unless they install it. And in order to install it, they have to go through the OAuth authorization process first. This is pretty much the same as any authorization process for sites like Facebook or Google whenever you install a third-party app.

现在您已经创建了一个应用程序和一个开发商店进行测试,现在该对用户进行身份验证,以便他们可以使用您的应用程序。 您可能在想,如果我拥有开发商店和应用程序,为什么需要进行身份验证? 好吧,开发商店代表任何Shopify用户拥有的真实世界商店。 这意味着除非安装它们,否则他们将无权访问您的应用程序。 为了安装它,他们必须首先经过OAuth授权过程。 这与安装第三方应用程序时对Facebook或Google等网站的任何授权过程几乎相同。

The first step in the authorization process is for the user to install the app. Apps can be found on the Shopify App Store. You can only get your app listed once Shopify approves it. You can submit your app for approval by clicking the Edit App Store listing button on the app page. You won’t really go through that in this tutorial, so you’ll just directly access the install URL in the browser. Here’s the actual authorization process for an app that’s already listed in the app store:

授权过程的第一步是让用户安装应用程序。 可以在Shopify应用商店中找到应用 。 您只有在Shopify批准后才能列出您的应用。 您可以通过单击应用程序页面上的“ 编辑App Store列表”按钮来提交您的应用程序以供批准。 在本教程中,您将不会真正进行遍历,因此,您将直接在浏览器中访问安装URL。 这是已经在应用商店中列出的应用的实际授权过程:

User installs the app from the app store.

用户从应用商店中安装应用。 User gets redirected to the app install page. This is a page in the app, which means it is managed by you. The page asks for the name of the store (e.g. test-shop.myshopify.com).

用户被重定向到应用程序安装页面。 这是应用程序中的页面,这意味着它由您管理。 该页面询问商店名称(例如test-shop.myshopify.com)。

User clicks install.

用户单击安装 。

The app generates a unique string and saves it in the database along with the store name.

该应用程序生成一个唯一的字符串,并将其与商店名称一起保存在数据库中。

The app constructs the Shopify app authorization URL and redirects the user to it. This is the page where the user can see the name of the app and the list of permissions it’s asking for. From there, the user can click the Install app button.

该应用程序构造Shopify应用程序授权URL,并将用户重定向到该URL。 在此页面上,用户可以看到应用程序的名称以及所请求的权限列表。 用户可以从此处单击“ 安装应用程序”按钮。

Shopify redirects the user to the redirect URL that you have specified in your app settings. The access code, hmac, state, and timestamp are passed along to the redirect URL as query parameters.

Shopify将用户重定向到您在应用程序设置中指定的重定向URL。 访问代码,hmac,状态和时间戳作为查询参数传递到重定向URL。 The app verifies that the request is valid.

该应用程序验证请求是否有效。 If the request is valid, the app requests the permanent access token from the Shopify API.

如果请求有效,则应用程序从Shopify API请求永久访问令牌。 Save the access token along with the other important details to the app database.

将访问令牌以及其他重要详细信息保存到应用程序数据库。

演示应用 (Demo App)

We’ll now proceed with going through each of the steps, only step 1 will be replaced with accessing the install page directly in the browser. This page is responsible for initializing an app install request.

现在,我们将继续执行每个步骤,仅将步骤1替换为直接在浏览器中访问安装页面。 该页面负责初始化应用安装请求。

安装依赖项 (Installing the Dependencies)

composer require twig/twig guzzlehttp/guzzle nesbot/carbon vlucas/phpdotenv ircmaxell/random-lib

安装页面 (Install Page)

Create an install.php file and add the following code:

创建一个install.php文件并添加以下代码:

<?php require 'vendor/autoload.php'; $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); $db = new Mysqli(getenv('MYSQL_HOST'), getenv('MYSQL_USER'), getenv('MYSQL_PASS'), getenv('MYSQL_DB')); if (!empty($_POST)) { $store = $_POST['store']; $factory = new RandomLib\Factory; $generator = $factory->getMediumStrengthGenerator(); $nonce = $generator->generateString(20); $api_key = getenv('SHOPIFY_APIKEY'); $scopes = getenv('SHOPIFY_SCOPES'); $redirect_uri = urlencode(getenv('SHOPIFY_REDIRECT_URI')); if ($query = $db->prepare('INSERT INTO installs SET store = ?, nonce = ?, access_token = ""')) { $query->bind_param('ss', $store, $nonce); $query->execute(); $query->close(); $url = "https://{$store}/admin/oauth/authorize?client_id={$api_key}&scope={$scopes}&redirect_uri={$redirect_uri}&state={$nonce}"; header("Location: {$url}"); } } else { $loader = new Twig_Loader_Filesystem('templates'); $twig = new Twig_Environment($loader, [ 'cache' => 'cache', 'debug' => true ]); $template = $twig->loadTemplate('install.html'); echo $template->render([]); }

Breaking down the code above, we first connect to the MySQL database. You can find the schema in the Github repo.

分解上面的代码,我们首先连接到MySQL数据库。 您可以在Github存储库中找到该架构。

$db = new Mysqli(getenv('MYSQL_HOST'), getenv('MYSQL_USER'), getenv('MYSQL_PASS'), getenv('MYSQL_DB'));

This uses phpdotenv to load the configuration from the .env file at the root of the working directory. The .env file contains the following:

这使用phpdotenv从工作目录根目录下的.env文件加载配置。 .env文件包含以下内容:

MYSQL_HOST=localhost MYSQL_DB=shopifytester MYSQL_USER=YOUR_DB_USER MYSQL_PASS=YOUR_DB_PASSWORD SHOPIFY_APIKEY="YOUR SHOPIFY APP API KEY" SHOPIFY_SECRET="YOUR SHOPIFY APP SECRET" SHOPIFY_SCOPES="read_products,read_customers" SHOPIFY_REDIRECT_URI="http://localhost/shopify-tester/login.php"

Go ahead and replace the placeholder values with your own values. You can also replace the SHOPIFY_REDIRECT_URI if you used a different redirect URL.

继续,并将占位符值替换为您自己的值。 如果您使用其他重定向URL,也可以替换SHOPIFY_REDIRECT_URI 。

Next, check if the user has submitted the form. If not, return the install page:

接下来,检查用户是否已提交表单。 如果没有,请返回安装页面:

if (!empty($_POST)) { ... } else { $loader = new Twig_Loader_Filesystem('templates'); $twig = new Twig_Environment($loader, [ 'cache' => 'cache', 'debug' => true ]); $template = $twig->loadTemplate('install.html'); echo $template->render([]); }

The install page is located at templates/install.html and contains the following:

安装页面位于templates/install.html ,包含以下内容:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Install</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/picnic/6.1.1/picnic.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/picnic/6.1.1/plugins.min.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <nav> <a href="#" class="brand"> <span>Shopify App</span> </a> </nav> <main> <form method="POST"> <fieldset class="flex one"> <label> Store Name <input type="text" name="store" placeholder="e.g. test-shop.myshopify.com"> </label> </fieldset> <button>Install</button> </form> </main> </body> </html>

As you can see, it’s a pretty standard HTML page with a form asking for the store name.

如您所见,这是一个非常标准HTML页面,其中包含要求商店名称的表单。

picnic.css is used to beautify the page but there’s also the css/style.css file for adding the styles for the main content:

picnic.css用于美化页面,但还有css/style.css文件,用于添加主要内容的样式:

main { width: 500px; margin: 0 auto; padding-top: 150px; }

Going back to the install.php file, below is the code that is executed once the form is submitted. First, it generates a random string. This is used later on as an additional check if the authorization request is valid:

返回到install.php文件,以下是提交表单后执行的代码。 首先,它生成一个随机字符串。 稍后将其用作授权请求是否有效的附加检查:

$factory = new RandomLib\Factory; $generator = $factory->getMediumStrengthGenerator(); $nonce = $generator->generateString(20);

Insert the store name along with the random string into the database, then redirect the user to the Shopify authorization page:

将商店名称和随机字符串一起插入数据库,然后将用户重定向到Shopify授权页面:

$api_key = getenv('SHOPIFY_APIKEY'); $scopes = getenv('SHOPIFY_SCOPES'); $redirect_uri = urlencode(getenv('SHOPIFY_REDIRECT_URI')); if ($query = $db->prepare('INSERT INTO installs SET store = ?, nonce = ?, access_token = ""')) { $query->bind_param('ss', $store, $nonce); $query->execute(); $query->close(); $url = "https://{$store}/admin/oauth/authorize?client_id={$api_key}&scope={$scopes}&redirect_uri={$redirect_uri}&state={$nonce}"; header("Location: {$url}"); }

The authorization page URL needs the store, client_id, scope, redirect_uri, and state. The store is the name of the Shopify store (e.g. test-shop.myshopify.com), the client_id is the API key of your app and the redirect_uri is the redirection URL that you supplied to your app settings.

授权页面URL需要store , client_id , scope , redirect_uri和state 。 store是Shopify商店的名称(例如test-shop.myshopify.com), client_id是您的应用程序的API密钥, redirect_uri是您提供给应用程序设置的重定向URL。

If you decided to use a different redirection URL, you can always update the app settings to reflect the changes. The scope are the data you want the app to have access to. Here is the list of scopes that you can supply. For this tutorial, you’ll only be using the read_products and read_customers scopes. Each scope can be separated by a comma like so: read_products,read_customers. Lastly, the state is the random string that you have generated.

如果您决定使用其他重定向URL,则始终可以更新应用程序设置以反映更改。 scope是您希望应用访问的数据。 这是您可以提供的范围的列表 。 对于本教程,您将仅使用read_products和read_customers范围。 每个范围可以用逗号分隔,例如: read_products,read_customers 。 最后, state是您生成的随机字符串。

Once the values are substituted, the authorization URL should look something like this:

替换值后,授权URL应如下所示:

https://yourshopifystore.myshopify.com/admin/oauth/authorize?client_id=your_api_key&scope=read_products,read_customers&redirect_uri=http://localhost/shopify-tester/login.php&state=your_unique_key

The user is redirected to that URL and they will see the following screen:

用户被重定向到该URL,他们将看到以下屏幕:

The user can verify that the page is showing the correct app name and the scopes that you’ve asked for. If correct, the user can click the Install app button to install the app.

用户可以验证页面是否显示正确的应用程序名称以及您要求的范围。 如果正确,则用户可以单击“ 安装应用程序”按钮来安装应用程序。

From there, Shopify generates the access code and the HMAC (Keyed-hash message authentication code). Those are passed along with the shop, timestamp and the state to your redirect URL. In the app, you can use this information to verify that the request is valid.

Shopify从那里生成访问代码和HMAC(键哈希消息身份验证代码)。 这些信息与shop , timestamp和state一起传递到您的重定向URL。 在应用程序中,您可以使用此信息来验证请求是否有效。

授权页面 (Authorization Page)

Once Shopify redirects to the redirect URL, you’re responsible for verifying that the request is valid. If it is valid, make a request for the access token. Create an auth.php file at the root of your working directory and add the following code:

Shopify重定向到重定向URL后,您将负责验证请求是否有效。 如果有效,则请求访问令牌。 在工作目录的根目录中创建一个auth.php文件,并添加以下代码:

<?php require 'vendor/autoload.php'; use Carbon\Carbon; use GuzzleHttp\Client; $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); $db = new Mysqli(getenv('MYSQL_HOST'), getenv('MYSQL_USER'), getenv('MYSQL_PASS'), getenv('MYSQL_DB')); $api_key = getenv('SHOPIFY_APIKEY'); $secret_key = getenv('SHOPIFY_SECRET'); $query = $_GET; if (!isset($query['code'], $query['hmac'], $query['shop'], $query['state'], $query['timestamp'])) { exit; //or redirect to an error page } $one_minute_ago = Carbon::now()->subSeconds(60)->timestamp; if ($query['timestamp'] < $one_minute_ago) { exit; //or redirect to an error page } $hmac = $query['hmac']; $store = $query['shop']; unset($query['hmac']); foreach ($query as $key => $val) { $params[] = "$key=$val"; } asort($params); $params = implode('&', $params); $calculated_hmac = hash_hmac('sha256', $params, $secret_key); if($hmac == $calculated_hmac){ $client = new Client(); $response = $client->request( 'POST', "https://{$store}/admin/oauth/access_token", [ 'form_params' => [ 'client_id' => $api_key, 'client_secret' => $secret_key, 'code' => $query['code'] ] ] ); $data = json_decode($response->getBody()->getContents(), true); $access_token = $data['access_token']; $nonce = $query['state']; if ($select = $db->prepare("SELECT id FROM installs WHERE store = ? AND nonce = ?")) { $select->bind_param('ss', $store, $nonce); $select->execute(); $select->bind_result($id); $select->fetch(); $select->close(); if ($id > 0) { $db->query("UPDATE installs SET access_token = '$access_token' WHERE id = '$id'"); } } }

Breaking down the code above, first check if all the parameters that you’re expecting are passed along in the URL:

分解上面的代码,首先检查是否在URL中传递了您期望的所有参数:

$query = $_GET; if (!isset($query['code'], $query['hmac'], $query['shop'], $query['state'], $query['timestamp'])) { exit; //or redirect to an error page }

Save the value of the hmac to a variable because you need to unset it from the query parameters array. Then loop through the remaining parameters to construct an array containing a key-value pair.

将hmac的值保存到变量中,因为您需要从查询参数数组中将其取消设置。 然后遍历其余参数以构造包含键值对的数组。

$hmac = $query['hmac']; unset($query['hmac']); $params = []; foreach ($query as $key => $val) { $params[] = "$key=$val"; }

Sort the resulting array and convert it to a string:

对结果数组进行排序并将其转换为字符串:

asort($params); $params = implode('&', $params);

Calculate the hmac based on the parameters and the Shopify app secret key:

根据参数和Shopify应用秘密密钥计算hmac :

$calculated_hmac = hash_hmac('sha256', $params, $secret_key);

If the value of the generated hmac is the same as the one that was passed in as query parameter, you’re sure that the request came from Shopify. From there, make a request for the permanent access token from Shopify API and store it in the database:

如果生成的hmac的值与作为查询参数传递的hmac的值相同,那么您确定请求来自Shopify。 从那里,从Shopify API请求永久访问令牌并将其存储在数据库中:

$store = $query['shop']; if($hmac === $calculated_hmac){ $client = new Client(); $response = $client->request( 'POST', "https://{$store}/admin/oauth/access_token", [ 'form_params' => [ 'client_id' => $api_key, 'client_secret' => $secret_key, 'code' => $query['code'] ] ] ); $data = json_decode($response->getBody()->getContents(), true); $access_token = $data['access_token']; $nonce = $query['state']; if ($select = $db->prepare("SELECT id FROM installs WHERE store = ? AND nonce = ?")) { $select->bind_param('ss', $store, $nonce); $select->execute(); $select->bind_result($id); $select->fetch(); $select->close(); if ($id > 0) { $db->query("UPDATE installs SET access_token = '$access_token' WHERE id = '$id'"); } } }

向API发出请求 (Making Requests to the API)

Now that you have acquired an access token, you can make API requests on behalf of the user. The access token is like a key to the user’s shop. It gives you read and write access to any of the endpoints listed in the API reference page as long as it is part of the permissions that you asked for when the user installed the app.

现在,您已经获得了访问令牌,您可以代表用户发出API请求。 访问令牌就像是用户商店的钥匙。 只要它是用户安装应用程序时要求的权限的一部分,它就可以使您对API参考页中列出的任何端点进行读写访问。

Also note that endpoints with a “Shopify Plus” label are only available for use by Shopify Plus merchants. This means that it’s only accessible to the app if the user who installed it is a Shopify Plus merchant.

另请注意,带有“ Shopify Plus”标签的端点仅可供Shopify Plus商家使用 。 这意味着,只有安装了Shopify Plus商家的用户才能使用该应用。

To demonstrate how to make requests to the Shopify API, you’re going to create a page that shows the list of products that you’ve added to the store. Start by creating a products.php file and add the following code:

为了演示如何向Shopify API发出请求,您将创建一个页面,该页面显示已添加到商店的产品列表。 首先创建一个products.php文件,并添加以下代码:

<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; $dotenv = new Dotenv\Dotenv(__DIR__); $dotenv->load(); $db = new Mysqli(getenv('MYSQL_HOST'), getenv('MYSQL_USER'), getenv('MYSQL_PASS'), getenv('MYSQL_DB')); $store = 'test-shop.myshopify.com'; $select = $db->query("SELECT access_token FROM installs WHERE store = '$store'"); $user = $select->fetch_object(); $access_token = $user->access_token; $client = new Client(); $response = $client->request( 'GET', "https://{$store}/admin/products.json", [ 'query' => [ 'fields' => 'id,images,title,variants', 'access_token' => $access_token ] ] ); $result = json_decode($response->getBody()->getContents(), true); $loader = new Twig_Loader_Filesystem('templates'); $twig = new Twig_Environment($loader, [ 'cache' => 'cache', 'debug' => true ]); $template = $twig->loadTemplate('products.html'); echo $template->render(['products' => $result['products']]);

Breaking down the code above, first get the access token from the database. To quickly demonstrate things, the name of the Shopify store is hard-coded. For Shopify apps that display data from a Shopify store, the domain name of the website used for displaying the data is usually used.

分解上面的代码,首先从数据库中获取访问令牌。 为了快速演示,Shopify商店的名称是硬编码的。 对于显示Shopify商店中数据的Shopify应用程序,通常使用用于显示数据的网站的域名。

$store = 'test-shop.myshopify.com'; $select = $db->query("SELECT access_token FROM installs WHERE store = '$store'"); $user = $select->fetch_object(); $access_token = $user->access_token;

Next, make a request to the products endpoint. Note that the base URL is the store name: https://test-shop.myshopify.com. This means that the base URL is different for every store, which is why it’s important to save the store name in the database so you can refer to it later on. When making requests to the API, you always need to supply the access_token. For GET requests, you can supply it as a query parameter. For POST requests, add it as a form_params.

接下来,向产品端点发出请求。 请注意,基本URL是商店名称: https://test-shop.myshopify.com : https://test-shop.myshopify.com 。 这意味着每个商店的基本URL都不相同,这就是为什么将商店名称保存在数据库中很重要,以便以后可以引用它的原因。 向API发出请求时,您始终需要提供access_token 。 对于GET请求,您可以将其作为query参数提供。 对于POST请求,将其添加为form_params 。

The products endpoint doesn’t require anything to be supplied as a query parameter, though below, the fields parameter is supplied to specify the fields that you want to return. If you don’t specify the fields parameter, it will return all the product fields (e.g. title, images, description). You can also filter and limit the results by supplying any of these parameters.

产品端点不需要提供任何内容作为查询参数,尽管下面提供了fields参数来指定要返回的字段。 如果不指定fields参数,它将返回所有产品字段(例如标题,图像,描述)。 您还可以通过提供以下任何参数来过滤和限制结果。

$client = new Client(); $response = $client->request( 'GET', "https://{$store}/admin/products.json", [ 'query' => [ 'fields' => 'id,images,title,variants', 'access_token' => $access_token ] ] ); $result = json_decode($response->getBody()->getContents(), true);

This gives the following result when printed out:

打印出以下结果:

Array ( [products] => Array ( [0] => Array ( [id] => 6664000769 [title] => Arduino Uno [images] => Array ( [0] => Array ( [id] => 12780821761 [product_id] => 6664000769 [position] => 1 [created_at] => 2016-06-21T07:31:02-04:00 [updated_at] => 2016-06-21T07:31:02-04:00 [src] => https://cdn.shopify.com/s/files/1/1354/0873/products/uno.jpg?v=1466508662 [variant_ids] => Array ( ) ) ) ) [1] => Array ( [id] => 6663985537 [title] => Raspberry Pi 3 Model B Motherboard [images] => Array ( [0] => Array ( [id] => 12780794177 [product_id] => 6663985537 [position] => 1 [created_at] => 2016-06-21T07:29:10-04:00 [updated_at] => 2016-06-21T07:29:10-04:00 [src] => https://cdn.shopify.com/s/files/1/1354/0873/products/berry.jpg?v=1466508550 [variant_ids] => Array ( ) ) ) ) ) )

But you won’t really be printing the result out – you’re passing the result data to the template and rendering the page instead:

但是,您实际上并不会真正打印出结果,而是将结果数据传递到模板并呈现页面:

$loader = new Twig_Loader_Filesystem('templates'); $twig = new Twig_Environment($loader, [ 'cache' => 'cache', 'debug' => true ]); $template = $twig->loadTemplate('products.html'); echo $template->render(['products' => $result['products']]);

Here are the contents of the template (templates/products.html):

以下是模板的内容( templates/products.html ):

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Products</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/picnic/6.1.1/picnic.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/picnic/6.1.1/plugins.min.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <nav> <a href="#" class="brand"> <span>Shopify App</span> </a> </nav> <main> <h1>Products</h1> <div class="flex two"> {% for prod in products %} <div> <article class="card"> <img src="{{ prod.images[0].src }}"> <section> <h3>{{ prod.title }}</h3> <strong>{{ prod.variants[0].price }} PHP</strong> </section> </article> </div> {% endfor %} </div> </main> </body> </html>

结论 (Conclusion)

That’s it! In this tutorial, you’ve learned the basics of developing a Shopify app. As you have seen, developing a Shopify app is very similar to developing a standard PHP app. The only difference is that you make use of the Shopify API in order to manipulate data from a Shopify store, rather than directly from the database.

而已! 在本教程中,您学习了开发Shopify应用程序的基础知识。 如您所见,开发Shopify应用程序与开发标准PHP应用程序非常相似。 唯一的区别是,您使用Shopify API来处理来自Shopify商店而不是直接来自数据库的数据。

In a future post, we’ll make things more interesting by building a more complex app, and by utilizing a framework for some proper code structure.

在以后的文章中,我们将通过构建更复杂的应用程序并利用框架来构建一些适当的代码结构,使事情变得更加有趣。

Do you use Shopify? How has it been working out for you?

您是否使用Shopify? 您的工作情况如何?

翻译自: https://www.sitepoint.com/shopify-app-development-made-simple/

guzzle 封装api

相关资源:Guzzle一个可扩展的HTTP客户端
最新回复(0)