如何在WooCommerce Blocks中关联Stripe客户至Payment Intent实现延迟捕获
我需要实现Stripe预授权扣款,待客户确认保留商品后再进行捕获操作。在WooCommerce传统短代码结账流程中,Stripe会自动将客户关联至Payment Intent,后续捕获可正常执行;但在WooCommerce Blocks结账流程中,客户未被关联到支付方式,导致支付方式失效,后续捕获操作失败。
我已编写用于关联客户与支付方式的函数:
function attach_stripe_customer_to_payment_method( $payment_method_id, $customer_id, $stripe_secret ) { $response = wp_remote_post( "https://api.stripe.com/v1/payment_methods/$payment_method_id/attach", array( 'method' => 'POST', 'headers' => array( 'Authorization' => 'Bearer ' . $stripe_secret, ), 'body' => array( 'customer' => $customer_id, ), ) ); return wp_remote_retrieve_body( $response ); }
在传统短代码结账流程中,我可通过woocommerce_checkout_order_processed钩子获取$payment_method_id并完成关联:
add_action( 'woocommerce_checkout_order_processed', function( $order_id, $posted_data, $order ) { // 此处可正常获取payment_method_id并关联客户 }, 10, 3 );
但在Blocks结账流程中,仅能使用woocommerce_store_api_checkout_order_processed钩子,无法在此处获取$payment_method_id:
add_action( 'woocommerce_store_api_checkout_order_processed', function( $order ) { // 无法获取payment_method_id,无法关联客户 }, 10, 1 );
$payment_method_id仅能在woocommerce_thankyou钩子中获取,但此时Stripe已标记支付方式为已使用,导致Payment Intent无法用于后续延迟捕获。
请问如何在WooCommerce Blocks结账流程中更早获取$payment_method_id,以便关联客户并保留预授权用于后续捕获?
可以利用Stripe for WooCommerce插件提供的wc_stripe_payment_intent_created钩子,该钩子会在Payment Intent创建完成后立即触发,无论使用传统结账还是Blocks结账流程,都能在此阶段获取到$payment_method_id和订单关联的客户信息,提前完成客户与支付方式的关联,避免后续捕获失败。
具体实现代码如下:
add_action( 'wc_stripe_payment_intent_created', function( $payment_intent, $order ) { // 获取Stripe密钥 $stripe_secret = wc_stripe_get_secret_key(); // 获取订单关联的WordPress用户ID,读取对应的Stripe客户ID $wp_user_id = $order->get_user_id(); $stripe_customer_id = get_user_meta( $wp_user_id, '_stripe_customer_id', true ); // 验证Stripe客户ID和支付方式ID是否存在 if ( $stripe_customer_id && ! empty( $payment_intent->payment_method ) ) { // 调用关联函数完成客户与支付方式的绑定 attach_stripe_customer_to_payment_method( $payment_intent->payment_method, $stripe_customer_id, $stripe_secret ); } }, 10, 2 );
关键说明
wc_stripe_payment_intent_created钩子传递两个核心参数:$payment_intent(Stripe的Payment Intent对象)和$order(WooCommerce订单对象),可直接从$payment_intent->payment_method获取支付方式ID。- WooCommerce Stripe插件会自动为注册用户创建并存储Stripe客户ID(元数据键为
_stripe_customer_id),无需额外创建逻辑。 - 该钩子触发时,Payment Intent仍处于预授权状态,尚未被标记为已使用,完全满足后续延迟捕获的需求。
若需支持访客下单场景,可先为访客创建临时Stripe客户并关联,待用户注册后再迁移客户信息,确保支付方式关联的稳定性。
内容的提问来源于stack exchange,提问作者Awais Aezad

