rhysnhall/etsy-php-sdk
Composer 安装命令:
composer require rhysnhall/etsy-php-sdk
包简介
PHP SDK for Etsy API v3.
README 文档
README
A PHP SDK for the Etsy API v3.
Proper documentation still to come. Want to write it for me? I'll buy you an iced latte.
Requirements
PHP 8 or greater.
Install
Install the package using composer.
composer require rhysnhall/etsy-php-sdk
Include the Etsy class.
use Etsy\Etsy; $etsy = new Etsy( $client_id, $shared_secret, $access_token ); // Do the Etsy things.
Usage
Authorizing your app
The Etsy API uses OAuth 2.0 authentication. You can read more about authenticating with Etsy on their documentation.
The first step in OAuth2 is to request an OAuth token. You will need an existing App API key and shared secret which you can obtain by registering an app here.
$client = new Etsy\OAuth\Client( $client_id, $shared_secret );
Generate a URL to redirect the user to authorize access to your app.
$url = $client->getAuthorizationUrl( $redirect_uri, $scopes, $code_challenge, $nonce );
Redirect URI
You must set an authorized callback URL. Check out the Etsy documentation for further information.
Scope
Depending on your apps requirements, you will need to specify the permission scopes you want to authorize access for.
$scopes = ["listings_d", "listings_r", "listings_w", "profile_r"];
You can get all scopes, but it is generally recommended to only get what you need.
$scopes = \Etsy\Utils\PermissionScopes::ALL_SCOPES;
Code challenge
You'll need to generate a PKCE code challenge and save this along with the verifier used to generate the challenge. You are welcome to generate your own, or let the SDK do this for you.
[$verifier, $code_challenge] = $client->generateChallengeCode();
Nonce
The nonce is a single use token used for CSRF protection. You can use any token you like but it is recommended to let the SDK generate one for you each time you authorize a user. Save this for verifying the response later on.
$nonce = $client->createNonce();
The URL will redirect your user to the Etsy authorization page. If the user grants access, Etsy will send back a request with an authorization code and the nonce (state).
https://www.example.com/some/location?
code=bftcubu-wownsvftz5kowdmxnqtsuoikwqkha7_4na3igu1uy-ztu1bsken68xnw4spzum8larqbry6zsxnea4or9etuicpra5zi
&state=superstate
It is up to you to validate the nonce. If they do not match you should discard the response.
For more information on Etsy's response, check out the documentation here.
The final step is to get the access token for the user. To do this you will need to make a request using the code that was just returned by Etsy. You will also need to pass in the same callback URL as the first request and the verifier used to generate the PKCE code challenge.
[$access_token, $refresh_token] = $client->requestAccessToken( $redirect_uri, $code, $verifier );
You'll be provided with both an access token and a refresh token. The access token has a valid duration of 3600 seconds (1 hour). Save both of these for late use.
Refreshing your token
You can refresh your authorization token (even after it has expired) using the refresh token that was previously provided. This will provide you with a new valid access token and another refresh token.
[$access_token, $refresh_token] = $client->refreshAccessToken($refresh_token);
The Etsy documentation states that refreshed access tokens have a duration of 86400 seconds (24 hours) but on testing they appear to only remain valid for up 3600 seconds (1 hour).
Exchanging legacy OAuth 1.0 token for OAuth 2.0 token
If you previously used v2 of the Etsy API and still have valid authorization tokens for your users, you may swap these over for valid OAuth2 tokens.
[$access_token, $refresh_token] = $client->exchangeLegacyToken($legacy_token);
This will provide you with a brand new set of OAuth2 access and refresh tokens.
Basic use
Create a new instance of the Etsy class using your App API key, app shared secret and a user's access token. You must always initialize the Etsy resource before calling any resources.
use Etsy\Etsy; use Etsy\Resources\User; $etsy = new Etsy($apiKey, $sharedSecret, $accessToken); // Get the authenticated user. $user = User::me(); // Get the users shop. $shop = $user->shop();
Resources
Most calls will return a Resource. Resources contain a number of methods that streamline your interaction with the Etsy API.
// Get a Listing Resource $listing = \Etsy\Resources\Listing::get($shopId);
Resources contain the API response from Etsy as properties.
$listingTitle = $listing->title;
Associations
Resources will return associations as their respective Resource when appropriate. For example the bellow call will return the shop property as an instance of Etsy\Resources\Shop.
$shop = $listing->shop;
toJson
The toJson method will return the Resource as a JSON encoded object.
$json = $listing->toJson();
toArray
The toArray method will return the Resource as an array.
$array = $listing->toArray();
Collections
When there is more than one result a collection will be returned.
$reviews = Review::all();
Results are stored as an array of Resource on the data property of the collection.
$firstReview = $reviews->data[0];
Collections contain a handful of useful methods.
first
Get the first item in the collection.
$firstReview = $reviews->first();
count
Get the number of results in the collection. Not be confused with the count property which displays the number of results in a full Etsy resource.
$count = $reviews->count();
append
Append a property to each item in the collection.
$reviews->append(['shop_id' => $shopId]);
paginate
Most Etsy methods are capped at 100 results per call. You can use the paginate method to get more results than this (up to 500 results).
// Get 100 results using pagination. foreach($reviews->paginate(200) as $review) { ... }
toJson
Returns the items in the collection as an array of JSON strings.
$jsonArray = $reviews->toJson();
Direct Requests
You can make direct requests to the Etsy API using the static $client property of the Etsy class.
$response = Etsy::$client->get( "/application/listings/active", [ "limit" => 25 ] );
If you still want to use the Resources classes you can convert the response into a Resource. Pass the response from the client as the first parameter and the name of the resource as the second. If the response is an array then a Collection will be returned.
$listings = Etsy::getResource( Etsy::$client->get("/application/listings/active"), 'Listing' );
File Uploads
Etsy listings support uploads for files, images and videos depending on the Listing type. The SDK includes basic support for uploading files.
Images
To upload an image you need to pass the image data under the image parameter on your request as if it was prepared for multipart form-data.
$data = [ 'image' => [ 'content' => fopen('./path-to-image.jpg') ] ]; $image = ListingImage::create( $shopId, $listingId, $data );
For convenience you can just include a path or an external URL and the SDK will handle basic reading of the file.
$data = [ 'image' => './path-to-image.jpg' ];
Other files
Video and file uploads work the same way but these also require a name parameter on the upload request. This name just represents the name of the file to upload.
ListingVideo::create( $shopId, $listingId, [ 'video' => './path-to-video.mp4', 'name' => $fileName ] ); ListingFile::create( $shopId, $listingId, [ 'file' => './downloadable-template.pdf', 'name' => $fileName ] );
Instance Methods
Most of the SDK is built around calling static methods on the different Etsy resources. For convenience some resources contain instance methods. These are designed to streamline interaction with the SDK.
Save method
Many resources contain a save() method which is a convenient shortcut for a patch request. In most cases the current data will be compared against the values of the _originalState property on the Resource and if no data has been changed the patch request will be skipped.
$listing = \Etsy\Resources\Listing::get($listingId); # Update listing title. $listing->title = 'Updated title'; $listing->save();
Other methods
Review each Resource to better understand the methods available. There are some examples below of methods available to the Listing resource.
$listing->images(); // Get all images for the listing. $listing->uploadImage($imageData); // Upload a new image. $listing->inventory(); // Get the listing inventory. $listing->translation('en'); // Get the English translation for the listing.
Full documentation will be available soon (or so I keep saying). Email hello@rhyshall.com for any assistance.
Contributing
Help improve this SDK by contributing.
Before opening a pull request, please first discuss the proposed changes via Github issue or email.
License
This project is licensed under the MIT License - see the LICENSE file for details
rhysnhall/etsy-php-sdk 适用场景与选型建议
rhysnhall/etsy-php-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 120.18k 次下载、GitHub Stars 达 52, 最近一次更新时间为 2020 年 03 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「api」 「sdk」 「etsy」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 rhysnhall/etsy-php-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 rhysnhall/etsy-php-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 rhysnhall/etsy-php-sdk 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A PSR-7 compatible library for making CRUD API endpoints
Alfabank REST API integration
Zero-dependency raw PHP DNS resolver, domain-ownership verification, and intoDNS/MxToolbox-style diagnostics. Queries authoritative nameservers directly over sockets — never trusts the recursive cache for ownership checks.
A lightweight plain-PHP framework for database-backed CRUD APIs.
bughq error tracking - PHP SDK
ABsurge PHP SDK for feature flags and A/B testing
统计信息
- 总下载量: 120.18k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 52
- 点击次数: 17
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-03-29