如何生成eBay OAuth用户令牌?

时间:2019-06-30 20:20:24

标签: php ebay-api ebay-sdk

我一直在使用David Sadler的ebay-sdk-php生成对Ebay API的交易调用,但是首先我必须创建OAuthUserToken。

我使用了gettoken.php示例并创建了以下代码:

    $service = new \DTS\eBaySDK\OAuth\Services\OAuthService([
        'credentials'   => config('ebay.'.config('ebay.mode').'.credentials'),
        'ruName' => config('ebay.'.config('ebay.mode').'.ruName'),
        'sandbox'     => true
    ]);

    $token = session('????'); //here I have to retrieve the authorization callback information.
    /**
     * Create the request object.
     */
    $request = new \DTS\eBaySDK\OAuth\Types\GetUserTokenRestRequest();
    $request->code = $token;
    /**
     * Send the request.
     */
    $response = $service->getUserToken($request);

由于某种原因,我无法为UserOauth令牌生成重定向。我认为该代码:

$service = new\DTS\eBaySDK\OAuth\Services\OAuthService([

...自动生成到eBay Grant Area的重定向,但并非如此。

有人知道如何解决吗?我想知道如何授予用户访问权限,然后执行通话(例如getEbayTime)。

1 个答案:

答案 0 :(得分:2)

您可以使用redirectUrlForUser()函数来生成用于重定向的URL。

$url =  $service->redirectUrlForUser([
    'state' => '<state>',
    'scope' => [
        'https://api.ebay.com/oauth/api_scope/sell.account',
        'https://api.ebay.com/oauth/api_scope/sell.inventory'
    ]
]);

然后,致电header()来重定向用户。请注意,标题调用之前不能显示任何text / html。

header("Location: $url");

此后,当用户从ebay网站返回时,您的令牌应存储在$_GET["code"]中。

$token = $_GET["code"];

因此,您可以发送请求并使用示例来取回OAuth令牌。

$request = new \DTS\eBaySDK\OAuth\Types\GetUserTokenRestRequest();
$request->code = $token;

$response = $service->getUserToken($request);

// Output the result of calling the service operation.
printf("\nStatus Code: %s\n\n", $response->getStatusCode());
if ($response->getStatusCode() !== 200) {
    // Display information that an error has happened
    printf(
        "%s: %s\n\n",
        $response->error,
        $response->error_description
    );
} else {
    // Use the token to make calls to ebay services or store it.
    printf(
        "%s\n%s\n%s\n%s\n\n",
        $response->access_token,
        $response->token_type,
        $response->expires_in,
        $response->refresh_token
    );
}

您的OAuth令牌将位于$response->access_token变量中。令牌是短暂的,因此如果您想使用它,则需要不定期更新。为此,请使用$response->refresh_token并致电$service->refreshUserToken()

$response = $service->refreshUserToken(new Types\RefreshUserTokenRestRequest([
    'refresh_token' => '<REFRESH TOKEN>',
    'scope' => [
        'https://api.ebay.com/oauth/api_scope/sell.account',
        'https://api.ebay.com/oauth/api_scope/sell.inventory'
    ]
]));
// Handle it the same way as above, when you got the first OAuth token