Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
* use from
* https://gitlab.com/interlopertx/ump/-/commit/9fa3cf5f29566b29df1d2aa7df3baf3e8fd372c4
* https://francescopantisano.it/ebay-oauth-2-generate-token-refresh-php/
*
* Why we have access token and refresh token?
* We use Access Token for all the api request on eBay service.
* We use Refresh Token to regenerate an Access Token.
*
* Access token is valid 2 hour, but Refresh Token is valid 18 months.
*/
namespace App\Ebay;
use App\Model\GlobalDefault;
use Exception;
use stdClass;
class OAuthToken
{
private string $access_token = '';
private string $refresh_token = '';
private int $expires_in = 7200;
private int $refresh_token_expires_in = 47304000;
private string $token_type = '';
private string $updated_at = '';
private string $created_at = '';
private string $local_token_file = '';
private string $client_id = '';
private string $dev_id = '';
private string $client_secret = '';
private string $ru_name = '';
private string $code = '';
private const DATETIME_FORMAT = 'Y-m-d H:i:s';
private array $scope = [
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/buy.order.readonly',
'https://api.ebay.com/oauth/api_scope/buy.guest.order',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketplace.insights.readonly',
'https://api.ebay.com/oauth/api_scope/commerce.catalog.readonly',
'https://api.ebay.com/oauth/api_scope/buy.shopping.cart',
'https://api.ebay.com/oauth/api_scope/buy.offer.auction',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
'https://api.ebay.com/oauth/api_scope/commerce.identity.email.readonly',
'https://api.ebay.com/oauth/api_scope/commerce.identity.phone.readonly',
'https://api.ebay.com/oauth/api_scope/commerce.identity.address.readonly',
'https://api.ebay.com/oauth/api_scope/commerce.identity.name.readonly',
'https://api.ebay.com/oauth/api_scope/commerce.identity.status.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.item.draft',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/sell.item',
'https://api.ebay.com/oauth/api_scope/sell.reputation',
'https://api.ebay.com/oauth/api_scope/sell.reputation.readonly',
'https://api.ebay.com/oauth/api_scope/commerce.notification.subscription',
'https://api.ebay.com/oauth/api_scope/commerce.notification.subscription.readonly'
];
/**
*
* @throws Exception
*/
public function __construct()
{
date_default_timezone_set('Asia/Karachi');
$dir = base_path() . '/' . __NAMESPACE__ . '/';
$this->local_token_file = $dir . 'token.json';
if (!is_writable(dirname($dir)))
throw new Exception("Not Write Permission $dir");
$this->client_id = env('EBAY_CLIENT_ID');
$this->dev_id = env('EBAY_DEV_ID');
$this->client_secret = env('EBAY_CLIENT_SECRET');
$this->ru_name = env('EBAY_RU_NAME');
/*
* if ./token.json not exist
*/
if (!file_exists($this->local_token_file)) {
$token_info = $this->access_token_generate(false);
$token_info->created_at = date(self::DATETIME_FORMAT);
$this->access_token_fwrite($token_info);
}
// if file exist store token details in class instance members
$this->access_token_fread();
}
public static function bearer(): array
{
return [
'Authorization: Bearer ' . (new self())->get_access_token(),
'Content-Type: application/json',
'Accept: application/json',
];
}
private function authorization(): string
{
return base64_encode($this->client_id . ':' . $this->client_secret);
}
public function get_scope_list(): string
{
return implode(' ', $this->scope);
}
private function auth_basic(): array
{
return [
'Authorization: Basic ' . $this->authorization(),
'Content-Type: application/x-www-form-urlencoded',
];
}
public static function get_token(): string
{
return (new self())->get_access_token();
}
private function access_token_fwrite(stdClass $response): void
{
if (file_exists($this->local_token_file))
$this->access_token_fread();
$response->refresh_token = $response->refresh_token ?? $this->refresh_token;
$response->refresh_token_expires_in = $response->refresh_token_expires_in ?? $this->refresh_token_expires_in;
$response->updated_at = date(self::DATETIME_FORMAT);
$response->created_at = $response->created_at ?? $this->created_at;
$token_fp = fopen($this->local_token_file, 'w');
fwrite($token_fp, json_encode($response));
fclose($token_fp);
$this->access_token_store_db($response);
$this->access_token_fread();
}
private function access_token_fread(): void
{
$token = json_decode(
file_get_contents($this->local_token_file)
);
$this->access_token = $token->access_token;
$this->expires_in = $token->expires_in;
$this->refresh_token = $token->refresh_token;
$this->refresh_token_expires_in = $token->refresh_token_expires_in;
$this->token_type = $token->token_type;
$this->updated_at = $token->updated_at;
$this->created_at = $token->created_at;
}
private function access_token_store_db($token)
{
$global_default = GlobalDefault::select('defaults')->where('platform_id', 1)->where('user_id', 1)->first();
$id = $global_default->id;
$global_default_column = unserialize($global_default->defaults);
$global_default_column['authToken'] = $token->access_token;
$global_default_column['expires_in'] = date(self::DATETIME_FORMAT);
$global_default_column = serialize($global_default_column);
GlobalDefault::where('platform_id', 1)->where('user_id', 1)->update(['defaults' => $global_default_column]);
}
protected function get_access_token(): string
{
if ($this->refresh_token_expired()) {
unlink($this->local_token_file);
$this->__construct();
}
if ($this->access_token_expired()) {
//echo 'Request for Refreshing...' . PHP_EOL;
$response = $this->access_token_generate(true);
$this->access_token_fwrite($response);
//echo 'Token is Refreshed' . PHP_EOL;
}
return $this->access_token;
}
private function access_token_generate(bool $refresh): stdClass
{
$url = Ebay::API_BASE_URL . '/identity/v1/oauth2/token';
if ($refresh === false)
$this->fetch_code();
$body = ($refresh) ? [
'grant_type' => 'refresh_token',
'refresh_token' => $this->refresh_token,
'scope' => $this->get_scope_list(),
] : [
'grant_type' => 'authorization_code',
'code' => $this->code,
'redirect_uri' => $this->ru_name,
];
return Ebay::http()->post($url, $body, $this->auth_basic());
}
private function fetch_code(): void
{
// GET https://auth.sandbox.ebay.com/oauth2/authorize
//$url = 'https://auth.sandbox.ebay.com/oauth2/authorize';
echo 'Enter code: ';
flush();
$this->code = urldecode(trim(fgets(STDIN)));
// $perms = [
// 'client_id' => $this->client_id,
// 'redirect_uri' => $this->ru_name,
// 'response_type' => 'code',
// 'scope' => $this->get_scope_list(),
// //'state' => '',
// 'prompt' => 'login',
// ];
// $url = Ebay::http()->get_redirect($url, $perms, []);
// $post = Ebay::http()->post($url, ['pass' => 'SndB2b*@Work21On'], []);
// dd($post);
}
public function access_token_expired(): bool
{
$token_time = strtotime($this->updated_at);
$time_current = strtotime(date(self::DATETIME_FORMAT));
/*
* return TRUE if expired
* don't change
*/
return ($this->expires_in < ($time_current - $token_time));
}
public function refresh_token_expired(): bool
{
$time_token = strtotime($this->created_at);
$time_current = strtotime(date(self::DATETIME_FORMAT));
/*
* return TRUE if expired
* don't change
*/
return ($this->refresh_token_expires_in < ($time_current - $time_token));
}
}
@mudassaralichouhan
Copy link
Author

mudassaralichouhan commented Apr 22, 2022

Ebay User Token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment