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

stripe / stripe-php / 8653696086

11 Apr 2024 09:49PM UTC coverage: 61.376% (-0.1%) from 61.521%
8653696086

push

github

ramya-stripe
Fix bad merge

6 of 6 new or added lines in 1 file covered. (100.0%)

61 existing lines in 7 files now uncovered.

2417 of 3938 relevant lines covered (61.38%)

3.14 hits per line

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

82.07
/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()
24✔
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)
23✔
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()
20✔
79
    {
80
        $this->closeCurlHandle();
20✔
81
    }
82

83
    public function initUserAgentInfo()
23✔
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()
3✔
93
    {
94
        return $this->defaultOptions;
3✔
95
    }
96

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

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

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

118
    /**
119
     * @return bool
120
     */
121
    public function getEnableHttp2()
4✔
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()
6✔
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)
2✔
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)
1✔
171
    {
172
        $this->timeout = (int) \max($seconds, 0);
1✔
173

174
        return $this;
1✔
175
    }
176

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

181
        return $this;
1✔
182
    }
183

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

189
    public function getConnectTimeout()
1✔
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)
4✔
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)
4✔
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)
4✔
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
        return $opts;
4✔
301
    }
302

303
    /**
304
     * @param 'delete'|'get'|'post' $method
305
     * @param string $absUrl
306
     * @param array $headers
307
     * @param array $params
308
     * @param bool $hasFile
309
     * @param 'preview'|'standard' $apiMode
310
     */
311
    private function constructRequest($method, $absUrl, $headers, $params, $hasFile, $apiMode)
4✔
312
    {
313
        $method = \strtolower($method);
4✔
314

315
        $opts = $this->calculateDefaultOptions($method, $absUrl, $headers, $params, $hasFile);
4✔
316
        list($absUrl, $body) = $this->constructUrlAndBody($method, $absUrl, $params, $hasFile, $apiMode);
4✔
317
        $opts = $this->constructCurlOptions($method, $absUrl, $headers, $body, $opts);
4✔
318

319
        return [$opts, $absUrl];
4✔
320
    }
321

322
    /**
323
     * @param 'delete'|'get'|'post' $method
324
     * @param string $absUrl
325
     * @param array $headers
326
     * @param array $params
327
     * @param bool $hasFile
328
     * @param 'preview'|'standard' $apiMode
329
     */
330
    public function request($method, $absUrl, $headers, $params, $hasFile, $apiMode = 'standard')
4✔
331
    {
332
        list($opts, $absUrl) = $this->constructRequest($method, $absUrl, $headers, $params, $hasFile, $apiMode);
4✔
333
        list($rbody, $rcode, $rheaders) = $this->executeRequestWithRetries($opts, $absUrl);
4✔
334

335
        return [$rbody, $rcode, $rheaders];
4✔
336
    }
337

338
    /**
339
     * @param 'delete'|'get'|'post' $method
340
     * @param string $absUrl
341
     * @param array $headers
342
     * @param array $params
343
     * @param bool $hasFile
344
     * @param callable $readBodyChunk
345
     * @param 'preview'|'standard' $apiMode
346
     */
UNCOV
347
    public function requestStream($method, $absUrl, $headers, $params, $hasFile, $readBodyChunk, $apiMode = 'standard')
×
348
    {
UNCOV
349
        list($opts, $absUrl) = $this->constructRequest($method, $absUrl, $headers, $params, $hasFile, $apiMode);
×
UNCOV
350
        $opts[\CURLOPT_RETURNTRANSFER] = false;
×
UNCOV
351
        list($rbody, $rcode, $rheaders) = $this->executeStreamingRequestWithRetries($opts, $absUrl, $readBodyChunk);
×
352

UNCOV
353
        return [$rbody, $rcode, $rheaders];
×
354
    }
355

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

381
        $writeCallback = null;
3✔
382
        $writeCallbackWrapper = function ($curl, $data) use (&$writeCallback, &$rheaders, &$determineWriteCallback) {
3✔
383
            if (null === $writeCallback) {
3✔
384
                $writeCallback = \call_user_func_array($determineWriteCallback, [$rheaders]);
3✔
385
            }
386

387
            return \call_user_func_array($writeCallback, [$curl, $data]);
3✔
388
        };
3✔
389

390
        return [$headerCallback, $writeCallbackWrapper];
3✔
391
    }
392

393
    private static function parseLineIntoHeaderArray($line, &$headers)
6✔
394
    {
395
        if (false === \strpos($line, ':')) {
6✔
396
            return \strlen($line);
6✔
397
        }
398
        list($key, $value) = \explode(':', \trim($line), 2);
6✔
399
        $headers[\trim($key)] = \trim($value);
6✔
400

401
        return \strlen($line);
6✔
402
    }
403

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

425
        // Will contain the bytes of the body of the last request
426
        // if it was not successful and should not be retries
427
        /** @var null|string */
428
        $rbody = null;
3✔
429

430
        // Status code of the last request
431
        /** @var null|bool */
432
        $rcode = null;
3✔
433

434
        // Array of headers from the last request
435
        /** @var null|array */
436
        $lastRHeaders = null;
3✔
437

438
        $errno = null;
3✔
439
        $message = null;
3✔
440

441
        $determineWriteCallback = function ($rheaders) use (
3✔
442
            &$readBodyChunk,
3✔
443
            &$shouldRetry,
3✔
444
            &$rbody,
3✔
445
            &$numRetries,
3✔
446
            &$rcode,
3✔
447
            &$lastRHeaders,
3✔
448
            &$errno
3✔
449
        ) {
3✔
450
            $lastRHeaders = $rheaders;
3✔
451
            $errno = \curl_errno($this->curlHandle);
3✔
452

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

455
            // Send the bytes from the body of a successful request to the caller-provided $readBodyChunk.
456
            if ($rcode < 300) {
3✔
457
                $rbody = null;
2✔
458

459
                return function ($curl, $data) use (&$readBodyChunk) {
2✔
460
                    // Don't expose the $curl handle to the user, and don't require them to
461
                    // return the length of $data.
462
                    \call_user_func_array($readBodyChunk, [$data]);
2✔
463

464
                    return \strlen($data);
2✔
465
                };
2✔
466
            }
467

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

470
            // Discard the body from an unsuccessful request that should be retried.
471
            if ($shouldRetry) {
1✔
472
                return function ($curl, $data) {
1✔
473
                    return \strlen($data);
1✔
474
                };
1✔
475
            } else {
476
                // Otherwise, buffer the body into $rbody. It will need to be parsed to determine
477
                // which exception to throw to the user.
478
                $rbody = '';
1✔
479

480
                return function ($curl, $data) use (&$rbody) {
1✔
481
                    $rbody .= $data;
1✔
482

483
                    return \strlen($data);
1✔
484
                };
1✔
485
            }
486
        };
3✔
487

488
        while (true) {
3✔
489
            list($headerCallback, $writeCallback) = $this->useHeadersToDetermineWriteCallback($opts, $determineWriteCallback);
3✔
490
            $opts[\CURLOPT_HEADERFUNCTION] = $headerCallback;
3✔
491
            $opts[\CURLOPT_WRITEFUNCTION] = $writeCallback;
3✔
492

493
            $shouldRetry = false;
3✔
494
            $rbody = null;
3✔
495
            $this->resetCurlHandle();
3✔
496
            \curl_setopt_array($this->curlHandle, $opts);
3✔
497
            $result = \curl_exec($this->curlHandle);
3✔
498
            $errno = \curl_errno($this->curlHandle);
3✔
499
            if (0 !== $errno) {
3✔
500
                $message = \curl_error($this->curlHandle);
1✔
501
            }
502
            if (!$this->getEnablePersistentConnections()) {
3✔
503
                $this->closeCurlHandle();
1✔
504
            }
505

506
            if (\is_callable($this->getRequestStatusCallback())) {
3✔
507
                \call_user_func_array(
1✔
508
                    $this->getRequestStatusCallback(),
1✔
509
                    [$rbody, $rcode, $lastRHeaders, $errno, $message, $shouldRetry, $numRetries]
1✔
510
                );
1✔
511
            }
512

513
            if ($shouldRetry) {
3✔
514
                ++$numRetries;
1✔
515
                $sleepSeconds = $this->sleepTime($numRetries, $lastRHeaders);
1✔
516
                \usleep((int) ($sleepSeconds * 1000000));
1✔
517
            } else {
518
                break;
3✔
519
            }
520
        }
521

522
        if (0 !== $errno) {
3✔
523
            $this->handleCurlError($absUrl, $errno, $message, $numRetries);
1✔
524
        }
525

526
        return [$rbody, $rcode, $lastRHeaders];
2✔
527
    }
528

529
    /**
530
     * @param array $opts cURL options
531
     * @param string $absUrl
532
     */
533
    public function executeRequestWithRetries($opts, $absUrl)
