如何在woocommerce支付网关类的payment_fields()中获取订单ID

时间:2017-05-11 09:15:09

标签: php wordpress woocommerce payment-gateway

我正在为woocommerce开发一个自定义支付网关,支付网关需要在处理付款之前进行注册,并且需要提交表单以重定向到网关的付款页面,用户将在其中提供他的卡详细信息。

需要使用表单提交重定向,因为必须传递我在注册调用中获得的事务ID和URL:

以下是我的支付网关的实际流程:

1-注册电话(必须通过orderID,金额,ReturnURL) 我在payment_fields()函数中这样做,而不是将返回值放在隐藏的表单中。 2-重定向调用(必须以PortalURL为我的表单操作且TransactionID为隐藏字段的形式传递TransactionID,PortalURL)

这是我的支付网关类:

           <?php
           $conn=mysqli_connect("localhost","root","pass","data");       

            if (mysqli_connect_errno())                
              {
              echo "Failed to connect to MySQL: " . mysqli_connect_error();
              }
             $name='அடகு';
            //To get the Main json
            $sql="SELECT * FROM mytab where value='$name' ";

            $r = mysqli_query($conn,$sql);
                    $data = array();

                    while($row = mysqli_fetch_assoc($r)) {
                      $data[] = $row;
                    }
            $nestedArray = array();
            foreach($data as $itemData){

              $nestedArrayItem['id'] = $itemData['id'];
                $nestedArrayItem['name'] = $itemData['name'];
                $nestedArrayItem['parent'] = $itemData['parent'];
              $nestedArrayItem['tooltip'] = $itemData['tooltip'];
                 $nestedArrayItem['color'] = $itemData['color'];
            $nestedArrayItem['children'] = array();
            insertIntoNestedArrayyy($nestedArray, $nestedArrayItem);
            }
            header('Content-Type: application/json');
                $jj=(array_remove_empty($nestedArray));
            $json=json_encode($jj,JSON_UNESCAPED_UNICODE);

            echo "MAIN json:"."\n". $json;      

         echo "\n";
          echo "CHILD AND SUBCHILD JSON:"."\n";
            foreach($nestedArray as $r){
          foreach($r['children'] as $k){
          $w= $k['name'];
            //To get the subchild
         $sq="SELECT * FROM mytab where value='$w' ";
           $rr = mysqli_query($conn,$sq);
                    $dataa = array();

                    while($roww = mysqli_fetch_assoc($rr)) {
                      $dataa[] = $roww;
                    }

              $nestedArray = array();
            foreach($dataa as $itemData){
              $nestedArrayItem['id'] = $itemData['id'];
                $nestedArrayItem['name'] = $itemData['name'];
                $nestedArrayItem['parent'] = $itemData['parent'];
              $nestedArrayItem['tooltip'] = $itemData['tooltip'];
                 $nestedArrayItem['color'] = $itemData['color'];
                $nestedArrayItem['children'] = array();
                insertIntoNestedArrayyy($nestedArray, $nestedArrayItem);
             }
        $nestedArray=(array_remove_empty($nestedArray));
                    $c1= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
             $c1 = substr($c1, 1, -1);
           // $c1=str_replace("[]"," ",$c1);

           echo $c1;

            foreach($nestedArray as $r){
        foreach($r['children'] as $k){
        $w= $k['name'];
        //To get the sub-subchild
        $sql="SELECT * FROM mytab where value='$w' ";
                    $rr = mysqli_query($conn,$sql);
                    $dataa = array();

                    while($roww = mysqli_fetch_assoc($rr)) {
                        if($roww >0){
                      $dataa[] = $roww;
                }}

               $nestedArray = array();
            foreach($dataa as $itemData){
              $nestedArrayItem['id'] = $itemData['id'];
                $nestedArrayItem['name'] = $itemData['name'];
                $nestedArrayItem['parent'] = $itemData['parent'];
              $nestedArrayItem['tooltip'] = $itemData['tooltip'];
                 $nestedArrayItem['color'] = $itemData['color'];
                $nestedArrayItem['children'] = array();
                insertIntoNestedArrayyy($nestedArray, $nestedArrayItem);
              }
        $nestedArray=(array_remove_empty($nestedArray));
                    $c2= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
                    $c2=str_replace("[]"," ",$c2);

            echo $c2."\n";
              }


                 }

         }
          }
          function buildtt($src_arr, $parent_id = 0, $tree = array())
            {
                foreach($src_arr as $idx => $roww)
                {
                    if($roww['parent'] == $parent_id)
                    {
                        foreach($roww as $k => $v)
                            $tree[$roww['id']][$k] = $v;
                        unset($src_arr[$idx]);
            $tree[$roww['id']]['children'] = buildtt($src_arr, $roww['id']);
                    }
                }
                ksort($tree);
                return $tree;
            }
             function array_remove_empty($haystack)
            {
                foreach ($haystack as $key => $value) {
                    if (is_array($value)) {
                    $haystack[$key] = array_remove_empty($haystack[$key]);
                    }

                    if (empty($haystack[$key])) {
                        unset($haystack[$key]);
                    }
                }

                return $haystack;
            }
            function insertIntoNestedArrayyy(&$array, $searchItem){

                if($searchItem['parent'] == 0){
                    array_push($array, $searchItem);
                    return;
                }
                if(empty($array)){ return; }
             array_walk($array, function(&$item, $key, $searchItem){
                if($item['id'] == $searchItem['parent']){
                        array_push($item['children'], $searchItem);
                        return;
                    }
                    insertIntoNestedArrayyy($item['children'], $searchItem);
            }, $searchItem);
            }
            ?>

现在我的问题是,我在payment_fields()函数中需要OrderID,OrderTotal和get_return_url()。

我已经完成了以下所有方法,但没有一个适合我。

<?php

    class WC_Etisalat_Payment_Gateway extends WC_Payment_Gateway {

        public function __construct(){

            $this->id = 'epg';
            $this->icon = '';
            $this->has_fields = false;
            $this->method_title = 'Etisalat Payment Gateway';
            $this->method_description = 'Pay with your UAE Credit, Debit or Prepaid cards.';
            $this->supports           = array(
                'products',
                'refunds',
            );

            $this->init_form_fields();
            $this->init_settings();

            $this->enabled = $this->get_option('enabled');
            $this->title = $this->get_option('title');
            $this->description = $this->get_option('description');

            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );

            add_action( 'admin_notices', array( $this,  'do_ssl_check' ) );

        }

        public function do_ssl_check() {
            if( $this->enabled == "yes" ) {
                if( get_option( 'woocommerce_force_ssl_checkout' ) == "no" ) {
                    echo "<div class=\"error\"><p>". sprintf( __( "<strong>%s</strong> is enabled and WooCommerce is not forcing the SSL certificate on your checkout page. Please ensure that you have a valid SSL certificate and that you are <a href=\"%s\">forcing the checkout pages to be secured.</a>" ), $this->method_title, admin_url( 'admin.php?page=wc-settings&tab=checkout' ) ) ."</p></div>";
                }
            }
        }

        public function init_form_fields() {
            $this->form_fields = array(
                'enabled' => array(
                    'title'   => 'Enable/Disable',
                    'type'    => 'checkbox',
                    'label'   => 'Enable Etisalat Payment Gateway',
                    'default' => ''
                ),
                'title' => array(
                    'title'       => 'Title',
                    'type'        => 'text',
                    'description' => 'This controls the title for the payment method the customer sees during checkout.',
                    'default'     => 'Etisalat Payment Gateway'
                ),
                'description' => array(
                    'title'       => 'Description',
                    'type'        => 'textarea',
                    'description' => 'Payment method description that the customer will see on your checkout.',
                    'default'     => 'Pay with your UAE Credit, Debit or Prepaid cards.'
                ),
                'epg_merchant_id' => array(
                    'title'     => 'EPG Merchant ID',
                    'type'      => 'text'
                ),
                'epg_merchant_password' => array(
                    'title'     => 'EPG Password',
                    'type'      => 'password'
                )
            );
        }

        public function admin_options() {
            ?>

            <h2>Etisalat Payment Gateway</h2>

            <table class="form-table">

                <?php $this->generate_settings_html(); ?>

            </table>

            <?php
        }

        public function init_epg_register( $order_id, $amount, $return_url ) {

            $cert = plugin_dir_path( __FILE__ )."cert.pem";

            $opts = array(
                'ssl' => array(
                    'verify_peer'       => false,
                    'verify_peer_name'  => false,
                )
            );
            $options = array(
                'trace'         => 1,
                'keep_alive'    => true,
                'exceptions'    => 0,
                'local_cert'    => $cert,
                'passphrase'    => $this->get_option('epg_merchant_password'),
                'stream_context' => stream_context_create($opts),
                'cache_wsdl'    => WSDL_CACHE_NONE
            );
            $client = new SoapClient("https://demo-ipg.comtrust.ae:2443/MerchantAPI.svc?singleWsdl", $options);

            $params = array(
                'Register' => '',
                'request' => array(
                    'Customer'      => $this->get_option('epg_merchant_id'),
                    'Language'      => 'en',
                    'version'       => 2,
                    'Amount'        => $amount,
                    'Currency'      => 'USD',
                    'OrderID'       => $order_id,
                    'OrderInfo'     => $order_id,
                    'OrderName'     => $order_id,
                    'ReturnPath'    => $return_url,
                    'TransactionHint' => 'VCC:Y'
                )
            );

            $result = $client->Register($params);

            $response = json_encode( $result );

            $decode_data = json_decode($response);
            $reg_result = $decode_data->RegisterResult;

            return $reg_result;

        }

        public function process_payment( $order_id ) {

            global $woocommerce;

            $order = wc_get_order( $order_id );

            $order->update_status( 'on-hold', __( 'Awaiting offline payment', 'wc-gateway-offline' ) );

            $order->reduce_order_stock();

            $woocommerce->cart->empty_cart();

            return array(
                'result'    => 'success'
            );

        }

        public function payment_fields(){

            global $woocommerce;

            $order_id = $woocommerce->session->order_awaiting_payment;

            $order = wc_get_order( $order_id );

            $register = $this->init_epg_register( $order_id, $woocommerce->cart->total, $this->get_return_url( $order ) );

            $environment_url = $register->PaymentPortal;

            $transaction_id = $register->TransactionID;

            if ( $description = $this->get_description() ) {
                echo wpautop( wptexturize( $description ) );
            }

            ?>
            <form id="epg_payment_call" action="<?php echo esc_url( $environment_url ); ?>" method="post">
                <!--<input type='hidden' name='Price' value='<?php echo esc_attr( $woocommerce->cart->total ); ?>'/>
                <input type='hidden' name='ReturnURL' value='<?php echo esc_attr( $this->get_return_url( $order ) ); ?>'/>-->
                <input type='hidden' name='TransactionID' value='<?php echo esc_attr( $transaction_id ); ?>'/>
                <input type="submit" value="Place Order">
            </form>
            <?php
        }

    }

