我发现@FullStackFool上面的帖子非常有用。基于此,我建立了一个类,从本地数据库获取当前令牌,如果需要刷新令牌,则刷新令牌,显示获取新刷新令牌的说明,或处理代码以生成新的刷新令牌。
该类是用PHP 5.6编写的(抱歉 - 老的内部订单管理系统),但可以轻松升级到PHP 7 / Laravel等版本。
构造函数只接受一个可选值 - 这是由ebay生成的URL字符串,用于验证/登录以获取新令牌。如果将其提供给构造函数,它将解析它,获取“code”部分,然后获取新的令牌和刷新令牌。
希望代码是自说明的 - 我已经尝试很好地对其进行了注释。希望其他人也会发现这个有用。
数据库表(EbayTokens):
CREATE TABLE IF NOT EXISTS `EbayTokens` (
`TokenID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`TokenValue` text,
`TokenCreated` datetime DEFAULT NULL,
`TokenLifetime` int(11) unsigned DEFAULT NULL,
`RefreshTokenValue` text,
`RefreshTokenCreated` datetime DEFAULT NULL,
`RefreshTokenLifetime` int(11) unsigned DEFAULT NULL,
`TokenType` varchar(100) DEFAULT NULL,
PRIMARY KEY (`TokenID`),
UNIQUE KEY `TokenID` (`TokenID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
PHP类(ebaytoken.php):
<?php
class EbayToken {
public $success = false;
public $messages = [];
public $db_token = null;
private $string;
private $access_token_expired = true;
private $refresh_token_expired = true;
private $refresh_token_almost_expired = true;
private $client_id = 'your_client_id';
private $secret = 'your_secret';
private $ru_name_value = 'your_ru';
private $scope = 'https://api.ebay.com/oauth/api_scope/sell.fulfillment';
private $base64_encoded_credentials = null;
function __construct($string = null) {
$this->string = $string;
$this->base64_encoded_credentials = base64_encode($this->client_id . ':' . $this->secret);
$this->get_token_from_db();
$this->check_db_token();
if(($this->access_token_expired == true) && ($this->refresh_token_expired == true)) {
if((isset($this->string)) && ($this->string != '')) {
$this->get_new_tokens($this->string);
} else {
$this->get_new_tokens_instructions();
}
} else if($this->access_token_expired == true) {
if($this->refresh_token_almost_expired == true) {
$this->need_new_tokens_almost_instructions();
}
$this->refresh_token();
} else {
if($this->refresh_token_almost_expired == true) {
$this->need_new_tokens_almost_instructions();
}
}
}
private function get_token_from_db() {
$sql = "SELECT * FROM EbayTokens";
$res = @mysql_query($sql);
$count = 0;
if($res) {
$count = mysql_num_rows($res);
while ($rec = mysql_fetch_assoc($res)) {
$this->db_token = $rec;
}
$this->messages[] = '<span style="color:limegreen;"><strong>Access token loaded from database...</strong></span>';
} else {
$this->messages[] = '<span style="color:red;"><strong>No token found in database!</strong></span>';
}
return null;
}
private function check_db_token() {
if($this->db_token != null) {
$now = new DateTime();
$now_plus_30_days = new DateTime();
$now_plus_30_days->add(DateInterval::createFromDateString('30 days'));
$date_created = DateTime::createFromFormat('Y-m-d H:i:s', $this->db_token['TokenCreated']);
$date_expires = DateTime::createFromFormat('Y-m-d H:i:s', $this->db_token['TokenCreated']);
$date_expires->add(DateInterval::createFromDateString($this->db_token['TokenLifetime'] . ' seconds'));
$refresh_date_created = DateTime::createFromFormat('Y-m-d H:i:s', $this->db_token['RefreshTokenCreated']);
$refresh_date_expires = DateTime::createFromFormat('Y-m-d H:i:s', $this->db_token['RefreshTokenCreated']);
$refresh_date_expires->add(DateInterval::createFromDateString($this->db_token['RefreshTokenLifetime'] . ' seconds'));
$this->messages[] = 'Access token created on: ' . $date_created->format('d/m/Y H:i:s') . ', expires: ' . $date_expires->format('d/m/Y H:i:s');
if($date_expires < $now) {
$this->messages[] = ' <span style="color:red;"><strong>Access token expired!</strong></span>';
} else {
$this->messages[] = ' <span style="color:limegreen;"><strong>Access token valid!</strong></span>';
$this->access_token_expired = false;
}
$this->messages[] = 'Refresh token created on: ' . $refresh_date_created->format('d/m/Y H:i:s') . ', expires: ' . $refresh_date_expires->format('d/m/Y H:i:s');
if($refresh_date_expires < $now) {
$this->messages[] = '<span style="color:red;"><strong>Refresh token expired!</strong></span>';
} else if($refresh_date_expires < $now_plus_30_days) {
$this->messages[] = ' <span style="color:darkorange;"><strong>Refresh token valid! But expires within 30 days. INFORM ADMIN TO GENERATE A NEW REFRESH TOKEN.</strong></span>';
$this->refresh_token_expired = false;
} else {
$this->messages[] = '<span style="color:limegreen;"><strong>Refresh token valid!</strong></span>';
$this->refresh_token_almost_expired = false;
$this->refresh_token_expired = false;
}
if(($this->refresh_token_expired == false) && ($this->access_token_expired == false)) {
$this->messages[] = '<span style="color:limegreen;"><strong>All tokens valid!</strong></span>';
$this->success = true;
}
}
return null;
}
private function refresh_token() {
$this->messages[] = 'OAUTH token expired - refreshing token...';
$url_get_token = 'https://api.ebay.com/identity/v1/oauth2/token';
$port = 443;
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . $this->base64_encoded_credentials
);
$payload = array(
'grant_type' => 'refresh_token',
'refresh_token' => $this->db_token['RefreshTokenValue'],
'scope=' . urlencode($this->scope),
);
$payload_string = http_build_query($payload);
$ch = curl_init();
curl_setopt($ch, CURLOPT_PORT, $port);
curl_setopt($ch, CURLOPT_URL, $url_get_token);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload_string);
$data = curl_exec($ch);
curl_close($ch);
$array_data = json_decode($data, true);
$access_token = null;
if((is_array($array_data)) && (isset($array_data['access_token']))) {
$access_token = mysql_real_escape_string($array_data['access_token']);
$expires_in = mysql_real_escape_string($array_data['expires_in']);
$token_type = mysql_real_escape_string($array_data['token_type']);
$now = new DateTime();
$now_mysql = $now->format('Y-m-d H:i:s');
$existing_token_id = $this->db_token['TokenID'];
$sql = sprintf("UPDATE EbayTokens SET TokenValue = '%s', TokenCreated = '%s', TokenLifetime = %s, TokenType = '%s' WHERE TokenID = %d", $access_token, $now_mysql, $expires_in, $token_type, $existing_token_id);
if (@executeSQL($sql)) {
$this->messages[] = '<span style="color:limegreen;"><strong>Success! Token refreshed and saved to database.</strong></span>';
}
$this->get_token_from_db();
$this->check_db_token();
} else {
$this->messages[] = '<span style="color:red;"><strong>Failed to get OAUTH token! Aborting</strong></span>.';
$this->messages[] = 'Reply was:' . '<br><pre>' . print_r($array_data) . '</pre>';
}
return null;
}
private function get_new_tokens($string) {
$auth_code = null;
$parameters = parse_url($string);
$query_array = explode('&', $parameters['query']);
foreach ($query_array as $parameter) {
$parameter_array = explode('=', $parameter);
if($parameter_array[0] == 'code') {
$auth_code = $parameter_array[1];
break;
}
}
$this->messages[] = "Getting eBay Oauth token using URL string...";
$this->messages[] = 'Using auth code: ' . $auth_code;
$url_get_token = 'https://api.ebay.com/identity/v1/oauth2/token';
$port = 443;
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . $this->base64_encoded_credentials
);
$payload = array(
'grant_type' => 'authorization_code',
'code' => urldecode($auth_code),
'redirect_uri' => $this->ru_name_value,
);
$payload_string = http_build_query($payload);
$ch = curl_init();
curl_setopt($ch, CURLOPT_PORT, $port);
curl_setopt($ch, CURLOPT_URL, $url_get_token);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload_string);
$data = curl_exec($ch);
curl_close($ch);
$array_data = json_decode($data, true);
$access_token = null;
if((is_array($array_data)) && (isset($array_data['access_token']))) {
$access_token = mysql_real_escape_string($array_data['access_token']);
$expires_in = mysql_real_escape_string($array_data['expires_in']);
$refresh_token = mysql_real_escape_string($array_data['refresh_token']);
$refresh_token_expires_in = mysql_real_escape_string($array_data['refresh_token_expires_in']);
$token_type = mysql_real_escape_string($array_data['token_type']);
$this->truncate_db();
$now = new DateTime();
$now_mysql = $now->format('Y-m-d H:i:s');
$sql = sprintf("INSERT INTO EbayTokens SET TokenValue = '%s', TokenCreated = '%s', TokenLifetime = %d, RefreshTokenValue = '%s', RefreshTokenCreated = '%s', RefreshTokenLifetime = %d, TokenType = '%s' ", $access_token, $now_mysql, $expires_in, $refresh_token, $now_mysql, $refresh_token_expires_in, $token_type);
if (@executeSQL($sql)) {
$this->messages[] = '<span style="color:limegreen;"><strong>Success! New token aquired and saved to database.</strong></span>';
} else {
$this->messages[] = '<span style="color:red;"><strong>Error saving new token to database!</strong></span>';
}
$this->get_token_from_db();
$this->check_db_token();
} else {
$this->messages[] = '<span style="color:red;"><strong>Failed to get OAUTH token! Aborting</strong></span>.';
$this->messages[] = 'Reply was:' . '<br><pre>' . print_r($array_data) . '</pre>';
}
return null;
}
private function get_new_tokens_instructions() {
$this->messages[] = '<span style="color:red;">Tokens expired! Admin action required</span>';
$this->messages[] = "In order to get a fresh oauth token (and more importantly a refresh token), click on the URL below (it will open in a new window) and login as.";
$url_get_consent = 'https://auth.ebay.com/oauth2/authorize';
$payload = array(
'client_id=' . $this->client_id,
'redirect_uri=' . $this->ru_name_value,
'response_type=code',
'scope=' . urlencode($this->scope),
);
$payload_string = implode('&', $payload);
$url_get_consent_full = $url_get_consent . '?' . $payload_string;
$this->messages[] = 'URL: <a href="' . $url_get_consent_full . '" target="_blank">' . $url_get_consent_full . '</a><br>';
$this->messages[] = "Once you have completed the login and see the window saying you can close the page, <strong>copy the URL</strong>. It will contain a 'code' parameter.";
$this->messages[] = "Insert the coppied URL in the form below and click submit. The new code will be used and a new oauth and refresh token will be obtained and stored in the database.";
$this->messages[] = '
<form>
URL string:
<input type="text" name="string" size="50">
<input type="submit" value="Submit">
</form>
';
return null;
}
private function need_new_tokens_almost_instructions() {
$this->messages[] = '<span style="color:darkorange;">Tokens ALMOST expired! Admin action required</span>';
$this->messages[] = "In order to get a fresh oauth token (and more importantly a refresh token), click on the URL below (it will open in a new window) and login.";
$url_get_consent = 'https://auth.ebay.com/oauth2/authorize';
$payload = array(
'client_id=' . $this->client_id,
'redirect_uri=' . $this->ru_name_value,
'response_type=code',
'scope=' . urlencode($this->scope),
);
$payload_string = implode('&', $payload);
$url_get_consent_full = $url_get_consent . '?' . $payload_string;
$this->messages[] = 'URL: <a href="' . $url_get_consent_full . '" target="_blank">' . $url_get_consent_full . '</a><br>';
$this->messages[] = "Once you have completed the login and see the window saying you can close the page, <strong>copy the URL</strong>. It will contain a 'code' parameter.";
$this->messages[] = "Insert the coppied URL in the form below and click submit. The new code will be used and a new oauth and refresh token will be obtained and stored in the database.";
$this->messages[] = '
<form>
URL string:
<input type="text" name="string" size="50">
<input type="submit" value="Submit">
</form>
';
return null;
}
private function truncate_db() {
$sql = "TRUNCATE TABLE EbayTokens";
if (@executeSQL($sql)) {
$this->messages[] = '<span style="color:limegreen;"><strong>Existing tokens deleted from database.</strong></span>';
}
return null;
}
}
?>
这是一个测试/使用的小脚本:
<?php
require_once("classes/ebaytoken.php");
$thispage = new Page();
$string = null;
if((isset($_GET['string'])) && ($_GET['string'] != '')) {
$string = $_GET['string'];
}
$token = new EbayToken($string);
echo "<h3>Current eBay Tokens</h3>";
$messages = $token->messages;
if(count($messages) > 0) {
echo '<ul>';
foreach ($messages as $message) {
echo '<ul>' . $message . '</ul>';
}
echo '</ul>';
}
if($token->success == true) {
get_orders($token->db_token);
}
function get_orders($token_data) {
echo "<h3>Getting Ebay Orders</h3>";
$url_get_orders = 'https://api.ebay.com/sell/fulfillment/v1/order';
$port = 443;
$headers = array(
'Authorization: Bearer ' . $token_data['TokenValue'],
'X-EBAY-C-MARKETPLACE-ID: EBAY_GB',
);
$payload = array(
'filter=orderfulfillmentstatus:' . urlencode('{NOT_STARTED|IN_PROGRESS}'),
'limit=100',
'offset=0',
);
$payload_string = implode('&', $payload);
$url_get_orders_full = $url_get_orders . '?' . $payload_string;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_get_orders_full);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
$array_data = json_decode($data, true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
return null;
}
?>