php Webhook问题,它返回的值不超过200

m2xkgtsf  于 5个月前  发布在  PHP
关注(0)|答案(3)|浏览(47)

我正在使用WordPress,我想在我的服务器上包含一个条带webhook端点。我不知道为什么,但即使我硬编码错误“400”发送到条带它发送“200”,我不知道为什么,这似乎很奇怪,但\Stripe\StripeClient(STRIPE_TEST_KEY);似乎发送响应“200”,因为在此指令之后什么也没有发生。
下面是我的代码:

require_once('wp-content/plugins/myplugin/stripe/init.php');
require_once( dirname( __FILE__ ) . '/wp-load.php' );

/*$stripe = new */
\Stripe\StripeClient(STRIPE_TEST_KEY);
$response = ["user" => 6];
http_response_code(400);
header('Content-Type: application/json'); // Setting header
echo json_encode($response); // Sending response
exit();

// This is your Stripe CLI webhook secret for testing your endpoint locally.
$endpoint_secret = 'whsec_Qz...';

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;

try {
  $event = \Stripe\Webhook::constructEvent(
    $payload, $sig_header, $endpoint_secret
  );
} catch(\UnexpectedValueException $e) {
  // Invalid payload
  http_response_code(400);
  exit(); 
} catch(\Stripe\Exception\SignatureVerificationException $e) {
  // Invalid signature
  http_response_code(400);
  
}

http_response_code(200);

字符串
通常,此代码应发送以条带化响应'400',但它没有,并且如果指令

$response = ["user" => 6];
header('Content-Type: application/json'); // Setting header
echo json_encode($response); // Sending response
exit();


被放在前面:

\Stripe\StripeClient(STRIPE_TEST_KEY);


它向stripe发送响应“400”。
我读了文件,但我什么也没发现。

jei2mxaa

jei2mxaa1#

您只在catch语句中指定了400错误代码。
下面这一行,不设置你的响应状态码为任何东西,大概只是发送回一个200状态响应。

header('Content-Type: application/json'); // Setting header
echo json_encode($response); // Sending response
exit();

字符串
我下面有这个代码,它从我几年前创建的一个插件的stipe中捕获webhook,你可以参考,如果你想在没有实际捕获和错误的情况下向stripe发送错误响应,你需要在try-catch块之外定义http_response_code(400);

public function captureStipeWebhook() {
    $action = isset( $_REQUEST['stripe_bacs_webhook'] ) ? $_REQUEST['stripe_bacs_webhook'] : false;
    
    if ( !$action || !in_array( $action, ['live', 'test']))
        return;

    \Stripe\Stripe::setApiKey( $this->stripeSecretKey() );
    
    $payload = @file_get_contents('php://input');
    $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
    $response = null;   
    
    try {
        $response = \Stripe\Webhook::constructEvent(
            $payload, $sig_header, get_option( $this->stripeOptNameSecret() )
        );
        
        if ( 
                $response->type === 'checkout.session.completed' 
                && isset( $response->data->object->metadata->sb_sub )  
                && $this->url() == $response->data->object->metadata->url  
            ) {
            $intent = \Stripe\SetupIntent::retrieve( $response->data->object->setup_intent );
            $prices = explode(',', str_replace(' ', '', $response->data->object->metadata->selected_price) );
            $oneTimeCharges = $response->data->object->metadata->additional_items ? explode(',', str_replace(' ', '', $response->data->object->metadata->additional_items) ) : false;
            $items = [];
            $oneTimeItems = [];
            foreach ( $prices as $price ) {
                if ( $price && $price !== '' ) {
                    $items[] = ['price' => $price];
                }
            }
            foreach ( $oneTimeCharges as $otc ) {
                if ( $otc && $otc !== '' && $otc !== 'false' ) {
                    $oneTimeItems[] = ['price' => $otc];
                }
            }
            $subData = [
                'customer' => $intent->customer,                
                'default_payment_method' => $intent->payment_method,
                'items' => [$items],                    
            ];
            if ( $oneTimeItems ) {
                $subData['add_invoice_items'] = $oneTimeItems;
            }
            if ( isset( $response->data->object->metadata->selected_coupon ) ) {
                $subData['coupon'] = $response->data->object->metadata->selected_coupon;
            }
            $subscription = \Stripe\Subscription::create( $subData, [
                'idempotency_key' => $response->data->object->metadata->iptc_key
            ]);
            //$this->log( 'webhook-event', json_encode( $subscription ) ) ;
            wp_send_json([$subData, $subscription]);
        } else {
            $responseMessage = [
                'message' => 'Webhook Received!',
                'type'  => 'No Sub'
            ];
        }     
    } catch(\UnexpectedValueException $e) {
        // Invalid payload
        http_response_code(400);
        $this->log( 'webhook-error', json_encode( $e->getMessage() ) ) ;
        $responseMessage = $e->getMessage();
    } catch(\Stripe\Exception\SignatureVerificationException $e) {
        // Invalid signature
        http_response_code(400);
        $this->log( 'webhook-error', json_encode( $e->getMessage() ) ) ;
        $responseMessage = $e->getMessage();
    }
    wp_send_json([$responseMessage]);
}

u59ebvdq

u59ebvdq2#

如果不将数据发送回条带,则不必为端点设置header('Content-Type: application/json');
下面是我目前设置的代码:

$payload = file_get_contents('php://input');

if(!$payload) {
    http_response_code(400);
    exit(); 
}

if( !isset($_SERVER["HTTP_STRIPE_SIGNATURE"])){
    http_response_code(401);
    exit(); 
}

$endpoint_secret = 'whsec_Qz...';
$event = null;

try {
    $event = \Stripe\Event::constructFrom(
        json_decode($payload, true)
    );
} catch(\UnexpectedValueException $e) {
    echo '⚠️  Webhook error while parsing basic request.';
    http_response_code(400);
    exit();
}

if ($endpoint_secret) {
    $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
    try {
        $event = \Stripe\Webhook::constructEvent(
            $payload, $sig_header, $endpoint_secret
        );
    } catch(\Stripe\Exception\SignatureVerificationException $e) {
        echo '⚠️  Webhook error while validating signature.';
        http_response_code(400);
        exit();
    }
}

switch ($event->type) {
    case 'checkout.session.completed':

//Do stuff
break;
default:
        exit();
}

http_response_code(200);

字符串

8dtrkrch

8dtrkrch3#

我通过声明来解决我的问题:

new \Stripe\StripeClient(STRIPE_TEST_KEY);

字符串
而不仅仅是:

\Stripe\StripeClient(STRIPE_TEST_KEY);

相关问题