Skip to content

Instantly share code, notes, and snippets.

@jalallinux
Last active February 1, 2023 08:48
Show Gist options
  • Save jalallinux/1440292461f55a36eb62fd59e3258550 to your computer and use it in GitHub Desktop.
Save jalallinux/1440292461f55a36eb62fd59e3258550 to your computer and use it in GitHub Desktop.
Fetch Amazon product details
<?php
namespace JalalLinuX\AmazonApi;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class AmazonApi
{
private PendingRequest $client;
public function __construct()
{
$this->client = Http::baseUrl(self::API_BASE_URI)->asJson()->acceptJson();
}
private function fetchMltId(string $asin): string
{
return $this->client->get("product/v2/{$asin}")->throw()->json('mlt');
}
private function transform(Collection $product): Collection
{
return $product->except(self::TRANSFORM['except_keys'])->mapWithKeys(function ($v, $k) {
if (!is_null(@self::TRANSFORM['map_keys'][$k])) {
return [self::TRANSFORM['map_keys'][$k] => $v];
}
return [$k => $v];
});
}
public function product(string $asin): Collection
{
$mltId = $this->fetchMltId($asin);
$product = $this->client->get("product/v2/mlt-{$mltId}");
throw_if(!$product->successful(), new \Exception("Can't fetch product with ASIN: {$asin}, MLT: $mltId"));
Cache::put(self::CACHING_PREFIX . $asin, $product = $product->collect(), self::CACHING_TIME);
return $this->transform($product);
}
const TRANSFORM = [
'map_keys' => [
'amazonId' => 'id',
'englishTitle' => 'title',
'productImage' => 'image',
],
'except_keys' => [
'id', 'title', 'parentId', 'amazonParentId', 'canonicalId', 'delivery', 'categories',
'variations', 'price.rialPrice', 'price.irShipping', 'price.shippingTypes', 'otherMarkets',
]
];
const CACHING_TIME = 60;
const CACHING_PREFIX = 'AMAZON_PRODUCT_';
const API_BASE_URI = 'https://api.malltina.com';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment