【问题标题】:Get current Order ID for Woocommerce user cart获取 Woocommerce 用户购物车的当前订单 ID
【发布时间】:2017-10-11 11:55:12
【问题描述】:

我正在向 WP Woocommerce 添加自定义支付网关。 我想获取创建的购物车的当前用户 order_id。

我可以获得购物车总数:

global $woocommerce;
$total= $woocommerce->cart->total ;

或与:

WC()->cart->get_total() ;

如何调用函数:

process_payment($order_id)

当我还没有 $order_id 而我只有购物车时?

(错误的问题:还没有order_id)

【问题讨论】:

  • 您在购物车中时还没有订单...订单ID仅在您订购商品后出现。
  • 支付完成后如何获取ID?
  • @iheb 您应该更新您的问题以反映您想要的内容。您首先询问如何从购物车中获取订单 ID,然后在购买完成后...

标签: wordpress woocommerce payment-gateway


【解决方案1】:

最初提出的问题的答案是:

您的购物车中还没有订单 ID。 只有结帐完成后,订单 ID 才存在。

答案与问题不相符,可能需要再次询问或编辑。

【讨论】:

    【解决方案2】:
    add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
    function custom_process_order($order_id) {
        $order = new WC_Order( $order_id );
        $myuser_id = (int)$order->user_id;
        $user_info = get_userdata($myuser_id);
        $items = $order->get_items();
        foreach ($items as $item) {
            if ($item['product_id']==24) {
              // Do something clever
            }
        }
        return $order_id;
    }
    

    这将挂钩到 WooCommerce 以在下订单后触发 custom_process_order

    【讨论】:

    • 收到付款后如何启动创建订单流程?
    • @lheb Saad:我没有明白你的意思——我的回答将帮助你在付款完成后获得 ID。在调用上述函数之前也没有订单 ID
    • Thnx Rahman 为您解释。我的问题是如何调用此函数:将其放在何处以及在没有订单 ID 时如何调用它。我正在使用一个单独的文件 (notification.php) 来连接支付提供商
    • 您可以将该代码放在您的活动主题functions.php 文件下。对代码进行必要的更改。
    • 下单后可以查看这篇文章来设置重定向。 xadapter.com/…
    【解决方案3】:

    如何创建自定义支付网关? 您是否创建了扩展 WC_Payment_Gateway 的类, 你不需要直接调用process_payment()函数。

    您只需要创建扩展WC_Payment_Gateway 的类并将该函数添加到您的类中,它将自动从结帐过程中调用 见woocommerce/includes/class-wc-checkout.php线777

    process_payment() 函数应该返回一个带有键 resultsredirect_url 的数组

    示例:

    public function process_payment( $order_id ) {
        $order = wc_get_order( $order_id );
    
        // Set order status
        $order->update_status( 'processing', __( 'Payment created from custom gateway' ) );
    
        // Reduce stock levels
        wc_reduce_stock_levels( $order_id );
    
        // Remove cart
        WC()->cart->empty_cart();
    
        // Return thankyou redirect
        return array(
            'result'    => 'success',
            'redirect'  => $this->get_return_url( $order ),
        );
    }
    

    【讨论】:

    • 是的,我创建了一个扩展 'WC_Payment_Gateway' 的类(使用代码查看答案。它包含插件的所有代码)。问题是如何在结账页面提交表单后开始创建订单。付款完成后,我们将在文件notification.php中更改订单状态
    • @IhebSaad 抱歉,我不确定你想要什么。您的意思是在处理订单之前您需要与其他网站(支付提供商)沟通,如果您从支付提供商那里获得成功响应,那么应该创建/处理订单?
    • 没错!我想在结帐页面提交表单后创建订单,并在付款完成后更改订单状态(已完成)。
    • 您不应该在结帐页面上提交您的自定义表单。您可以通过自定义类上的方法validate_fields() 验证它并返回bool(true 或false),或者在挂钩woocommerce_checkout_process 上检查它,您可以在class-wc-checkout.php 文件https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-checkout.php 上查看结帐过程的代码
    【解决方案4】:

    我有一个使用文件 custom payment.php 创建的插件 包含与支付提供商联系的表单:

    /*
    Plugin Name: Clic To Pay Payment Gateway
    Description: Custom payment gateway example
    Author:  
    Author URI: 
    */
    
    if ( ! defined( 'ABSPATH' ) ) {
        exit; // Exit if accessed directly
    }
    
    /**
     * Custom Payment Gateway.
     *
     * Provides a Custom Payment Gateway, mainly for testing purposes.
     */
    add_action('plugins_loaded', 'init_custom_gateway_class');
    function init_custom_gateway_class(){
    
        class WC_Gateway_Custom extends WC_Payment_Gateway {
    
            public $domain;
    
            /**
             * Constructor for the gateway.
             */
            public function __construct() {
    
                $this->domain = 'custom_payment';
    
                $this->id                 = 'ClictoPay';
                $this->icon               = apply_filters('woocommerce_custom_gateway_icon', '');
                $this->has_fields         = false;
                $this->method_title       = __( 'ClictoPay', $this->domain );
                $this->method_description = __( 'Allows payments with custom gateway.', $this->domain );
    
                // Load the settings.
                $this->init_form_fields();
                $this->init_settings();
    
                // Define user set variables
                $this->title        = $this->get_option( 'title' );
                $this->description  = $this->get_option( 'description' );
                $this->instructions = $this->get_option( 'instructions', $this->description );
                $this->order_status = $this->get_option( 'order_status', 'completed' );
    
                // Actions
                add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
                add_action( 'woocommerce_thankyou_custom', array( $this, 'thankyou_page' ) );
    
                // Customer Emails
                add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
            }
    
            /**
             * Initialise Gateway Settings Form Fields.
             */
            public function init_form_fields() {
    
                $this->form_fields = array(
                    'enabled' => array(
                        'title'   => __( 'Enable/Disable', $this->domain ),
                        'type'    => 'checkbox',
                        'label'   => __( 'Enable Clic To Pay Payment', $this->domain ),
                        'default' => 'yes'
                    ),
                    'title' => array(
                        'title'       => __( 'Title', $this->domain ),
                        'type'        => 'text',
                        'description' => __( 'This controls the title which the user sees during checkout.', $this->domain ),
                       // 'default'     => __( 'Clic to pay Payment', $this->domain ),
                        'desc_tip'    => false,
                    ),
                    'order_status' => array(
                        'title'       => __( 'Order Status', $this->domain ),
                        'type'        => 'select',
                        'class'       => 'wc-enhanced-select',
                        'description' => __( 'Choose whether status you wish after checkout.', $this->domain ),
                        'default'     => 'wc-completed',
                        'desc_tip'    => true,
                        'options'     => wc_get_order_statuses()
                    ),
                    'description' => array(
                        'title'       => __( 'Description', $this->domain ),
                        'type'        => 'textarea',
                        'description' => __( 'Payment method description that the customer will see on your checkout.', $this->domain ),
                        'default'     => __('Payment Information', $this->domain),
                        'desc_tip'    => true,
                    ),
                    'instructions' => array(
                        'title'       => __( 'Instructions', $this->domain ),
                        'type'        => 'textarea',
                        'description' => __( 'Instructions that will be added to the thank you page and emails.', $this->domain ),
                        'default'     => '',
                        'desc_tip'    => true,
                    ),
                );
            }
    
            /**
             * Output for the order received page.
             */
            public function thankyou_page() {
                if ( $this->instructions )
                    echo wpautop( wptexturize( $this->instructions ) );
            }
    
            /**
             * Add content to the WC emails.
             *
             * @access public
             * @param WC_Order $order
             * @param bool $sent_to_admin
             * @param bool $plain_text
             */
            public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
                if ( $this->instructions && ! $sent_to_admin && 'custom' === $order->payment_method && $order->has_status( 'on-hold' ) ) {
                    echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
                }
            }
    
            public function payment_fields(){
    
                if ( $description = $this->get_description() ) {
                  //  echo wpautop( wptexturize( $description ) );
                }
    
    
               ?>
    
     <form action="https://clictopay.monetiquetunisie.com/clicktopay/" method="post" name="form">
    
    <?php $loguserid = session_id();
     /***/
    global $woocommerce,$amount ,$connectdb ;
    
    // se connecter  la base
     $connectdb=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE)or die("error 01");
    $amount =number_format (  $woocommerce->cart->total, 3 , ',' ,'');
    /**/
    /*  $order = wc_get_order( $order_id );       ,  etat='".$order_id."'    */
    
    $querye=mysqli_query($connectdb," Update nauto  set amount='".$amount."',  session='".$loguserid ."'  ")or die(mysqli_error .' erreur');
    
    
    
    /***/           
    $refc='cd'.date('ymdHis');
    
    //$amount =number_format (  $woocommerce->cart->total, 3 , ',' ,'');
    
     echo      '<input type="hidden" name="sid" value="'.$loguserid.'">   
                <input name="Reference" type="hidden" value="'.$refc.'"> 
                <input name="Montant" type="hidden" value='.$amount.' >     '; ?>
                            <input name="Devise" type="hidden" value="TND" />
                            <input type="hidden" name="affilie" value="0870172012">
                <input type="hidden" name="lg" value="en">
    
                <table border="0">
                <tr><td  ><input style="margin-right:105px;  border: none;
      background: no-repeat url('https://saharagift.com/wp-content/uploads/2017/05/payyy.png') 0 0;width:250px;height:46px;
    
    
    " name="Submit"   type="submit" value=""  id="clictop"  onmouseover='if ( (document.getElementById("billing_first_name").value.length <2) || (document.getElementById("billing_last_name_field").value.length <2) || (document.getElementById("billing_email").value.length <5) || (document.getElementById("billing_address_1").value.length <5) || (document.getElementById("billing_city").value.length <2) || (document.getElementById("billing_postcode").value.length <2) || ( ! document.getElementById("billing_email").value.includes("@")) || ( ! document.getElementById("billing_email").value.includes(".")) )
    {alert("Please check billing details !");
    document.getElementById("clictop").disabled = true;
    }
    else{
    document.getElementById("clictop").disabled = false;
    }'  /></td></tr>
                <tr><td><img style="float:left;margin-left:10px;" src="https://saharagift.com/wp-content/uploads/2017/05/pmm.png"  /></td></tr>
    </table>
                </form>
                 <?php
            }
    
            /**
             * Process the payment and return the result.
             *
             * @param int $order_id
             * @return array
             */
            public function process_payment( $order_id ) {
    
                $order = wc_get_order( $order_id );
    
                $status = 'wc-' === substr( $this->order_status, 0, 3 ) ? substr( $this->order_status, 3 ) : $this->order_status;
    
                // Set order status
                $order->update_status( $status, __( 'Checkout with custom payment. ', $this->domain ) );
    
                // Reduce stock levels
                $order->reduce_order_stock();
    
                // Remove cart
                WC()->cart->empty_cart();
    
                // Return thankyou redirect
                return array(
                    'result'    => 'success',
                    'redirect'  => $this->get_return_url( $order )
                );
            }
        }
    }
    
    add_filter( 'woocommerce_payment_gateways', 'add_custom_gateway_class' );
    function add_custom_gateway_class( $methods ) {
        $methods[] = 'WC_Gateway_Custom'; 
        return $methods;
    }
    
    add_action('woocommerce_checkout_process', 'process_custom_payment');
    function process_custom_payment(){
    
        if($_POST['payment_method'] != 'custom')
            return;
    
        if( !isset($_POST['mobile']) || empty($_POST['mobile']) )
            wc_add_notice( __( 'Please add your mobile number', $this->domain ), 'error' );
    
    
        if( !isset($_POST['transaction']) || empty($_POST['transaction']) )
            wc_add_notice( __( 'Please add your transaction ID', $this->domain ), 'error' );
    
    }
    
    /**
     * Update the order meta with field value
     */
    add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta' );
    function custom_payment_update_order_meta( $order_id ) {
    
        if($_POST['payment_method'] != 'custom')
            return;
    
        // echo "<pre>";
        // print_r($_POST);
        // echo "</pre>";
        // exit();
    
      ///  update_post_meta( $order_id, 'mobile', $_POST['mobile'] );
      ///  update_post_meta( $order_id, 'transaction', $_POST['transaction'] );
    }
    
    /**
     * Display field value on the order edit page
     */
    add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_checkout_field_display_admin_order_meta', 10, 1 );
    function custom_checkout_field_display_admin_order_meta($order){
        $method = get_post_meta( $order->id, '_payment_method', true );
        if($method != 'custom')
            return;
    
      /*  $mobile = get_post_meta( $order->id, 'mobile', true );
        $transaction = get_post_meta( $order->id, 'transaction', true );
    
        echo '<p><strong>'.__( 'Mobile Number' ).':</strong> ' . $mobile . '</p>';
        echo '<p><strong>'.__( 'Transaction ID').':</strong> ' . $transaction . '</p>';*/
    }
    
    
    
    
    ?>
    

    支付提供商与文件 notfication.php 通信(在成功支付的情况下,anwser 详细信息而不是答案一致):

    <?
    $ref = $_GET['Reference'];
    $act = $_GET['Action'];
    $par = $_GET['Param'];
    define("DB_HOST", "****");
    define("DB_USER", "****");
    define("DB_PASSWORD", "****");
    define("DB_DATABASE", "****");
    // se connecter  la base
    include '/wp-content/plugins/woocommerce/woocommerce.php';
    include '/wp-content/plugins/CustomPayment.php';
    global $connectdb, $woocommerce,$amount;
    $connectdb=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE)or die("error 01");
    $loguserid = session_id();
    /* */
    $query=mysqli_query ($connectdb,"SELECT * FROM nauto  ;");
    
    /** recupertaion  amount*/
    while($col = mysqli_fetch_object($query)){ 
      $amount=$col->amount ;
    } 
    
    $querye=mysqli_query($connectdb," Update nauto  set amount='".$amount."' , ref='".$ref."'   ")or die(mysqli_error .' erreur');
    
    
    switch ($act) {
    case "DETAIL":
    // accéder à la base et récuperer le montant
    echo "Reference=".$ref. "&Action=".$act."&Reponse=".$amount;
    break;
    case "ERREUR":
    // accéder à la base et mettre à jour l’état de la transaction
    $queryerr=mysqli_query($connectdb," Update nauto  set num=".$par.", etat=".$act." ")or die(mysqli_error .' erreur');
    echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
    break;
    case "ACCORD":
    // accéder à la base, enregistrer le numéro d’autorisation (dans param)
    $query=mysqli_query($connectdb," INSERT INTO nauto  (num,ref,session,etat,amount) values (".$par.",".$ref.",".$loguserid.",".$etat.",".$amount.")" )or die(mysqli_error .' here');
    
    echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
    ///echo "Reference=".$ref. "Action=".$act. "Reponse=ANNULATION"."Param=".$par;
    
    break;
    case "REFUS":
    // accéder à la base et mettre à jour l’état de la transaction
    $queryref=mysqli_query($connectdb," Update nauto  set num=".$par.", etat=".$act." ")or die(mysqli_error .' refus');
    echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
    break;
    case "ANNULATION":
    // accéder à la base et mettre à jour l’état de la transaction
    $queryann=mysqli_query($connectdb," Update nauto  set num=".$par.", etat=".$act." ")or die(mysqli_error .' annulation');
    echo "Reference=".$ref. "&Action=".$act. "&Reponse=OK";
    break;
    }
    ?>
    

    收到付款后如何创建订单(notification.php 中的案例 ACCORD)???

    【讨论】:

      【解决方案5】:

      如果您的用户尝试付款但失败,您可能需要检查 $order_id = WC()->session->get( 'order_awaiting_payment' );

      【讨论】:

        猜你喜欢
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 2017-10-13
        • 2016-11-27
        • 2015-02-21
        相关资源
        最近更新 更多