You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce感谢页发短信 如何获取买家手机号替换$to参数

WooCommerce订单感谢页获取买家手机号的实现方案

核心问题说明

你现有代码的问题是没有获取当前跳转对应订单的实例,无法读取订单关联的联系方式。WooCommerce中订单的买家手机号统一存储在订单的账单联系字段中,不区分注册用户、访客下单场景,通过官方封装方法即可直接读取,不要直接从当前登录用户元数据中取值,否则访客下单时会完全拿不到手机号。

具体实现步骤

  • 第一步:在感谢页逻辑中通过URL携带的订单密钥,校验后获取对应WC_Order订单实例,不要直接用URL传入的order_id做查询,避免越权访问
  • 第二步:调用订单对象官方提供的get_billing_phone()方法获取买家预留的手机号,该方法兼容所有WooCommerce正式版本,无需手动读取数据库字段
  • 第三步:增加非空判断和去重逻辑,避免手机号为空时报错、用户刷新页面重复发送短信

修正后的代码示例

场景1:支付网关类内thankyou_page方法(和你现有代码结构匹配)

public function thankyou_page() {
    if ( $this->instructions ) {
        // 从URL获取订单校验密钥,查询对应订单
        $order_key = sanitize_text_field( $_GET['key'] ?? '' );
        $order_id  = wc_get_order_id_by_order_key( $order_key );
        $order     = wc_get_order( $order_id );

        $to = '';
        // 校验订单有效性后读取手机号
        if ( $order instanceof WC_Order ) {
            // 增加重复发送判断,避免刷新页面重复发短信
            if ( $order->get_meta( '_accept_sms_sent', true ) ) {
                echo wpautop( wptexturize( $this->instructions ) );
                return;
            }
            $to = sanitize_text_field( $order->get_billing_phone() );
        }

        // 手机号有效时调用短信接口
        if ( ! empty( $to ) ) {
            $api_sms = new sms_meli;
            $api_sms->send_sms( $to, 'Your Order is Accept' );
            // 标记短信已发送
            $order->update_meta_data( '_accept_sms_sent', '1' );
            $order->save();
        }

        echo wpautop( wptexturize( $this->instructions ) );
    }
}

场景2:直接挂载到woocommerce_thankyou钩子的通用实现

如果你不是在自定义支付网关类中写逻辑,可以直接挂载官方钩子实现,钩子本身会传入当前订单ID,无需手动从URL取参:

add_action( 'woocommerce_thankyou', 'send_order_accept_sms', 10, 1 );
function send_order_accept_sms( $order_id ) {
    $order = wc_get_order( $order_id );
    // 订单无效或已发送过短信直接终止
    if ( ! $order instanceof WC_Order || $order->get_meta( '_accept_sms_sent', true ) ) {
        return;
    }

    $to = sanitize_text_field( $order->get_billing_phone() );
    if ( empty( $to ) ) {
        return;
    }

    $api_sms = new sms_meli;
    $api_sms->send_sms( $to, 'Your Order is Accept' );
    // 标记已发送状态
    $order->update_meta_data( '_accept_sms_sent', '1' );
    $order->save();
}

注意事项

  • 禁止直接通过get_user_meta( get_current_user_id(), 'billing_phone', true )取手机号:未注册的访客下单时当前用户ID为0,会完全无法获取号码
  • 所有传入参数必须做安全校验和实例判断,避免参数篡改、订单不存在时触发PHP致命错误
  • 必须加发送状态标记,用户刷新感谢页、重复访问时不会重复触发短信发送

内容的提问来源于stack exchange,提问作者pishkar fully

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 06:15:47