PHP code example of erikwang2013 / stripe-php-erik

1. Go to this page and download the library: Download erikwang2013/stripe-php-erik library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

erikwang2013 / stripe-php-erik example snippets










use Erikwang2013\Stripe\StripeClient;

class PaymentController
{
    public function charge(StripeClient $stripe)
    {
        $charge = $stripe->charges->create([
            'amount' => 2000,
            'currency' => 'usd',
            'source' => 'tok_visa',
        ]);

        return response()->json($charge);
    }
}

use Erikwang2013\Stripe\Laravel\Facade\Stripe;

$customer = Stripe::customers()->create([
    'email' => '[email protected]',
]);

$stripe = app('stripe');
$customer = $stripe->customers->create(['email' => '[email protected]']);

use Erikwang2013\Stripe\Webhook;
use Illuminate\Http\Request;

Route::post('/stripe/webhook', function (Request $request) {
    $signature = $request->header('Stripe-Signature');
    $secret = config('stripe.webhook_secret');

    try {
        $event = Webhook::constructEvent(
            $request->getContent(),
            $signature,
            $secret
        );

        // Handle event... · 处理事件...

        return response('', 200);
    } catch (\Exception $e) {
        return response('', 400);
    }
});


return [
    'api_key' => getenv('STRIPE_API_KEY') ?: '',
    'api_base' => getenv('STRIPE_API_BASE') ?: null,
    'api_version' => getenv('STRIPE_API_VERSION') ?: null,
    'webhook_secret' => getenv('STRIPE_WEBHOOK_SECRET') ?: '',
    'client_id' => getenv('STRIPE_CLIENT_ID') ?: null,
    'max_network_retries' => getenv('STRIPE_MAX_NETWORK_RETRIES') ?: 0,
    'enable_telemetry' => getenv('STRIPE_ENABLE_TELEMETRY') ?: true,
    'ca_bundle_path' => getenv('STRIPE_CA_BUNDLE_PATH') ?: null,
    'app_info' => [
        'name' => getenv('STRIPE_APP_NAME') ?: null,
        'version' => getenv('STRIPE_APP_VERSION') ?: null,
        'url' => getenv('STRIPE_APP_URL') ?: null,
    ],
];

use Erikwang2013\Stripe\Webman\StripeHelper;

// Initialize on worker start · 在 Worker 启动时初始化
StripeHelper::init();

use Erikwang2013\Stripe\Webman\StripeHelper;
use Erikwang2013\Stripe\StripeClient;

// Via helper · 通过辅助类
$stripe = StripeHelper::client();
$customer = $stripe->customers->create([
    'email' => '[email protected]',
]);

// Or directly · 或直接使用
$stripe = new StripeClient(getenv('STRIPE_API_KEY'));

use Erikwang2013\Stripe\Webhook;
use Webman\Http\Request;
use Webman\Http\Response;

class StripeWebhook
{
    public function index(Request $request): Response
    {
        $signature = $request->header('Stripe-Signature');
        $secret = config('plugin.stripe.webhook_secret');

        try {
            $event = Webhook::constructEvent(
                $request->rawBody(),
                $signature,
                $secret
            );

            // Handle event... · 处理事件...

            return response('', 200);
        } catch (\Exception $e) {
            return response('', 400);
        }
    }
}

use Erikwang2013\Stripe\StripeClient;
use Hyperf\Di\Annotation\Inject;

class PaymentController extends AbstractController
{
    #[Inject]
    protected StripeClient $stripe;

    public function charge()
    {
        $charge = $this->stripe->charges->create([
            'amount' => 2000,
            'currency' => 'usd',
            'source' => 'tok_visa',
        ]);

        return $this->response->json($charge->toArray());
    }
}


return [
    'api_key' => env('stripe.api_key', ''),
    'api_base' => env('stripe.api_base', null),
    'api_version' => env('stripe.api_version', null),
    'webhook_secret' => env('stripe.webhook_secret', ''),
    'client_id' => env('stripe.client_id', null),
    'max_network_retries' => env('stripe.max_network_retries', 0),
    'enable_telemetry' => env('stripe.enable_telemetry', true),
    'ca_bundle_path' => env('stripe.ca_bundle_path', null),
    'app_info' => [
        'name' => env('stripe.app_name', null),
        'version' => env('stripe.app_version', null),
        'url' => env('stripe.app_url', null),
    ],
];

use Erikwang2013\Stripe\ThinkPHP\StripeHelper;

class AppService extends Service
{
    public function boot()
    {
        StripeHelper::init();
    }
}

use Erikwang2013\Stripe\ThinkPHP\StripeHelper;
use Erikwang2013\Stripe\StripeClient;

// Via helper · 通过辅助类
$stripe = StripeHelper::client();
$customer = $stripe->customers->create([
    'email' => '[email protected]',
]);

// Via container (when StripeService is registered) · 通过容器(StripeService 注册后)
$stripe = app('stripe');
// Or via DI · 或依赖注入
// public function __construct(StripeClient $stripe) { ... }

// Or directly · 或直接使用
$stripe = new StripeClient(config('stripe.api_key'));

use Erikwang2013\Stripe\Webhook;

class StripeWebhook
{
    public function index()
    {
        $signature = request()->header('Stripe-Signature');
        $secret = config('stripe.webhook_secret');

        try {
            $event = Webhook::constructEvent(
                request()->getContent(),
                $signature,
                $secret
            );

            // Handle event... · 处理事件...

            return response('', 200);
        } catch (\Exception $e) {
            return response('', 400);
        }
    }
}

$stripe = new \Erikwang2013\Stripe\StripeClient('sk_test_...');
$customer = $stripe->customers->create([
    'description' => 'example customer',
    'email' => '[email protected]',
    'payment_method' => 'pm_card_visa',
]);
echo $customer;

// set up your tweaked Curl client · 配置自定义 Curl 客户端
$curl = new \Erikwang2013\Stripe\HttpClient\CurlClient();
$curl->setTimeout(10); // default is \Erikwang2013\Stripe\HttpClient\CurlClient::DEFAULT_TIMEOUT
$curl->setConnectTimeout(5); // default is \Erikwang2013\Stripe\HttpClient\CurlClient::DEFAULT_CONNECT_TIMEOUT

echo $curl->getTimeout(); // 10
echo $curl->getConnectTimeout(); // 5

// tell Stripe to use the tweaked client · 让 Stripe 使用自定义客户端
\Erikwang2013\Stripe\ApiRequestor::setHttpClient($curl);

// use the Stripe API client as you normally would · 正常使用即可

// set up your tweaked Curl client · 配置带代理的 Curl 客户端
$curl = new \Erikwang2013\Stripe\HttpClient\CurlClient([CURLOPT_PROXY => 'proxy.local:80']);
// tell Stripe to use the tweaked client · 让 Stripe 使用此客户端
\Erikwang2013\Stripe\ApiRequestor::setHttpClient($curl);

\Erikwang2013\Stripe\Stripe::setLogger($logger);

$customer = $stripe->customers->create([
    'description' => 'example customer',
]);
echo $customer->getLastResponse()->headers['Request-Id'];

$curl = new \Erikwang2013\Stripe\HttpClient\CurlClient([CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1]);
\Erikwang2013\Stripe\ApiRequestor::setHttpClient($curl);

$customers = $stripe->customers->all([],[
    'api_key' => 'sk_test_...',
    'stripe_account' => 'acct_...'
]);

$stripe->customers->retrieve('cus_123456789', [], [
    'api_key' => 'sk_test_...',
    'stripe_account' => 'acct_...'
]);

\Erikwang2013\Stripe\Stripe::setCABundlePath("path/to/ca/bundle");

\Erikwang2013\Stripe\Stripe::setMaxNetworkRetries(2);

\Erikwang2013\Stripe\Stripe::setEnableTelemetry(false);

$stripe = new \Erikwang2013\Stripe\StripeClient('sk_test_xyz');
$response = $stripe->rawRequest('post', '/v1/beta_endpoint', [
  "caveat": "emptor"
], [
  "stripe_version" => "2022-11_15",
]);
// $response->body is a string, you can call $stripe->deserialize to get a \Erikwang2013\Stripe\StripeObject.
$obj = $stripe->deserialize($response->body);

// For GET requests, the params argument must be null, and you should write the query string explicitly.
$get_response = $stripe->rawRequest('get', '/v1/beta_endpoint?caveat=emptor', null, [
  "stripe_version" => "2022-11_15",
]);

\Erikwang2013\Stripe\Stripe::setAppInfo("MyAwesomePlugin", "1.2.34", "https://myawesomeplugin.info");
bash
composer 
bash
composer 

src/
├── Laravel/
│   ├── StripeServiceProvider.php   # 服务提供者:注册、配置发布、别名
│   └── Facade/
│       └── Stripe.php              # 门面:静态代理 StripeClient
├── Webman/
│   ├── Install.php                 # 插件安装器:WEBMAN_PLUGIN 标记 + 配置拷贝
│   └── StripeHelper.php            # 辅助类:init() + client()
├── Hyperf/
│   ├── ConfigProvider.php          # 配置提供器:DI 定义 + 配置发布 + boot()
│   └── StripeClientFactory.php     # 工厂:从容器创建 StripeClient
├── ThinkPHP/
│   ├── StripeService.php           # think\Service:容器绑定 + 自动注册
│   └── StripeHelper.php            # 辅助类:init() + client()
config/
└── stripe.php                      # 通用配置模板(含中英文注释)

composer �
      ├─── Laravel ──→ auto-discovery → ServiceProvider::register() → 容器绑定
      │                                 → ServiceProvider::boot()     → 配置合并
      │
      ├─── Webman  ──→ WEBMAN_PLUGIN 标记 → webman 启动时自动发现
      │             ──→ process.php 中手动 StripeHelper::init()
      │
      ├─── Hyperf  ──→ ConfigProvider::__invoke() → DI 定义注册
      │             ──→ 手动 php bin/hyperf.php vendor:publish
      │             ──→ 应用启动时 ConfigProvider::boot()
      │
      └─── ThinkPHP ──→ extra.think.services → StripeService::register() → 容器绑定
                                                StripeService::boot()     → 初始化
bash
php artisan vendor:publish --tag=stripe-config
bash
composer 
bash
composer 
bash
php bin/hyperf.php vendor:publish erikwang2013/stripe-php-erik
bash
composer 
bash
just test tests/Stripe/UtilTest.php
# or: ./vendor/bin/phpunit tests/Stripe/UtilTest.php
bash
./update_certs.php