eBay OAuth令牌和刷新令牌

27

我最近在为eBay令牌验证苦苦挣扎。 我发现很难理解如何获取新的令牌,在注册开发者计划账户后,我请求了密钥集并得到了它们,在此之后我授权访问Auth'n'Auth令牌,该令牌承诺持续18个月,并且该令牌仅适用于Trading、Shopping和Finding api。

但是当您需要执行Buy、Sell和Commerce api时,必须获得oauth令牌。您可以使用所谓的“Single User app”样式通过User Token Tool登录oauth,获得有效期为2小时的oauth。

令牌过期后,您会失去上述api的访问权限。我尝试从Trading>获取会话ID、Trading>获取令牌中获取令牌,但在向Fetch token提供会话ID后,它显示“最终用户未完成Auth&Auth登录流程。”虽然有一个有效期18个月的令牌,但它一直返回此错误。

是否有关于此的示例文章,任何人都可能已经阅读或编写?


你可以查看这个Node模块,它简化了所有关于生成访问令牌和使用所有eBay API的问题。https://github.com/ajay2507/ebay-node-api - Ajaykumar
我们正在烧毁“ebay”标签,这就是我从您的问题中删除标签的原因。您能否回滚您的回滚以做出贡献? - MilkyWay90
1
给所有偶然发现这篇文章的软件工程师们:https://www.nango.dev/blog/why-is-oauth-still-hard - simultsop
5个回答

62

这是关于“新销售”API的OAuth过程,与Auth 'n' Auth或旧版Trading API无关。虽然该过程适用于沙盒环境,但在生产环境中的流程相同。

你的困惑并非没有根据。我自己使用此API流程的经历以及大部分官方开发者论坛用户的经验都很痛苦。以下内容详细介绍了生成OAuth的步骤,无论您是连接到单个专用帐户还是多个用户帐户都适用(请使用Postman按照下面的步骤进行尝试):

官方指南可以解释整个过程,因此我不太愿意在这里重新创建整个指南。不过我可以提供一个摘要:

  1. 这里获取客户端ID和客户端密钥(请勿公开共享)。

  2. 通过点击"通过你的应用程序从eBay获取令牌"并填写表单,在此处生成RuName(重定向URL名称)。该表单用于构建用户将被重定向以允许您的应用程序访问其帐户的登录页面的外观。然后,RuName将直接出现在列标题" RuName(eBay Redirect URL name)"下面。

  3. 收集您需要的范围列表。每个API终点都需要具有适当范围权限的OAuth令牌。例如,创建或替换库存项目终点需要https://api.ebay.com/oauth/api_scope/sell.inventory范围。找出您需要的终点并转到每个API文档以查找范围部分。

  4. 现在,GET请求如下:

`https://signin.sandbox.ebay.com/authorize?
client_id=<your-client-id-value>&
redirect_uri=<your-RuName-value>&
response_type=code&
scope=https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.account%20
https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.inventory`

