如何使用动作挂钩woocommerce_checkout_order_processed获取订单ID

时间:2019-08-14 10:14:00

标签: php wordpress woocommerce

我正在设置woocommerce付款插件。我创建了一个付款字段,该字段应在收到付款之前显示订单ID。

我已经看到了这个答案Get the order ID in checkout page before payment process,但是我不知道如何使用自定义功能。 `

public function payment_fields(){
global $woocommerce;

$amount = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) );

///This works if the order has been already placed
$order = new WC_Order($post->ID);
$order_id = $order->get_id();

$shortcode = $this->shortcode;

$steps="Go to Safaricom Menu on your phone<br>
Select M-PESA<br>
Select Lipa na MPESA<br>
Select Pay Bill<br>
Enter Business No: $shortcode<br>
Enter Account No:$order_id<br>
Enter Amount: $amount <br>
Enter the transaction code you received from MPESA in the form below<br>";
echo wpautop( wptexturize( $steps) );

//This add the form field for Pay bill customers 
 woocommerce_form_field( 'mpesaid', array(
                'title'     => __( 'MPESA Reference', 'cwoa-authorizenet-aim' ),
                'type'      => 'text',
                'label'       => 'M-PESA Reference',
                'required'    => true,
                'maxlength'    => '10'
             )
            );
    }

`

1 个答案:

答案 0 :(得分:-1)

仅在触发付款时创建订单,在此之前您无法获得订单ID。因此,在提交之前,您将无法在结帐字段上填写订单ID。

过程如下:

下面的代码是从class-wc-checkout.php复制的。

  $order_id = $this->create_order( $posted_data );
  $order    = wc_get_order( $order_id );
  if ( is_wp_error( $order_id ) ) {
    throw new Exception( $order_id->get_error_message() );
  }
  if ( ! $order ) {
    throw new Exception( __( 'Unable to create order.', 'woocommerce' ) );
  }
  do_action( 'woocommerce_checkout_order_processed', $order_id, $posted_data, $order );
  if ( WC()->cart->needs_payment() ) {
    $this->process_order_payment( $order_id, $posted_data['payment_method'] );
  } else {
    $this->process_order_without_payment( $order_id );
  }

因此,基本上,在所有这些操作发生之前您就无法获得订单ID,并且正如您所看到的那样,即使您建议的方法也仅在创建订单后作为process_checkout的一部分发生。

建议是在结帐访问时更改流程并触发订单创建,但这尚未经过测试,并且我尚未检查所有方面,因此您可能会遇到多个问题。