Skip to content

Commit

Permalink
Search products and update them
Browse files Browse the repository at this point in the history
  • Loading branch information
McCaulay Hudson committed Mar 23, 2020
1 parent 0972961 commit c254662
Show file tree
Hide file tree
Showing 9 changed files with 298 additions and 31 deletions.
26 changes: 25 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ TRUSTPILOT_ACCESS_TOKEN=
- Consumer API
- Consumer Profile API
- Invitation API
- Private Products API
- Product Reviews API -> Conversations, Invitation Link
- Resources API
- Service Reviews API
Expand Down Expand Up @@ -142,6 +141,31 @@ $profile = Trustpilot::businessUnit()->profile();
$promotion = Trustpilot::businessUnit()->promotion();
```

### Products
```php
// Get all products
$products = Trustpilot::products()->get();

// Get the product with a sku of "samsung-galaxy-s10"
$product = Trustpilot::products()
->where('skus', 'samsung-galaxy-s10')
->first();

// Get all products with a sku of "samsung-galaxy-s8", "samsung-galaxy-s9" or "samsung-galaxy-s10"
$products = Trustpilot::products()
->where('skus', ['samsung-galaxy-s8', 'samsung-galaxy-s9', 'samsung-galaxy-s10'])
->get();

// Updating a product
$product = Trustpilot::products()
->where('skus', 'samsung-galaxy-s10')
->first();
$product->title = 'Samsung Galaxy S10';
$product->price = '9.99';
$product->currency = 'USD';
$product->save();
```

### Categories
```php
// Get all categories
Expand Down
31 changes: 29 additions & 2 deletions config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,25 @@
| Trustpilot API Access Token
|--------------------------------------------------------------------------
|
| The API access token for your trustpilot account.
| The API access key and secret for your trustpilot account.
|
*/
'api' => [
'access_token' => env('TRUSTPILOT_ACCESS_TOKEN'),
'key' => env('TRUSTPILOT_API_KEY'),
'secret' => env('TRUSTPILOT_API_SECRET'),
],

/*
|--------------------------------------------------------------------------
| Trustpilot Credentials
|--------------------------------------------------------------------------
|
| The login credentials for your trustpilot account.
|
*/
'credentials' => [
'username' => env('TRUSTPILOT_USERNAME'),
'password' => env('TRUSTPILOT_PASSWORD'),
],

/*
Expand All @@ -35,6 +49,19 @@
'endpoints' => [
'default' => env('TRUSTPILOT_DEFAULT_ENDPOINT', 'https://api.trustpilot.com/v1'),
'invitation' => env('TRUSTPILOT_INVITATION_ENDPOINT', 'https://invitations-api.trustpilot.com/v1'),
'oauth' => env('TRUSTPILOT_OAUTH_ENDPOINT', 'https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications'),
],

/*
|--------------------------------------------------------------------------
| Package cache settings
|--------------------------------------------------------------------------
|
| The cache prefix to be used for cache items in this package.
|
*/
'cache' => [
'prefix' => env('TRUSTPILOT_CACHE_PREFIX', 'trustpilot'),
],

];
124 changes: 109 additions & 15 deletions src/API/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace McCaulay\Trustpilot;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class Api
{
Expand Down Expand Up @@ -33,6 +34,20 @@ class Api
*/
private $path;

/**
* The access token cache key.
*
* @var string
*/
private $accessTokenKey;

/**
* The refresh token cache key.
*
* @var string
*/
private $refreshTokenKey;

/**
* Initialise the Api
*/
Expand All @@ -43,12 +58,14 @@ public function __construct()

$this->path = '/';
$this->endpoint = $this->config['endpoints']['default'];
$this->accessTokenKey = $this->config['cache']['prefix'] . '.access_token';
$this->refreshTokenKey = $this->config['cache']['prefix'] . '.refresh_token';

// Initalise the guzzle client
$this->client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'apikey' => $this->config['api']['access_token'],
'apikey' => $this->config['api']['key'],
],
]);
}
Expand Down Expand Up @@ -76,18 +93,91 @@ protected function setPath(string $path): self
return $this;
}

/**
* Get the OAuth access token.
*
* @return string|null
*/
protected function getAccessToken()
{
// Get from cache
if (Cache::has($this->accessTokenKey)) {
$accessToken = Cache::get($this->accessTokenKey);
if ($accessToken != null) {
return $accessToken;
}
}

// Refresh if refresh token exists
if (Cache::has($this->refreshTokenKey)) {
$accessToken = $this->requestAccessToken('/refresh', 'refresh_token', [
'refresh_token' => Cache::get($this->refreshTokenKey),
]);
if ($accessToken != null) {
return $accessToken;
}
}

// Otherwise request a new token
return $this->requestAccessToken('/accesstoken', 'password', [
'username' => $this->config['credentials']['username'],
'password' => $this->config['credentials']['password'],
]);
}

