首页 > 解决方案 > 如何在自定义函数中获取订单 ID

问题描述

我正在设置一个 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'
             )
            );
    }

`

标签: phpwordpresswoocommerce

解决方案


只有触发支付时才会创建订单,在此之前您无法获取订单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创建后订单的一部分发生。

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


推荐阅读