4✔
534
    {
535
        $numRetries = 0;
4✔
536

537
        while (true) {
4✔
538
            $rcode = 0;
4✔
539
            $errno = 0;
4✔
540
            $message = null;
4✔
541

542
            // Create a callback to capture HTTP headers for the response
543
            $rheaders = new Util\CaseInsensitiveArray();
4✔
544
            $headerCallback = function ($curl, $header_line) use (&$rheaders) {
4✔
545
                return CurlClient::parseLineIntoHeaderArray($header_line, $rheaders);
4✔
546
            };
4✔
547
            $opts[\CURLOPT_HEADERFUNCTION] = $headerCallback;
4✔
548

549
            $this->resetCurlHandle();
4✔
550
            \curl_setopt_array($this->curlHandle, $opts);
4✔
551
            $rbody = \curl_exec($this->curlHandle);
4✔
552

553
            if (false === $rbody) {
4✔
UNCOV
554
                $errno = \curl_errno($this->curlHandle);
×
UNCOV
555
                $message = \curl_error($this->curlHandle);
×
556
            } else {
557
                $rcode = \curl_getinfo($this->curlHandle, \CURLINFO_HTTP_CODE);
4✔
558
            }
559
            if (!$this->getEnablePersistentConnections()) {
4✔
UNCOV
560
                $this->closeCurlHandle();
×
561
            }
562

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

565
            if (\is_callable($this->getRequestStatusCallback())) {
4✔
566
                \call_user_func_array(
1✔
567
                    $this->getRequestStatusCallback(),
1✔
568
                    [$rbody, $rcode, $rheaders, $errno, $message, $shouldRetry, $numRetries]
1✔
569
                );
1✔
570
            }
571

572
            if ($shouldRetry) {
4✔
UNCOV
573
                ++$numRetries;
×
UNCOV
574
                $sleepSeconds = $this->sleepTime($numRetries, $rheaders);
×
UNCOV
575
                \usleep((int) ($sleepSeconds * 1000000));
×
576
            } else {
577
                break;
4✔
578
            }
579
        }
580

581
        if (false === $rbody) {
4✔
582
            $this->handleCurlError($absUrl, $errno, $message, $numRetries);
×
583
        }
584

585
        return [$rbody, $rcode, $rheaders];
4✔
586
    }
587

588
    /**
589
     * @param string $url
590
     * @param int $errno
591
     * @param string $message
592
     * @param int $numRetries
593
     *
594
     * @throws Exception\ApiConnectionException
595
     */
596
    private function handleCurlError($url, $errno, $message, $numRetries)
1✔
597
    {
598
        switch ($errno) {
599
            case \CURLE_COULDNT_CONNECT:
600
            case \CURLE_COULDNT_RESOLVE_HOST:
601
            case \CURLE_OPERATION_TIMEOUTED:
602
                $msg = "Could not connect to Stripe ({$url}).  Please check your "
×
603
                 . 'internet connection and try again.  If this problem persists, '
×
UNCOV
604
                 . "you should check Stripe's service status at "
×
UNCOV
605
                 . 'https://twitter.com/stripestatus, or';
×
606

UNCOV
607
                break;
×
608

609
            case \CURLE_SSL_CACERT:
610
            case \CURLE_SSL_PEER_CERTIFICATE:
UNCOV
611
                $msg = "Could not verify Stripe's SSL certificate.  Please make sure "
×
UNCOV
612
                 . 'that your network is not intercepting certificates.  '
×
UNCOV
613
                 . "(Try going to {$url} in your browser.)  "
×
UNCOV
614
                 . 'If this problem persists,';
×
615

UNCOV
616
                break;
×
617

618
            default:
619
                $msg = 'Unexpected error communicating with Stripe.  '
1✔
620
                 . 'If this problem persists,';
1✔
621
        }
622
        $msg .= ' let us know at support@stripe.com.';
1✔
623

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

626
        if ($numRetries > 0) {
1✔
UNCOV
627
            $msg .= "\n\nRequest was retried {$numRetries} times.";
×
628
        }
629

630
        throw new Exception\ApiConnectionException($msg);
1✔
631
    }
632

633
    /**
634
     * Checks if an error is a problem that we should retry on. This includes both
635
     * socket errors that may represent an intermittent problem and some special
636
     * HTTP statuses.
637
     *
638
     * @param int $errno
639
     * @param int $rcode
640
     * @param array|\Stripe\Util\CaseInsensitiveArray $rheaders
641
     * @param int $numRetries
642
     *
643
     * @return bool
644
     */
645
    private function shouldRetry($errno, $rcode, $rheaders, $numRetries)
