• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

stripe / stripe-php / #7111

pending completion
#7111

push

php-coveralls

pakrym-stripe
Bump version to 10.15.0-beta.1

1831 of 2732 relevant lines covered (67.02%)

3.85 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.01
/lib/HttpClient/CurlClient.php
1
<?php
2

3
namespace Stripe\HttpClient;
4

5
use Stripe\Exception;
6
use Stripe\Stripe;
7
use Stripe\Util;
8

9
// @codingStandardsIgnoreStart
10
// PSR2 requires all constants be upper case. Sadly, the CURL_SSLVERSION
11
// constants do not abide by those rules.
12

13
// Note the values come from their position in the enums that
14
// defines them in cURL's source code.
15

16
// Available since PHP 5.5.19 and 5.6.3
17
if (!\defined('CURL_SSLVERSION_TLSv1_2')) {
18
    \define('CURL_SSLVERSION_TLSv1_2', 6);
19
}
20
// @codingStandardsIgnoreEnd
21

22
// Available since PHP 7.0.7 and cURL 7.47.0
23
if (!\defined('CURL_HTTP_VERSION_2TLS')) {
24
    \define('CURL_HTTP_VERSION_2TLS', 4);
25
}
26

27
class CurlClient implements ClientInterface, StreamingClientInterface
28
{
29
    protected static $instance;
30

31
    public static function instance()
32
    {
33
        if (!static::$instance) {
24✔
34
            static::$instance = new static();
×
35
        }
36

37
        return static::$instance;
24✔
38
    }
39

40
    protected $defaultOptions;
41

42
    /** @var \Stripe\Util\RandomGenerator */
43
    protected $randomGenerator;
44

45
    protected $userAgentInfo;
46

47
    protected $enablePersistentConnections = true;
48

49
    protected $enableHttp2;
50

51
    protected $curlHandle;
52

53
    protected $requestStatusCallback;
54

55
    /**
56
     * CurlClient constructor.
57
     *
58
     * Pass in a callable to $defaultOptions that returns an array of CURLOPT_* values to start
59
     * off a request with, or an flat array with the same format used by curl_setopt_array() to
60
     * provide a static set of options. Note that many options are overridden later in the request
61
     * call, including timeouts, which can be set via setTimeout() and setConnectTimeout().
62
     *
63
     * Note that request() will silently ignore a non-callable, non-array $defaultOptions, and will
64
     * throw an exception if $defaultOptions returns a non-array value.
65
     *
66
     * @param null|array|callable $defaultOptions
67
     * @param null|\Stripe\Util\RandomGenerator $randomGenerator
68
     */
69
    public function __construct($defaultOptions = null, $randomGenerator = null)
70
    {
71
        $this->defaultOptions = $defaultOptions;
23✔
72
        $this->randomGenerator = $randomGenerator ?: new Util\RandomGenerator();
23✔
73
        $this->initUserAgentInfo();
23✔
74

75
        $this->enableHttp2 = $this->canSafelyUseHttp2();
23✔
76
    }
77

78
    public function __destruct()
79
    {
80
        $this->closeCurlHandle();
20✔
81
    }
82

83
    public function initUserAgentInfo()
84
    {
85
        $curlVersion = \curl_version();
23✔
86
        $this->userAgentInfo = [
23✔
87
            'httplib' => 'curl ' . $curlVersion['version'],
23✔
88
            'ssllib' => $curlVersion['ssl_version'],
23✔
89
        ];
23✔
90
    }
91

92
    public function getDefaultOptions()
93
    {
94
        return $this->defaultOptions;
3✔
95
    }
96

97
    public function getUserAgentInfo()
98
    {
99
        return $this->userAgentInfo;
4✔
100
    }
101

102
    /**
103
     * @return bool
104
     */
105
    public function getEnablePersistentConnections()
106
    {
107
        return $this->enablePersistentConnections;
6✔
108
    }
109

110
    /**
111
     * @param bool $enable
112
     */
113
    public function setEnablePersistentConnections($enable)
114
    {
115
        $this->enablePersistentConnections = $enable;
1✔
116
    }
117

118
    /**
119
     * @return bool
120
     */
121
    public function getEnableHttp2()
122
    {
123
        return $this->enableHttp2;
4✔
124
    }
125

126
    /**
127
     * @param bool $enable
128
     */
129
    public function setEnableHttp2($enable)
130
    {
131
        $this->enableHttp2 = $enable;
×
132
    }
133

134
    /**
135
     * @return null|callable
136
     */
137
    public function getRequestStatusCallback()
138
    {
139
        return $this->requestStatusCallback;
6✔
140
    }
141

142
    /**
143
     * Sets a callback that is called after each request. The callback will
144
     * receive the following parameters:
145
     * <ol>
146
     *   <li>string $rbody The response body</li>
147
     *   <li>integer $rcode The response status code</li>
148
     *   <li>\Stripe\Util\CaseInsensitiveArray $rheaders The response headers</li>
149
     *   <li>integer $errno The curl error number</li>
150
     *   <li>string|null $message The curl error message</li>
151
     *   <li>boolean $shouldRetry Whether the request will be retried</li>
152
     *   <li>integer $numRetries The number of the retry attempt</li>
153
     * </ol>.
154
     *
155
     * @param null|callable $requestStatusCallback
156
     */
157
    public function setRequestStatusCallback($requestStatusCallback)
158
    {
159
        $this->requestStatusCallback = $requestStatusCallback;
2✔
160
    }
161

162
    // USER DEFINED TIMEOUTS
163

164
    const DEFAULT_TIMEOUT = 80;
165
    const DEFAULT_CONNECT_TIMEOUT = 30;
166

167
    private $timeout = self::DEFAULT_TIMEOUT;
168
    private $connectTimeout = self::DEFAULT_CONNECT_TIMEOUT;
169

170
    public function setTimeout($seconds)
171
    {
172
        $this->timeout = (int) \max($seconds, 0);
1✔
173

174
        return $this;
1✔
175
    }
176

177
    public function setConnectTimeout($seconds)
178
    {
179
        $this->connectTimeout = (int) \max($seconds, 0);
1✔
180

181
        return $this;
1✔
182
    }
183

184
    public function getTimeout()
185
    {
186
        return $this->timeout;
1✔
187
    }
188

189
    public function getConnectTimeout()
190
    {
191
        return $this->connectTimeout;
1✔
192
    }
193

194
    // END OF USER DEFINED TIMEOUTS
195

196
    /**
197
     * @param 'delete'|'get'|'post' $method
198
     * @param string $absUrl
199
     * @param string $params
200
     * @param bool $hasFile
201
     * @param 'preview'|'standard' $apiMode
202
     */
203
    private function constructUrlAndBody($method, $absUrl, $params, $hasFile, $apiMode)
204
    {
205
        $params = Util\Util::objectsToIds($params);
4✔
206
        if ('post' === $method) {
4✔
207
            $absUrl = Util\Util::utf8($absUrl);
×
208
            if ($hasFile) {
×
209
                return [$absUrl, $params];
×
210
            }
211
            if ('preview' === $apiMode) {
×
212
                return [$absUrl, \json_encode($params)];
×
213
            }
214

215
            return [$absUrl, Util\Util::encodeParameters($params)];
×
216
        }
217
        if ($hasFile) {
4✔
218
            throw new Exception\UnexpectedValueException("Unexpected. {$method} methods don't support file attachments");
×
219
        }
220
        if (0 === \count($params)) {
4✔
221
            return [Util\Util::utf8($absUrl), null];
4✔
222
        }
223
        $encoded = Util\Util::encodeParameters($params);
×
224

225
        $absUrl = "{$absUrl}?{$encoded}";
×
226
        $absUrl = Util\Util::utf8($absUrl);
×
227

228
        return [$absUrl, null];
×
229
    }
230

231
    private function calculateDefaultOptions($method, $absUrl, $headers, $params, $hasFile)
232
    {
233
        if (\is_callable($this->defaultOptions)) { // call defaultOptions callback, set options to return value
4✔
234
            $ret = \call_user_func_array($this->defaultOptions, [$method, $absUrl, $headers, $params, $hasFile]);
1✔
235
            if (!\is_array($ret)) {
1✔
236
                throw new Exception\UnexpectedValueException('Non-array value returned by defaultOptions CurlClient callback');
1✔
237
            }
238

239
            return $ret;
1✔
240
        }
241
        if (\is_array($this->defaultOptions)) { // set default curlopts from array
3✔
242
            return $this->defaultOptions;
×
243
        }
244

245
        return [];
3✔
246
    }
247

248
    private function constructCurlOptions($method, $absUrl, $headers, $body, $opts)
249
    {
250
        if ('get' === $method) {
4✔
251
            $opts[\CURLOPT_HTTPGET] = 1;
4✔
252
        } elseif ('post' === $method) {
×
253
            $opts[\CURLOPT_POST] = 1;
×
254
        } elseif ('delete' === $method) {
×
255
            $opts[\CURLOPT_CUSTOMREQUEST] = 'DELETE';
×
256
        } else {
257
            throw new Exception\UnexpectedValueException("Unrecognized method {$method}");
×
258
        }
259

260
        if ($body) {
4✔
261
            $opts[\CURLOPT_POSTFIELDS] = $body;
×
262
        }
263
        // It is only safe to retry network failures on POST requests if we
264
        // add an Idempotency-Key header
265
        if (('post' === $method) && (Stripe::$maxNetworkRetries > 0)) {
4✔
266
            if (!$this->hasHeader($headers, 'Idempotency-Key')) {
×
267
                $headers[] = 'Idempotency-Key: ' . $this->randomGenerator->uuid();
×
268
            }
269
        }
270

271
        // By default for large request body sizes (> 1024 bytes), cURL will
272
        // send a request without a body and with a `Expect: 100-continue`
273
        // header, which gives the server a chance to respond with an error
274
        // status code in cases where one can be determined right away (say
275
        // on an authentication problem for example), and saves the "large"
276
        // request body from being ever sent.
277
        //
278
        // Unfortunately, the bindings don't currently correctly handle the
279
        // success case (in which the server sends back a 100 CONTINUE), so
280
        // we'll error under that condition. To compensate for that problem
281
        // for the time being, override cURL's behavior by simply always
282
        // sending an empty `Expect:` header.
283
        $headers[] = 'Expect: ';
4✔
284

285
        $opts[\CURLOPT_URL] = $absUrl;
4✔
286
        $opts[\CURLOPT_RETURNTRANSFER] = true;
4✔
287
        $opts[\CURLOPT_CONNECTTIMEOUT] = $this->connectTimeout;
4✔
288
        $opts[\CURLOPT_TIMEOUT] = $this->timeout;
4✔
289
        $opts[\CURLOPT_HTTPHEADER] = $headers;
4✔
290
        $opts[\CURLOPT_CAINFO] = Stripe::getCABundlePath();
4✔
291
        if (!Stripe::getVerifySslCerts()) {
4✔
292
            $opts[\CURLOPT_SSL_VERIFYPEER] = false;
×
293
        }
294

295
        if (!isset($opts[\CURLOPT_HTTP_VERSION]) && $this->getEnableHttp2()) {
4✔
296
            // For HTTPS requests, enable HTTP/2, if supported
297
            $opts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2TLS;
4✔
298
        }
299

300
        // If the user didn't explicitly specify a CURLOPT_IPRESOLVE option, we
301
        // force IPv4 resolving as Stripe's API servers are only accessible over
302
        // IPv4 (see. https://github.com/stripe/stripe-php/issues/1045).
303
        // We let users specify a custom option in case they need to say proxy
304
        // through an IPv6 proxy.
305
        if (!isset($opts[\CURLOPT_IPRESOLVE])) {
4✔
306
            $opts[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4;
4✔
307
        }
308

309
        return $opts;
4✔
310
    }
311

312
    /**
313
     * @param 'delete'|'get'|'post' $method
314
     * @param string $absUrl
315
     * @param array $headers
316
     * @param array $params
317
     * @param bool $hasFile
318
     * @param 'preview'|'standard' $apiMode
319
     */
320
    private function constructRequest($method, $absUrl, $headers, $params, $hasFile, $apiMode)
321
    {
322
        $method = \strtolower($method);
4✔
323

324
        $opts = $this->calculateDefaultOptions($method, $absUrl, $headers, $params, $hasFile);
4✔
325
        list($absUrl, $body) = $this->constructUrlAndBody($method, $absUrl, $params, $hasFile, $apiMode);
4✔
326
        $opts = $this->constructCurlOptions($method, $absUrl, $headers, $body, $opts);
4✔
327

328
        return [$opts, $absUrl];
4✔
329
    }
330

331
    /**
332
     * @param 'delete'|'get'|'post' $method
333
     * @param string $absUrl
334
     * @param array $headers
335
     * @param array $params
336
     * @param bool $hasFile
337
     * @param 'preview'|'standard' $apiMode
338
     */
339
    public function request($method, $absUrl, $headers, $params, $hasFile, $apiMode = 'standard')
340
    {
341
        list($opts, $absUrl) = $this->constructRequest($method, $absUrl, $headers, $params, $hasFile, $apiMode);
4✔
342
        list($rbody, $rcode, $rheaders) = $this->executeRequestWithRetries($opts, $absUrl);
4✔
343

344
        return [$rbody, $rcode, $rheaders];
4✔
345
    }
346

347
    /**
348
     * @param 'delete'|'get'|'post' $method
349
     * @param string $absUrl
350
     * @param array $headers
351
     * @param array $params
352
     * @param bool $hasFile
353
     * @param callable $readBodyChunk
354
     * @param 'preview'|'standard' $apiMode
355
     */
356
    public function requestStream($method, $absUrl, $headers, $params, $hasFile, $readBodyChunk, $apiMode = 'standard')
357
    {
358
        list($opts, $absUrl) = $this->constructRequest($method, $absUrl, $headers, $params, $hasFile, $apiMode);
×
359
        $opts[\CURLOPT_RETURNTRANSFER] = false;
×
360
        list($rbody, $rcode, $rheaders) = $this->executeStreamingRequestWithRetries($opts, $absUrl, $readBodyChunk);
×
361

362
        return [$rbody, $rcode, $rheaders];
×
363
    }
364

365
    /**
366
     * Curl permits sending \CURLOPT_HEADERFUNCTION, which is called with lines
367
     * from the header and \CURLOPT_WRITEFUNCTION, which is called with bytes
368
     * from the body. You usually want to handle the body differently depending
369
     * on what was in the header.
370
     *
371
     * This function makes it easier to specify different callbacks depending
372
     * on the contents of the heeder. After the header has been completely read
373
     * and the body begins to stream, it will call $determineWriteCallback with
374
     * the array of headers. $determineWriteCallback should, based on the
375
     * headers it receives, return a "writeCallback" that describes what to do
376
     * with the incoming HTTP response body.
377
     *
378
     * @param array $opts
379
     * @param callable $determineWriteCallback
380
     *
381
     * @return array
382
     */
383
    private function useHeadersToDetermineWriteCallback($opts, $determineWriteCallback)
384
    {
385
        $rheaders = new Util\CaseInsensitiveArray();
3✔
386
        $headerCallback = function ($curl, $header_line) use (&$rheaders) {
3✔
387
            return self::parseLineIntoHeaderArray($header_line, $rheaders);
3✔
388
        };
3✔
389

390
        $writeCallback = null;
3✔
391
        $writeCallbackWrapper = function ($curl, $data) use (&$writeCallback, &$rheaders, &$determineWriteCallback) {
3✔
392
            if (null === $writeCallback) {
3✔
393
                $writeCallback = \call_user_func_array($determineWriteCallback, [$rheaders]);
3✔
394
            }
395

396
            return \call_user_func_array($writeCallback, [$curl, $data]);
3✔
397
        };
3✔
398

399
        return [$headerCallback, $writeCallbackWrapper];
3✔
400
    }
401

402
    private static function parseLineIntoHeaderArray($line, &$headers)
403
    {
404
        if (false === \strpos($line, ':')) {
6✔
405
            return \strlen($line);
6✔
406
        }
407
        list($key, $value) = \explode(':', \trim($line), 2);
6✔
408
        $headers[\trim($key)] = \trim($value);
6✔
409

410
        return \strlen($line);
6✔
411
    }
412

413
    /**
414
     * Like `executeRequestWithRetries` except:
415
     *   1. Does not buffer the body of a successful (status code < 300)
416
     *      response into memory -- instead, calls the caller-provided
417
     *      $readBodyChunk with each chunk of incoming data.
418
     *   2. Does not retry if a network error occurs while streaming the
419
     *      body of a successful response.
420
     *
421
     * @param array $opts cURL options
422
     * @param string $absUrl
423
     * @param callable $readBodyChunk
424
     *
425
     * @return array
426
     */
427
    public function executeStreamingRequestWithRetries($opts, $absUrl, $readBodyChunk)
428
    {
429
        /** @var bool */
430
        $shouldRetry = false;
3✔
431
        /** @var int */
432
        $numRetries = 0;
3✔
433

434
        // Will contain the bytes of the body of the last request
435
        // if it was not successful and should not be retries
436
        /** @var null|string */
437
        $rbody = null;
3✔
438

439
        // Status code of the last request
440
        /** @var null|bool */
441
        $rcode = null;
3✔
442

443
        // Array of headers from the last request
444
        /** @var null|array */
445
        $lastRHeaders = null;
3✔
446

447
        $errno = null;
3✔
448
        $message = null;
3✔
449

450
        $determineWriteCallback = function ($rheaders) use (
3✔
451
            &$readBodyChunk,
3✔
452
            &$shouldRetry,
3✔
453
            &$rbody,
3✔
454
            &$numRetries,
3✔
455
            &$rcode,
3✔
456
            &$lastRHeaders,
3✔
457
            &$errno
3✔
458
        ) {
3✔
459
            $lastRHeaders = $rheaders;
3✔
460
            $errno = \curl_errno($this->curlHandle);
3✔
461

462
            $rcode = \curl_getinfo($this->curlHandle, \CURLINFO_HTTP_CODE);
3✔
463

464
            // Send the bytes from the body of a successful request to the caller-provided $readBodyChunk.
465
            if ($rcode < 300) {
3✔
466
                $rbody = null;
2✔
467

468
                return function ($curl, $data) use (&$readBodyChunk) {
2✔
469
                    // Don't expose the $curl handle to the user, and don't require them to
470
                    // return the length of $data.
471
                    \call_user_func_array($readBodyChunk, [$data]);
2✔
472

473
                    return \strlen($data);
2✔
474
                };
2✔
475
            }
476

477
            $shouldRetry = $this->shouldRetry($errno, $rcode, $rheaders, $numRetries);
1✔
478

479
            // Discard the body from an unsuccessful request that should be retried.
480
            if ($shouldRetry) {
1✔
481
                return function ($curl, $data) {
1✔
482
                    return \strlen($data);
1✔
483
                };
1✔
484
            } else {
485
                // Otherwise, buffer the body into $rbody. It will need to be parsed to determine
486
                // which exception to throw to the user.
487
                $rbody = '';
1✔
488

489
                return function ($curl, $data) use (&$rbody) {
1✔
490
                    $rbody .= $data;
1✔
491

492
                    return \strlen($data);
1✔
493
                };
1✔
494
            }
495
        };
3✔
496

497
        while (true) {
3✔
498
            list($headerCallback, $writeCallback) = $this->useHeadersToDetermineWriteCallback($opts, $determineWriteCallback);
3✔
499
            $opts[\CURLOPT_HEADERFUNCTION] = $headerCallback;
3✔
500
            $opts[\CURLOPT_WRITEFUNCTION] = $writeCallback;
3✔
501

502
            $shouldRetry = false;
3✔
503
            $rbody = null;
3✔
504
            $this->resetCurlHandle();
3✔
505
            \curl_setopt_array($this->curlHandle, $opts);
3✔
506
            $result = \curl_exec($this->curlHandle);
3✔
507
            $errno = \curl_errno($this->curlHandle);
3✔
508
            if (0 !== $errno) {
3✔
509
                $message = \curl_error($this->curlHandle);
1✔
510
            }
511
            if (!$this->getEnablePersistentConnections()) {
3✔
512
                $this->closeCurlHandle();
1✔
513
            }
514

515
            if (\is_callable($this->getRequestStatusCallback())) {
3✔
516
                \call_user_func_array(
1✔
517
                    $this->getRequestStatusCallback(),
1✔
518
                    [$rbody, $rcode, $lastRHeaders, $errno, $message, $shouldRetry, $numRetries]
1✔
519
                );
1✔
520
            }
521

522
            if ($shouldRetry) {
3✔
523
                ++$numRetries;
1✔
524
                $sleepSeconds = $this->sleepTime($numRetries, $lastRHeaders);
1✔
525
                \usleep((int) ($sleepSeconds * 1000000));
1✔
526
            } else {
527
                break;
3✔
528
            }
529
        }
530

531
        if (0 !== $errno) {
3✔
532
            $this->handleCurlError($absUrl, $errno, $message, $numRetries);
1✔
533
        }
534

535
        return [$rbody, $rcode, $lastRHeaders];
2✔
536
    }
537

538
    /**
539
     * @param array $opts cURL options
540
     * @param string $absUrl
541
     */
542
    public function executeRequestWithRetries($opts, $absUrl)
543
    {
544
        $numRetries = 0;
4✔
545

546
        while (true) {
4✔
547
            $rcode = 0;
4✔
548
            $errno = 0;
4✔
549
            $message = null;
4✔
550

551
            // Create a callback to capture HTTP headers for the response
552
            $rheaders = new Util\CaseInsensitiveArray();
4✔
553
            $headerCallback = function ($curl, $header_line) use (&$rheaders) {
4✔
554
                return CurlClient::parseLineIntoHeaderArray($header_line, $rheaders);
4✔
555
            };
4✔
556
            $opts[\CURLOPT_HEADERFUNCTION] = $headerCallback;
4✔
557

558
            $this->resetCurlHandle();
4✔
559
            \curl_setopt_array($this->curlHandle, $opts);
4✔
560
            $rbody = \curl_exec($this->curlHandle);
4✔
561

562
            if (false === $rbody) {
4✔
563
                $errno = \curl_errno($this->curlHandle);
×
564
                $message = \curl_error($this->curlHandle);
×
565
            } else {
566
                $rcode = \curl_getinfo($this->curlHandle, \CURLINFO_HTTP_CODE);
4✔
567
            }
568
            if (!$this->getEnablePersistentConnections()) {
4✔
569
                $this->closeCurlHandle();
×
570
            }
571

572
            $shouldRetry = $this->shouldRetry($errno, $rcode, $rheaders, $numRetries);
4✔
573

574
            if (\is_callable($this->getRequestStatusCallback())) {
4✔
575
                \call_user_func_array(
1✔
576
                    $this->getRequestStatusCallback(),
1✔
577
                    [$rbody, $rcode, $rheaders, $errno, $message, $shouldRetry, $numRetries]
1✔
578
                );
1✔
579
            }
580

581
            if ($shouldRetry) {
4✔
582
                ++$numRetries;
×
583
                $sleepSeconds = $this->sleepTime($numRetries, $rheaders);
×
584
                \usleep((int) ($sleepSeconds * 1000000));
×
585
            } else {
586
                break;
4✔
587
            }
588
        }
589

590
        if (false === $rbody) {
4✔
591
            $this->handleCurlError($absUrl, $errno, $message, $numRetries);
×
592
        }
593

594
        return [$rbody, $rcode, $rheaders];
4✔
595
    }
596

597
    /**
598
     * @param string $url
599
     * @param int $errno
600
     * @param string $message
601
     * @param int $numRetries
602
     *
603
     * @throws Exception\ApiConnectionException
604
     */
605
    private function handleCurlError($url, $errno, $message, $numRetries)
606
    {
607
        switch ($errno) {
608
            case \CURLE_COULDNT_CONNECT:
609
            case \CURLE_COULDNT_RESOLVE_HOST:
610
            case \CURLE_OPERATION_TIMEOUTED:
611
                $msg = "Could not connect to Stripe ({$url}).  Please check your "
×
612
                 . 'internet connection and try again.  If this problem persists, '
×
613
                 . "you should check Stripe's service status at "
×
614
                 . 'https://twitter.com/stripestatus, or';
×
615

616
                break;
×
617

618
            case \CURLE_SSL_CACERT:
619
            case \CURLE_SSL_PEER_CERTIFICATE:
620
                $msg = "Could not verify Stripe's SSL certificate.  Please make sure "
×
621
                 . 'that your network is not intercepting certificates.  '
×
622
                 . "(Try going to {$url} in your browser.)  "
×
623
                 . 'If this problem persists,';
×
624

625
                break;
×
626

627
            default:
628
                $msg = 'Unexpected error communicating with Stripe.  '
1✔
629
                 . 'If this problem persists,';
1✔
630
        }
631
        $msg .= ' let us know at support@stripe.com.';
1✔
632

633
        $msg .= "\n\n(Network error [errno {$errno}]: {$message})";
1✔
634

635
        if ($numRetries > 0) {
1✔
636
            $msg .= "\n\nRequest was retried {$numRetries} times.";
×
637
        }
638

639
        throw new Exception\ApiConnectionException($msg);
1✔
640
    }
641

642
    /**
643
     * Checks if an error is a problem that we should retry on. This includes both
644
     * socket errors that may represent an intermittent problem and some special
645
     * HTTP statuses.
646
     *
647
     * @param int $errno
648
     * @param int $rcode
649
     * @param array|\Stripe\Util\CaseInsensitiveArray $rheaders
650
     * @param int $numRetries
651
     *
652
     * @return bool
653
     */
654
    private function shouldRetry($errno, $rcode, $rheaders, $numRetries)
655
    {
656
        if ($numRetries >= Stripe::getMaxNetworkRetries()) {
15✔
657
            return false;
6✔
658
        }
659

660
        // Retry on timeout-related problems (either on open or read).
661
        if (\CURLE_OPERATION_TIMEOUTED === $errno) {
10✔
662
            return true;
1✔
663
        }
664

665
        // Destination refused the connection, the connection was reset, or a
666
        // variety of other connection failures. This could occur from a single
667
        // saturated server, so retry in case it's intermittent.
668
        if (\CURLE_COULDNT_CONNECT === $errno) {
9✔
669
            return true;
1✔
670
        }
671

672
        // The API may ask us not to retry (eg; if doing so would be a no-op)
673
        // or advise us to retry (eg; in cases of lock timeouts); we defer to that.
674
        if (isset($rheaders['stripe-should-retry'])) {
8✔
675
            if ('false' === $rheaders['stripe-should-retry']) {
3✔
676
                return false;
1✔
677
            }
678
            if ('true' === $rheaders['stripe-should-retry']) {
2✔
679
                return true;
2✔
680
            }
681
        }
682

683
        // 409 Conflict
684
        if (409 === $rcode) {
7✔
685
            return true;
1✔
686
        }
687

688
        // Retry on 500, 503, and other internal errors.
689
        //
690
        // Note that we expect the stripe-should-retry header to be false
691
        // in most cases when a 500 is returned, since our idempotency framework
692
        // would typically replay it anyway.
693
        if ($rcode >= 500) {
6✔
694
            return true;
3✔
695
        }
696

697
        return false;
3✔
698
    }
699

700
    /**
701
     * Provides the number of seconds to wait before retrying a request.
702
     *
703
     * @param int $numRetries
704
     * @param array|\Stripe\Util\CaseInsensitiveArray $rheaders
705
     *
706
     * @return int
707
     */
708
    private function sleepTime($numRetries, $rheaders)
709
    {
710
        // Apply exponential backoff with $initialNetworkRetryDelay on the
711
        // number of $numRetries so far as inputs. Do not allow the number to exceed
712
        // $maxNetworkRetryDelay.
713
        $sleepSeconds = \min(
5✔
714
            Stripe::getInitialNetworkRetryDelay() * 1.0 * 2 ** ($numRetries - 1),
5✔
715
            Stripe::getMaxNetworkRetryDelay()
5✔
716
        );
5✔
717

718
        // Apply some jitter by randomizing the value in the range of
719
        // ($sleepSeconds / 2) to ($sleepSeconds).
720
        $sleepSeconds *= 0.5 * (1 + $this->randomGenerator->randFloat());
5✔
721

722
        // But never sleep less than the base sleep seconds.
723
        $sleepSeconds = \max(Stripe::getInitialNetworkRetryDelay(), $sleepSeconds);
5✔
724

725
        // And never sleep less than the time the API asks us to wait, assuming it's a reasonable ask.
726
        $retryAfter = isset($rheaders['retry-after']) ? (float) ($rheaders['retry-after']) : 0.0;
5✔
727
        if (\floor($retryAfter) === $retryAfter && $retryAfter <= Stripe::getMaxRetryAfter()) {
5✔
728
            $sleepSeconds = \max($sleepSeconds, $retryAfter);
5✔
729
        }
730

731
        return $sleepSeconds;
5✔
732
    }
733

734
    /**
735
     * Initializes the curl handle. If already initialized, the handle is closed first.
736
     */
737
    private function initCurlHandle()
738
    {
739
        $this->closeCurlHandle();
5✔
740
        $this->curlHandle = \curl_init();
5✔
741
    }
742

743
    /**
744
     * Closes the curl handle if initialized. Do nothing if already closed.
745
     */
746
    private function closeCurlHandle()
747
    {
748
        if (null !== $this->curlHandle) {
23✔
749
            \curl_close($this->curlHandle);
1✔
750
            $this->curlHandle = null;
1✔
751
        }
752
    }
753

754
    /**
755
     * Resets the curl handle. If the handle is not already initialized, or if persistent
756
     * connections are disabled, the handle is reinitialized instead.
757
     */
758
    private function resetCurlHandle()
759
    {
760
        if (null !== $this->curlHandle && $this->getEnablePersistentConnections()) {
6✔
761
            \curl_reset($this->curlHandle);
3✔
762
        } else {
763
            $this->initCurlHandle();
5✔
764
        }
765
    }
766

767
    /**
768
     * Indicates whether it is safe to use HTTP/2 or not.
769
     *
770
     * @return bool
771
     */
772
    private function canSafelyUseHttp2()
773
    {
774
        // Versions of curl older than 7.60.0 don't respect GOAWAY frames
775
        // (cf. https://github.com/curl/curl/issues/2416), which Stripe use.
776
        $curlVersion = \curl_version()['version'];
23✔
777

778
        return \version_compare($curlVersion, '7.60.0') >= 0;
23✔
779
    }
780

781
    /**
782
     * Checks if a list of headers contains a specific header name.
783
     *
784
     * @param string[] $headers
785
     * @param string $name
786
     *
787
     * @return bool
788
     */
789
    private function hasHeader($headers, $name)
790
    {
791
        foreach ($headers as $header) {
×
792
            if (0 === \strncasecmp($header, "{$name}: ", \strlen($name) + 2)) {
×
793
                return true;
×
794
            }
795
        }
796

797
        return false;
×
798
    }
799
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc