【问题标题】:PHP Loop with Conditional Statement for CURL Execution用于 CURL 执行的带有条件语句的 PHP 循环
【发布时间】:2018-06-03 16:52:24
【问题描述】:

我正在使用 2 个函数来执行 CURL。第一个函数检索并存储令牌,而另一个函数使用存储的令牌执行订单。

我正在使用 file_put_contents 和 file_get_contents 来存储和检索令牌。

功能A:

function functionA() {
$ch = curl_init();

$url_token = $this->config['TOKEN'];
$id = $this->config['ID'];
$secret = $this->config['SECRET'];

curl_setopt($ch, CURLOPT_URL, $url_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"client_id\": \"$id\",
  \"client_secret\": \"$secret\",
  \"grant_type\": \"client_credentials\"
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

$json = json_decode($response, true);
$file = 'key.txt';
$token = $json['access_token'];

file_put_contents('./modules/custommodule/key.txt', $token, LOCK_EX);

//return $token;
}

功能B:

$file = './modules/custommodule/key.txt';
$retrieved_token = file_get_contents($file);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_order);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
  \"service_type\": \"xxx\",
  \"service_level\": \"xxx\",
  \"requested_tracking_number\": \"xxx\",
  \"reference\": {
    \"merchant_order_number\": \"xxx\"
  },
  \"from\": {
    \"name\": \"xxx\",
    \"phone_number\": \"xxx\",
    \"email\": \"xxx\",
    \"address\": {
      \"address1\": \"xxx\",
      \"address2\": \"xxx\",
      \"area\": \"xxx\",
      \"city\": \"xxx\",
      \"state\": \"xxx\",
      \"country\": \"xxx\",
      \"postcode\": \"xxx\"
    }
  },
  \"to\": {
    \"name\": \"xxx\",
    \"phone_number\": \"xxx\",
    \"email\": \"xxx\",
    \"address\": {
      \"address1\": \"xxx\",
      \"address2\": \"xxx\",
      \"area\": \"xxx\",
      \"city\": \"xxx\",
      \"state\": \"xxx\",
      \"country\": \"xxx\",
      \"postcode\": \"xxx\"
    }
  },
  \"parcel_job\": {
    \"pickup_instruction\": \"xxx\",
    \"delivery_instruction\": \"xxx\",
    \"delivery_start_date\": \"xxx\",
    \"delivery_timeslot\": {
      \"start_time\": \"xxx\",
      \"end_time\": \"xxx\",
      \"timezone\": \"xxx\"
    },
    \"dimensions\": {
      \"size\": \"xxx\"
    }
  }
}");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json",
  "Authorization: Bearer $retrieved_token"
));

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpcode === 401) {
    functionA();
    }
}

curl_close($ch);

file_put_contents('./modules/custommodule/response.txt', $response, LOCK_EX);
file_put_contents('./modules/custommodule/results.txt', $httpcode, LOCK_EX);

如您所见,如果令牌已过期,我将需要在启动函数 B 之前重新运行函数 A。我使用了我存储为变量 $httpcode 的状态 401。

我不确定如何在获得新的/刷新的令牌后重新运行函数 B。我应该实施哪个循环和条件来实现这一点?

谁能指出这一点?非常感谢任何帮助。

谢谢。

【问题讨论】:

  • 您需要存储token的有效期,以便在调用函数B之前检查您身边的token。如果token过期,您将请求一个新的token,然后调用函数B . 假设API授权状态会给你有效期
  • 我需要检查我是否能够获取信息。让我看看我检索令牌时可以挖掘到哪些信息。
  • 同意,虽然跟踪令牌何时过期并抢先刷新它很好,但应用程序在执行请求时也应该处理 401/403。

标签: php if-statement curl while-loop do-while


【解决方案1】:

重试框架中的一个非常基本的概念,前提是您可以保留上次获取令牌的缓存。

使用确定成功/失败所需的状态进行重构

function CurlRequestUsingTokenWithRetry( $curRequest, $previousToken )
{

   $token = $previousToken;

   $retries = 10;

   while( $retries > 0 )
   {

      $result = PerformTheCurlRequest( $curRequest, $token );

      if( $resultStatusCode == 401 )
      {
        $token = GetNewToken();
        if( !$token )
        {
          throw new Exception('getting new token failed');
        }
      }
      elseif( $resultStatusCode == 403 )
      {
        throw new Exception('oh no you are blocked');
      }
      else
      {
        return $reuslt;
      }

      $retries--;

   }

}

【讨论】:

  • 嗨@Scuzzy,我每次运行functionA() 时都能够获取令牌,因为我将它存储在key.txt 中。对于您的“if”子句状态 401,请问您如何返回执行 $result = PerformTheCurlRequest( $curRequest, $token );获得新令牌后?
  • 这取决于你来扩展这个概念,要么将 curl 代码直接嵌入其中,要么创建一个辅助函数。我的目标是演示一个简单的 while 循环结构,以允许您在根据 curl 请求失败获取新令牌后重试请求。我最近在一个项目中实现了这种结构,事实证明它简单但有效。
  • 是的,但我没有得到你在 if( $resultStatusCode == 401 ) { $token = GetNewToken(); 之后重新运行代码的部分}。是不是通过重试——;你输入?
  • 这是 while 循环的一个例子 :) $retries = 10; while( $retries > 0 ) { echo 'R'; $retries--; } 在上面的“echo”被替换为允许 while 循环继续循环,或者返回或抛出异常中断循环的工作.只有 401 会导致 while 循环不中断而继续。请注意,$token 被刷新,没有跳出循环。
猜你喜欢
  • 2014-08-30
  • 2022-12-07
  • 1970-01-01
  • 2022-11-26
  • 2013-09-08
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多