【问题标题】:How to get the order id in a custom function如何在自定义函数中获取订单 ID
【发布时间】:2019-08-14 10:14:00
【问题描述】:

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

`

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案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 的一部分发生。

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

    【讨论】:

    • 我从结账处了解到,我可以在订单支付页面处理付款。现在我已经为支付网关处理了 // 响应 public function process_payment( $order_id ) { global $woocommerce; $order = new WC_Order( $order_id ); $environment_url = $this->checkurl; $order->update_status('待付款', __( '待付款', 'woocommerce' )); $woocommerce->购物车->empty_cart(); return array('result' => 'success', 'redirect' => $order->get_checkout_payment_url()); } '
    • 这会将我重定向到 site.com/checkout/order-pay/46/ 现在购买 我无法处理付款...并且用户无法使用相同的网关进行付款 :)跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 2014-03-05
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2019-10-11
    • 2017-08-26
    相关资源
    最近更新 更多