/**
* Get the OAuth access token from the server.
*
* @param string $method
* @param string $grantType
* @param array $params
* @return string|null
*/
private function requestAccessToken($method, $grantType, $params)
{
$params['grant_type'] = $grantType;

$response = $this->client->request('GET', $this->config['endpoints']['oauth'] . $method, [
'headers' => [
'Authorization' => 'Basic ' . base64_encode($this->config['api']['key'] . ':' . $this->config['api']['secret']),
],
'form_params' => $params,
]);

if ($response->getStatusCode() != 200) {
return null;
}

$result = json_decode((string) $response->getBody());

// Cache the access token and refresh token
Cache::put($this->accessTokenKey, $result->access_token, $result->expires_in / 1000);
Cache::put($this->refreshTokenKey, $result->refresh_token, $result->refresh_token_expires_in / 1000);

return $result->access_token;
}

/**
* Perform a request to the API service.
*
* @param string $method
* @param array $params
* @return array|object
* @return object
*/
protected function request(string $method, string $path, array $query = [], array $params = [])
protected function request(string $method, string $path, array $query = [], array $params = [], bool $auth = false)
{
$headers = [];

// If auth is required, append access token
if ($auth) {
$headers['Authorization'] = 'Bearer ' . $this->getAccessToken();
}

// Perform request
$response = $this->client->request($method, $this->endpoint . $this->path . $path, [
'query' => $query,
'json' => $params,
'headers' => $headers,
]);
$contents = (string) $response->getBody();
return json_decode($contents);
Expand All @@ -98,11 +188,12 @@ protected function request(string $method, string $path, array $query = [], arra
*
* @param string $path
* @param array $query
* @return array|object
* @param bool $auth
* @return object
*/
protected function get(string $path, array $query = [])
protected function get(string $path, array $query = [], bool $auth = false)
{
return $this->request('GET', $path, $query);
return $this->request('GET', $path, $query, [], $auth);
}

/**
Expand All @@ -111,11 +202,12 @@ protected function get(string $path, array $query = [])
* @param string $path
* @param array $query
* @param array $params
* @return array|object
* @param bool $auth
* @return object
*/
protected function post(string $path, array $query = [], array $params = [])
protected function post(string $path, array $query = [], array $params = [], bool $auth = false)
{
return $this->request('POST', $path, $query, $params);
return $this->request('POST', $path, $query, $params, $auth);
}

/**
Expand All @@ -124,11 +216,12 @@ protected function post(string $path, array $query = [], array $params = [])
* @param string $path
* @param array $query
* @param array $params
* @return array|object
* @param bool $auth
* @return object
*/
protected function put(string $path, array $query = [], array $params = [])
protected function put(string $path, array $query = [], array $params = [], bool $auth = false)
{
return $this->request('PUT', $path, $query, $params);
return $this->request('PUT', $path, $query, $params, $auth);
}

/**
Expand All @@ -137,10 +230,11 @@ protected function put(string $path, array $query = [], array $params = [])
* @param string $path
* @param array $query
* @param array $params
* @return array|object
* @param bool $auth
* @return object
*/
protected function delete(string $path, array $query = [], array $params = [])
protected function delete(string $path, array $query = [], array $params = [], bool $auth = false)
{
return $this->request('DELETE', $path, $query, $params);
return $this->request('DELETE', $path, $query, $params, $auth);
}
}
8 changes: 4 additions & 4 deletions src/API/BusinessUnit/BusinessUnit.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php
namespace McCaulay\Trustpilot\API\BusinessUnit;

use McCaulay\Trustpilot\API\BusinessUnit\ProductApi;
use McCaulay\Trustpilot\API\BusinessUnit\Product\ProductApi;
use McCaulay\Trustpilot\API\Resource;
use McCaulay\Trustpilot\Query\Builder;

Expand Down Expand Up @@ -36,13 +36,13 @@ public function reviews(): Builder
}

/**
* Get the products api.
* Get the product api.
*
* @return \McCaulay\Trustpilot\API\BusinessUnit\ProductApi
* @return \McCaulay\Trustpilot\API\BusinessUnit\Product\ProductApi
*/
public function products(): ProductApi
{
return new ProductApi($this->id);
return new Product\ProductApi($this->id);
}

/**
Expand Down
40 changes: 40 additions & 0 deletions src/API/BusinessUnit/Product/Product.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
namespace McCaulay\Trustpilot\API\BusinessUnit\Product;

use McCaulay\Trustpilot\API\BusinessUnit\Product\ProductApi;
use McCaulay\Trustpilot\API\Resource;

class Product extends Resource
{
/**
* Save the product.
*
* @return mixed
*/
public function save()
{
return (new ProductApi())->save([$this->toSaveArray()])[0];
}

/**
* Get the parameters to save.
*
* @return array
*/
private function toSaveArray()
{
return [
'sku' => $this->sku,
'title' => $this->title,
'description' => $this->description,
'mpn' => $this->mpn,
'price' => $this->price,
'currency' => $this->currency,
'link' => $this->link,
'imageLink' => $this->imageLink,
'gtin' => $this->gtin,
'brand' => $this->brand,
'googleMerchantCenterProductId' => $this->googleMerchantCenterProductId,
];
}
}
Loading

0 comments on commit c254662

Please sign in to comment.