php - 如何在自定义函数中获取订单 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'
)
);
}
`
解决方案
只有触发支付时才会创建订单,在此之前您无法获取订单ID。因此,您将无法在提交之前在结帐字段中填充订单 ID。
过程如下:
- 在woocommerce/includes/class-wc-form-handler.php上,这些函数
checkout_action
被挂钩wp_loaded
以监听发布请求。 - 如果已触发结帐提交(下订单),则结帐处理开始
WC()->checkout()->process_checkout();
- 在woocommerce/includes/class-wc-checkout.php上,这些函数
process_checkout
将创建一个订单,如下所示:
下面的代码是从 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
创建后订单的一部分发生。
一个建议是在结帐访问时更改流程并触发订单创建,但这未经测试,我还没有检查所有方面,因此您可能会遇到多个问题。
推荐阅读
- macos - 如果我在 MacBook Pro 上重新打开终端,则找不到 nvm
- android - 无障碍服务对事件的行为
- angular - 角路由器散列
- googleplacesautocomplete - 需要在 Google Place Autocomplete 中获取英文地名
- django - Django 使用中间件设置 cookie 在第一页加载时失败
- electron - 带有私有 GitHub 存储库的电子自动更新器?
- django - 如何将通用视图转换为具有模式列表的基于类的视图
- excel - VBA 使用子参数中的值填充不同的对象
- node.js - 托管使用 ExpressJS 进行后端操作的 REACT 应用程序的步骤是什么?
- c# - 程序找不到路径部分视图