15✔
646
    {
647
        if ($numRetries >= Stripe::getMaxNetworkRetries()) {
15✔
648
            return false;
6✔
649
        }
650

651
        // Retry on timeout-related problems (either on open or read).
652
        if (\CURLE_OPERATION_TIMEOUTED === $errno) {
10✔
653
            return true;
1✔
654
        }
655

656
        // Destination refused the connection, the connection was reset, or a
657
        // variety of other connection failures. This could occur from a single
658
        // saturated server, so retry in case it's intermittent.
659
        if (\CURLE_COULDNT_CONNECT === $errno) {
9✔
660
            return true;
1✔
661
        }
662

663
        // The API may ask us not to retry (eg; if doing so would be a no-op)
664
        // or advise us to retry (eg; in cases of lock timeouts); we defer to that.
665
        if (isset($rheaders['stripe-should-retry'])) {
8✔
666
            if ('false' === $rheaders['stripe-should-retry']) {
3✔
667
                return false;
1✔
668
            }
669
            if ('true' === $rheaders['stripe-should-retry']) {
2✔
670
                return true;
2✔
671
            }
672
        }
673

674
        // 409 Conflict
675
        if (409 === $rcode) {
7✔
676
            return true;
1✔
677
        }
678

679
        // Retry on 500, 503, and other internal errors.
680
        //
681
        // Note that we expect the stripe-should-retry header to be false
682
        // in most cases when a 500 is returned, since our idempotency framework
683
        // would typically replay it anyway.
684
        if ($rcode >= 500) {
6✔
685
            return true;
3✔
686
        }
687

688
        return false;
3✔
689
    }
690

691
    /**
692
     * Provides the number of seconds to wait before retrying a request.
693
     *
694
     * @param int $numRetries
695
     * @param array|\Stripe\Util\CaseInsensitiveArray $rheaders
696
     *
697
     * @return int
698
     */
699
    private function sleepTime($numRetries, $rheaders)
5✔
700
    {
701
        // Apply exponential backoff with $initialNetworkRetryDelay on the
702
        // number of $numRetries so far as inputs. Do not allow the number to exceed
703
        // $maxNetworkRetryDelay.
704
        $sleepSeconds = \min(
5✔
705
            Stripe::getInitialNetworkRetryDelay() * 1.0 * 2 ** ($numRetries - 1),
5✔
706
            Stripe::getMaxNetworkRetryDelay()
5✔
707
        );
5✔
708

709
        // Apply some jitter by randomizing the value in the range of
710
        // ($sleepSeconds / 2) to ($sleepSeconds).
711
        $sleepSeconds *= 0.5 * (1 + $this->randomGenerator->randFloat());
5✔
712

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

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

722
        return $sleepSeconds;
5✔
723
    }
724

725
    /**
726
     * Initializes the curl handle. If already initialized, the handle is closed first.
727
     */
728
    private function initCurlHandle()
5✔
729
    {
730
        $this->closeCurlHandle();
5✔
731
        $this->curlHandle = \curl_init();
5✔
732
    }
733

734
    /**
735
     * Closes the curl handle if initialized. Do nothing if already closed.
736
     */
737
    private function closeCurlHandle()
23✔
738
    {
739
        if (null !== $this->curlHandle) {
23✔
740
            \curl_close($this->curlHandle);
1✔
741
            $this->curlHandle = null;
1✔
742
        }
743
    }
744

745
    /**
746
     * Resets the curl handle. If the handle is not already initialized, or if persistent
747
     * connections are disabled, the handle is reinitialized instead.
748
     */
749
    private function resetCurlHandle()
6✔
750
    {
751
        if (null !== $this->curlHandle && $this->getEnablePersistentConnections()) {
6✔
752
            \curl_reset($this->curlHandle);
3✔
753
        } else {
754
            $this->initCurlHandle();
5✔
755
        }
756
    }
757

758
    /**
759
     * Indicates whether it is safe to use HTTP/2 or not.
760
     *
761
     * @return bool
762
     */
763
    private function canSafelyUseHttp2()
23✔
764
    {
765
        // Versions of curl older than 7.60.0 don't respect GOAWAY frames
766
        // (cf. https://github.com/curl/curl/issues/2416), which Stripe use.
767
        $curlVersion = \curl_version()['version'];
23✔
768

769
        return \version_compare($curlVersion, '7.60.0') >= 0;
23✔
770
    }
771

772
    /**
773
     * Checks if a list of headers contains a specific header name.
774
     *
775
     * @param string[] $headers
776
     * @param string $name
777
     *
778
     * @return bool
779
     */
UNCOV
780
    private function hasHeader($headers, $name)
×
781
    {
UNCOV
782
        foreach ($headers as $header) {
×
UNCOV
783
            if (0 === \strncasecmp($header, "{$name}: ", \strlen($name) + 2)) {
×
UNCOV
784
                return true;
×
785
            }
786
        }
787

UNCOV
788
        return false;
×
789
    }
790
}
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