不工作:

global $wp;
    $order_id = $wp->query_vars['order-pay'];
    $order = new WC_Order( $order_id );

不工作:

get_query_var('order-pay');

任何人都可以帮我分类这个。因为我被困在这里。阅读woocommerce的所有文档并搜索堆栈溢出很多,但没有一个对我有用。

我正在使用最新版本的WooCommerce和WP。

3 个答案:

答案 0 :(得分:1)

我正在寻找类似的东西,但我担心你无法实现这一点,这是process_checkout方法的生命周期:

https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#895

如你所见@ line 928

$order_id = $this->create_order( $posted_data ); 

订单是在您即将付款时创建的,您之前无法获得订单。

答案 1 :(得分:1)

你不能像上一篇文章那样获得$ order_id,但你可以通过执行以下操作来检索payment_fields()函数中购物车的货币和价值:

$currency = get_woocommerce_currency();
$value = max( 0, apply_filters( 'woocommerce_calculated_total', round( WC()->cart->cart_contents_total + WC()->cart->fee_total + WC()->cart->tax_total, WC()->cart->dp ), WC()->cart ) );

希望这有帮助

答案 2 :(得分:0)

我已经使用以下代码实现了它。

global $woocommerce;
$ordID = $woocommerce->session->order_awaiting_payment;