为了方便起见,我已省略了添加state查询字符串的建议,但建议您了解它们是什么以及为何推荐在OAuth中使用。

  • 在浏览器中访问此URL将重定向您到一个登录页面,用于让用户允许您的应用程序访问其帐户,但仅限于URL中的范围。如果从PHP curl请求转储,则会得到重定向URL本身。 重要提示:即使您的应用程序只有一个用户,也需要最终用户的签署。例如,您为客户拥有一个电子商务网站,并且您想将其产品发送到他们的eBay帐户。您仍然需要每18个月至少执行一次此过程(很快就会知道为什么)。

  • 一旦用户登录并确认,浏览器将显示一个“现在可以关闭此窗口”的页面。您需要进行下一步所需的授权码位于此页面的URL中作为code查询字符串。如果您正在为多个用户开发应用程序并计划实际上让他们在此页面上登录,则需要配置应用程序以获取确认响应(即前面提到的URL),并从中提取代码。此代码非常短暂。如果您通过浏览器手动检索它,则需要快速进行下一步操作。

  • 现在,您需要向https://api.sandbox.ebay.com/identity/v1/oauth2/token执行POST请求。请参阅以下结构:

  • HTTP method:   POST
    URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
    
    HTTP headers:
    Content-Type = application/x-www-form-urlencoded
    Authorization = Basic <B64-encoded-oauth-credentials> (A base64-encoded value made from your client ID and client secret, separated by colon. For example, in PHP you could generate it with: `base64_encode ("fakeclientid123:fakeclientsecret123")`)
    
    Request body (wrapped for readability):
    grant_type=authorization_code& (literally the string "authorization_code")
    code=<authorization-code-value>& (code retreived in previous step)
    redirect_uri=<RuName-value> (same RuName as earlier)
    

    如果请求成功,它将返回以下类似的内容:

    {
        "access_token": "v^1.1#i^1#p^3#r^1...XzMjRV4xMjg0",
        "token_type": "User token",
        "expires_in": 7200,
        "refresh_token": "v^1.1#i^1#p^3#r^1...zYjRV4xMjg0",
        "refresh_token_expires_in": 47304000
      }
    

    我们需要的是oauth令牌,其有效期为2小时。 第二个令牌是刷新令牌,其有效期约为18个月。请妥善保管此令牌,不要共享它,并且不要在应用程序中硬编码它。从此时开始,您的应用程序应该使用此令牌执行刷新调用,以在需要时获取新的oauth。一旦18个月到期,或者用户再次通过“允许访问”过程,您将需要执行以上所有操作以生成新的刷新令牌。假设那时API没有发生变化。

    值得注意的是,18个月的寿命不是OAuth刷新的正常过程,通常每次使用旧令牌时都应返回新的刷新令牌。

  • 要刷新OAuth:

  •   HTTP method:   POST
      URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
    
      HTTP headers:
        Content-Type = application/x-www-form-urlencoded
        Authorization = Basic <B64-encoded-oauth-credentials>
    
       Request body (wrapped for readability):
          grant_type=refresh_token&
          refresh_token=<your-refresh-token-value>&
          scope=https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.account%20
          https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.inventory
    

    希望这对你有所帮助!


    2
    @tar,撰写本文时,传递会话ID并不是检索OAuth令牌和刷新令牌的过程的一部分。在我自己开发API的任何阶段,我都不需要考虑会话ID。如果这种情况已经改变,或者如果我成功地使用了API而没有这个关键部分,请指向相关文档。 - FullStackFool
    2
    原来 eBay 的 OAuth 不支持像他们的 Auth&Auth 那样的会话 ID。这是最愚蠢的事情,因为这意味着它与不能接受 URL 的桌面客户端不兼容。对此我感到很抱歉。 - tar
    2
    官方指南是一个失效的链接。 - Jonathon Philip Chambers
    4
    我希望在我自己花费15个小时之前能找到这个指南! 这可能就是“官方”指南... - Lord Elrond
    2
    有时候,refresh_token在18个月之前就会失效。eBay API太糟糕了... - PedroD
    显示剩余12条评论

    10

    对于那些在使用过程中遇到困难的人 - 确保你正在使用编码后的代码/令牌。

    我几乎失去了理智,试图弄清楚问题出在哪里,因为ebay返回的刷新令牌是解码后的。


    2

    针对有困难的人,请注意第4步中的URL与eBay上给出的URL不同。eBay上的URL以https://auth.sandbox.ebay.com/oauth2/authorize开头,但第4步中的URL以https://signin.sandbox.ebay.com/authorize开头。

    原始答案:"最初的回答"


    2
    eBay在2018年的某个时间更改了登录URL,在文档中直到2019年才出现。请随意提出编辑建议,以修复过时信息。 - Envek

    2
    如果您是API方面的新手,为了不像我一样花费太多时间查找错误,请注意在头部部分,<client_id:client_secret> 应该使用 base64 进行编码。
    此外,在获取权限页面URL中的 code 后,在正文部分,您应该使用 URL 解码对该代码进行解码。
    还有一件事,如果您无法获得代码,或者无法看到包含此代码的接受页面,请在获取 RuName 的 RuName 页面上单击 OAuth,然后单击测试登录。然后,您将进入接受权限页面,并可以从URL中获取代码。实际上,我就是从这里获得我的代码并且它有效。
    我发现一个很好的 Github 问题,非常好地解释了所有这些内容:github/ebay-sdk-php

    enter image description here


    1
    我发现@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 {
    
      //Set variables.
      public $success = false; //Default.
      public $messages = []; //All messages.
      public $db_token = null; //The actuasl token.
    
      private $string; //String to update the token.
    
      private $access_token_expired = true; //Dfault to expired.
      private $refresh_token_expired = true;
      private $refresh_token_almost_expired = true; //Flag to display a warning message.
    
      private $client_id = 'your_client_id';
      private $secret = 'your_secret'; //API key. https://developer.ebay.com/my/keys
      private $ru_name_value = 'your_ru';
      private $scope = 'https://api.ebay.com/oauth/api_scope/sell.fulfillment';
      private $base64_encoded_credentials = null; //Initialise this in a mo.
    
      function __construct($string = null) {
        //Save the string.
        $this->string = $string;
    
        //Ininitalise the credentials.
        $this->base64_encoded_credentials = base64_encode($this->client_id . ':' . $this->secret);
    
        //Get any existing token from db.
        $this->get_token_from_db();
    
        //Check if it's expired - or almost expired. If there is no token this will not do anything.
        $this->check_db_token();
    
        //Has the current token expired??
        if(($this->access_token_expired == true) && ($this->refresh_token_expired == true)) {
          //Uh oh. Gonna have to get a new token - or display instructions on how to. Has the user entered the URL string to parse?
          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) {
          //Just the access token. Get a fresh one. If the refresh token has almost expired, display the instuctions.
          if($this->refresh_token_almost_expired == true) {
            $this->need_new_tokens_almost_instructions();
          }
          $this->refresh_token(); //Just the access token expired - go and refresh it using the refresh token.
        } else {
          //All fine. If the refresh token has almost expired, display the instructions.
          if($this->refresh_token_almost_expired == true) {
            $this->need_new_tokens_almost_instructions();
          }
    
        }
      }
    
      //Get the current token information from the DB. Should only be 1.
      private function get_token_from_db() {
        //Get token(s). Should only be 1. But loop anyhow.
        $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;
      }
    
      //Has the access token expired?
      private function check_db_token() {
        //Do we even have a token from the db?
        if($this->db_token != null) {
    
          //Access token expired?
          $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']); //Make a new object.
          $date_expires->add(DateInterval::createFromDateString($this->db_token['TokenLifetime'] . ' seconds'));
    
          //Refresh token expired?
          $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']); //Make a new object.
          $refresh_date_expires->add(DateInterval::createFromDateString($this->db_token['RefreshTokenLifetime'] . ' seconds'));
    
          //Check access token.
          $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;
          }
    
          //Check refresh token.
          $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;
          }
    
          //Was it all ok?
          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;
      }
    
      //Go and get a new token using the refresh token. Save it to the db.
      private function refresh_token() {
        $this->messages[] = 'OAUTH token expired - refreshing token...';
        // $this->messages[] = 'Using refresh token: ' . $this->db_token['RefreshTokenValue'];
    
        //Connect to Ebay API and refresh the existing oauth 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);
    
        //Setting the curl parameters.
        $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_SSLVERSION, 1);
        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);
    
        //Convert the JSON result into array
        $array_data = json_decode($data, true);
    
        //Did we get an access token?
        $access_token = null;
        if((is_array($array_data)) && (isset($array_data['access_token']))) {
    
          //Save the tokens to the database. Set variables.
          $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']);
    
          //Update. This will only be run if there is already a token in the DB. So no need to truncate.
          $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);
    
          // $this->messages[] = 'SQL: ' . $sql;
          if (@executeSQL($sql)) {
            $this->messages[] = '<span style="color:limegreen;"><strong>Success! Token refreshed and saved to database.</strong></span>';
          }
    
          //Update the token in this object from the freshly saved data.
          $this->get_token_from_db();
          $this->check_db_token(); //Re-check - this will mark the success flag in this object.
    
        } 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;
      }
    
      //Get new tokens using the string supplied.
      private function get_new_tokens($string) {
    
        //Parse the URL string supplied and get the 'code'.
        $auth_code = null;
        $parameters = parse_url($string);
        $query_array = explode('&', $parameters['query']);
        //Loop through and get code. Just in case the 'code' moves to another position.
        foreach ($query_array as $parameter) {
          $parameter_array = explode('=', $parameter);
          if($parameter_array[0] == 'code') {
            $auth_code = $parameter_array[1];
            break; //Got what we want.
          }
        }
    
        /***********************************************************************/
    
        $this->messages[] = "Getting eBay Oauth token using URL string...";
        $this->messages[] = 'Using auth code: ' . $auth_code;
    
        //Connect to Ebay API and get an oath using authorisation 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), //Get from step one.
            'redirect_uri' => $this->ru_name_value, //Same as used in part one.
        );
        $payload_string = http_build_query($payload);
    
        //Setting the curl parameters.
        $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_SSLVERSION, 1);
        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);
    
        //Convert the JSON result into array
        $array_data = json_decode($data, true);
    
        //Did we get an access token?
        $access_token = null;
        if((is_array($array_data)) && (isset($array_data['access_token']))) {
    
          //Save the tokens to the database. Set variables.
          $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']);
    
          //Truncate and then insert. There may or may not be an existing token in the db.
          $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>';
          }
    
          //Update the token in the object from the freshly saved data.
          $this->get_token_from_db();
          $this->check_db_token(); //Re-check - this will mark the success flag.
    
        } 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;
      }
    
      //Instructions to get a new refresh token.
      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.";
    
        //Connect to Ebay API and get consent. The authorization code grant flow. https://developer.ebay.com/api-docs/static/oauth-authorization-code-grant.html
        $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;
      }
    
      //Instructions to get a new refresh token - refresh token has ALMOST expired.
      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.";
    
        //Connect to Ebay API and get consent. The authorization code grant flow. https://developer.ebay.com/api-docs/static/oauth-authorization-code-grant.html
        $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;
      }
    
      //Delete any tokens from the database. Use cautiously.
      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();
    
    //Is there a string in the $_GET array? If so, feed it into the constructor.
    $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>';
    }
    
    //Is the token valid?
    if($token->success == true) {
        get_orders($token->db_token);
    }
    
    //Get ebay orders.
    function get_orders($token_data) {
        echo "<h3>Getting Ebay Orders</h3>";
    
        //Start the main request now we have the token. https://developer.ebay.com/api-docs/sell/static/orders/discovering-unfulfilled-orders.html
        $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;
    
        //Setting the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url_get_orders_full); //For 'get', add query string to end of URL.
        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);
    
        //Convert the JSON result into array
        $array_data = json_decode($data, true);
    
        print_r('<pre>');
        print_r($array_data);
        print_r('</pre>');
    
        return null;
    }
    
    ?>
    

    谢谢@Dharman - 我知道这个。这是一个我很快就拼凑起来的内部应用程序的一小段示例代码。另外,没有真正的外部输入 - 只有eBay返回的数据。无论如何...我会更新的... - Steve Goddard
    抱歉 @Dharman - 我只完成了一半的工作。我已经将 ebay 返回的所有参数添加了 mysql_real_escape_string。虽然这不是准备好的语句,但它增加了一个合理的保护级别。 - Steve Goddard

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接