You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

WooCommerce支付成功后触发短信通知的钩子选择问询

解决WooCommerce支付成功后触发客户短信通知的钩子问题

嘿,我来帮你搞定这个钩子的选择问题!针对支付成功后触发短信的需求,WooCommerce有几个合适的钩子,其中最精准的是 woocommerce_payment_complete

为什么选这个钩子?

这个钩子会在支付完全处理完成(订单状态更新为completedprocessing,取决于你的WooCommerce设置)时触发,正好对应你需要的「支付成功」场景,而且它的参数就是$order_id,和你写的successful_payment_notification_client函数参数完美匹配。

修正后的代码

另外,我注意到你代码里用$_REQUEST获取手机号和客户姓名,这其实不太可靠——因为支付成功的触发可能来自支付网关的后台回调,这时候$_REQUEST里不一定有这些数据。建议直接从WC_Order对象里获取,这样更稳定:

if ( isset( $this->options['wc_notify_customer_payment_successful_enable'] ) ) {
    // 替换成正确的钩子
    add_action( 'woocommerce_payment_complete', array( $this, 'successful_payment_notification_client' ) );
}

/* WooCommerce Successful payment notification client */
/* @param $order_id */
public function successful_payment_notification_client ( $order_id ) {
    $order = wc_get_order( $order_id ); // 推荐用wc_get_order代替new WC_Order,更符合最新WooCommerce规范
    
    // 从订单对象获取手机号,而不是$_REQUEST
    $mobile = $order->get_billing_phone();
    if ( empty( $mobile ) ) {
        return;
    }

    $this->sms->to = array( $mobile );
    $template_vars = array(
        '%order_id%' => $order_id,
        '%order_number%' => $order->get_order_number(),
        '%status%' => wc_get_order_status_name( $order->get_status() ), // 获取状态的友好名称,比如"Completed"而不是"completed"
        '%billing_first_name%' => $order->get_billing_first_name(),
        '%billing_last_name%' => $order->get_billing_last_name(),
        '%transaction_id%' => $order->get_transaction_id(), // 这里你之前用的是_payment_method_title,应该是交易ID的话用get_transaction_id()更准确
    );
    $message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notify_customer_payment_successful_message'] );
    $this->sms->msg = $message;
    $this->sms->SendSMS();
}

其他可选钩子

如果你需要在订单状态变为「已完成」时触发,也可以用woocommerce_order_status_completed,但注意这个钩子是在订单状态更新为completed时触发,可能晚于支付完成的时间(比如有些订单需要人工确认后才会标记为完成)。而woocommerce_payment_complete是在支付成功的第一时间触发,更适合你的短信通知需求。

内容的提问来源于stack exchange,提问作者Milad Karimi

火山引擎 最新活动