Advertisement
rejuancse

2checkout-init

Sep 19th, 2018
594
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 19.24 KB | None | 0 0
  1. <?php
  2.  
  3. if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
  4.  
  5.  
  6.  
  7.  
  8. /* Add a custom payment class to WC
  9.   ------------------------------------------------------------ */
  10. add_action('plugins_loaded', 'woocommerce_twocheckout', 0);
  11.  
  12. function woocommerce_twocheckout(){
  13.     if (!class_exists('WC_Payment_Gateway'))
  14.         return; // if the WC payment gateway class is not available, do nothing
  15.     if(class_exists('WC_Gateway_Twocheckout'))
  16.         return;
  17.  
  18.     class WC_Gateway_Twocheckout extends WC_Payment_Gateway{
  19.  
  20.         // Logging
  21.         public static $log_enabled = false;
  22.         public static $log = false;
  23.  
  24.         public function __construct(){
  25.  
  26.             global $woocommerce;
  27.  
  28.             $plugin_dir             = plugin_dir_url(__FILE__);
  29.             $this->id               = 'twocheckout';
  30.             $this->icon             = apply_filters('woocommerce_twocheckout_icon', $this->get_option('icons') );
  31.             $this->has_fields       = true;
  32.             $this->method_title     = '2Checkout';
  33.  
  34.             $this->init_form_fields();
  35.             $this->init_settings();
  36.  
  37.             // Define user set variables
  38.             $this->title            = $this->get_option('title');
  39.             $this->seller_id        = $this->get_option('seller_id');
  40.             $this->description      = $this->get_option('description');
  41.             $this->sandbox          = $this->get_option('sandbox');
  42.             $this->debug            = $this->get_option('debug');
  43.             $this->publishable_key  = $this->get_option('publishable_key');
  44.             $this->private_key      = $this->get_option('private_key');
  45.  
  46.             self::$log_enabled      = $this->debug;
  47.  
  48.             add_action( 'woocommerce_receipt_' . $this->id, array($this, 'receipt_page') );
  49.             add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
  50.             add_action( 'woocommerce_api_wc_' . $this->id, array($this, 'check_ipn_response') );
  51.  
  52.  
  53.             if (!$this->is_valid_for_use()){
  54.                 $this->enabled = false;
  55.             }
  56.         }
  57.  
  58.         /**
  59.         * Logging method
  60.         * @param  string $message
  61.         */
  62.         public static function log( $message ) {
  63.             if ( self::$log_enabled ) {
  64.                 if ( empty( self::$log ) ) {
  65.                     self::$log = new WC_Logger();
  66.                 }
  67.                 self::$log->add( 'twocheckout', $message );
  68.             }
  69.         }
  70.  
  71.         /**
  72.          * Check if this gateway is enabled and available in the user's country
  73.          *
  74.          * @access public
  75.          * @return bool
  76.          */
  77.         function is_valid_for_use() {
  78.           $supported_currencies = array(
  79.             'AFN', 'ALL', 'DZD', 'ARS', 'AUD', 'AZN', 'BSD', 'BDT', 'BBD','BZD', 'BMD', 'BOB', 'BWP', 'BRL', 'GBP', 'BND', 'BGN', 'CAD',
  80.             'CLP', 'CNY', 'COP', 'CRC', 'HRK', 'CZK', 'DKK', 'DOP', 'XCD','EGP', 'EUR', 'FJD', 'GTQ', 'HKD', 'HNL', 'HUF', 'INR', 'IDR',
  81.             'ILS', 'JMD', 'JPY', 'KZT', 'KES', 'LAK', 'MMK', 'LBP', 'LRD','MOP', 'MYR', 'MVR', 'MRO', 'MUR', 'MXN', 'MAD', 'NPR', 'TWD',
  82.             'NZD', 'NIO', 'NOK', 'PKR', 'PGK', 'PEN', 'PHP', 'PLN', 'QAR','RON', 'RUB', 'WST', 'SAR', 'SCR', 'SGF', 'SBD', 'ZAR', 'KRW',
  83.             'LKR', 'SEK', 'CHF', 'SYP', 'THB', 'TOP', 'TTD', 'TRY', 'UAH','AED', 'USD', 'VUV', 'VND', 'XOF', 'YER');
  84.  
  85.             if ( ! in_array( get_woocommerce_currency(), apply_filters( 'woocommerce_twocheckout_supported_currencies', $supported_currencies ) ) ) return false;
  86.  
  87.             return true;
  88.         }
  89.  
  90.         /**
  91.          * Admin Panel Options
  92.          * - Options for bits like 'title' and availability on a country-by-country basis
  93.          *
  94.          * @since 1.0.0
  95.          */
  96.         public function admin_options() {
  97.             ?>
  98.             <h3><?php _e( '2Checkout', 'wp-crowdfunding' ); ?></h3>
  99.             <p><?php _e( '2Checkout - Credit Card/Paypal', 'wp-crowdfunding' ); ?></p>
  100.  
  101.             <?php if ( $this->is_valid_for_use() ) : ?>
  102.                 <table class="form-table">
  103.                     <?php
  104.                     // Generate the HTML For the settings form.
  105.                     $this->generate_settings_html();
  106.                     ?>
  107.                 </table><!--/.form-table-->
  108.             <?php else : ?>
  109.                 <div class="inline error"><p><strong><?php _e( 'Gateway Disabled', 'wp-crowdfunding' ); ?></strong>: <?php _e( '2Checkout does not support your store currency.', 'wp-crowdfunding' ); ?></p></div>
  110.             <?php
  111.             endif;
  112.         }
  113.  
  114.  
  115.         /**
  116.          * Initialise Gateway Settings Form Fields
  117.          *
  118.          * @access public
  119.          * @return void
  120.          */
  121.         function init_form_fields() {
  122.  
  123.             $this->form_fields = array(
  124.                 'enabled' => array(
  125.                     'title'         => __( 'Enable/Disable', 'wp-crowdfunding' ),
  126.                     'type'          => 'checkbox',
  127.                     'label'         => __( 'Enable 2Checkout', 'wp-crowdfunding' ),
  128.                     'default'       => 'yes'
  129.                 ),
  130.                 'title' => array(
  131.                     'title'         => __( 'Title', 'wp-crowdfunding' ),
  132.                     'type'          => 'text',
  133.                     'description'   => __( 'This controls the title which the user sees during checkout.', 'wp-crowdfunding' ),
  134.                     'default'       => __( 'Credit Card/PayPal', 'wp-crowdfunding' ),
  135.                     'desc_tip'      => true,
  136.                 ),
  137.                 'description' => array(
  138.                     'title'         => __( 'Description', 'wp-crowdfunding' ),
  139.                     'type'          => 'textarea',
  140.                     'description'   => __( 'This controls the description which the user sees during checkout.', 'wp-crowdfunding' ),
  141.                     'default'       => __( 'Pay with Credit Card/PayPal', 'wp-crowdfunding' )
  142.                 ),
  143.                 'icons' => array(
  144.                     'title'         => __( 'Icon URL', 'wp-crowdfunding' ),
  145.                     'type'          => 'text',
  146.                     'description'   => __( 'This controls the Icon URL which the user sees during checkout.', 'wp-crowdfunding' ),
  147.                     'default'       => '',
  148.                     'desc_tip'      => true,
  149.                 ),
  150.                 'seller_id' => array(
  151.                     'title'         => __( 'Seller ID', 'wp-crowdfunding' ),
  152.                     'type'          => 'text',
  153.                     'description'   => __( 'Please enter your 2Checkout account number; this is needed in order to take payment.', 'wp-crowdfunding' ),
  154.                     'default'       => '',
  155.                     'desc_tip'      => true,
  156.                     'placeholder'   => ''
  157.                 ),
  158.                 'publishable_key' => array(
  159.                     'title'         => __( 'Publishable Key', 'wp-crowdfunding' ),
  160.                     'type'          => 'text',
  161.                     'description'   => __( 'Please enter your 2Checkout Publishable Key; this is needed in order to take payment.', 'wp-crowdfunding' ),
  162.                     'default'       => '',
  163.                     'desc_tip'      => true,
  164.                     'placeholder'   => ''
  165.                 ),
  166.                 'private_key' => array(
  167.                     'title'         => __( 'Private Key', 'wp-crowdfunding' ),
  168.                     'type'          => 'text',
  169.                     'description'   => __( 'Please enter your 2Checkout Private Key; this is needed in order to take payment.', 'wp-crowdfunding' ),
  170.                     'default'       => '',
  171.                     'desc_tip'      => true,
  172.                     'placeholder'   => ''
  173.                 ),
  174.                 'sandbox' => array(
  175.                     'title'         => __( 'Sandbox/Production', 'wp-crowdfunding' ),
  176.                     'type'          => 'checkbox',
  177.                     'label'         => __( 'Use 2Checkout Sandbox', 'wp-crowdfunding' ),
  178.                     'default'       => 'no'
  179.                 ),
  180.                 'debug' => array(
  181.                     'title'         => __( 'Debug Log', 'wp-crowdfunding' ),
  182.                     'type'          => 'checkbox',
  183.                     'label'         => __( 'Enable logging', 'wp-crowdfunding' ),
  184.                     'default'       => 'no',
  185.                     'description'   => sprintf( __( 'Log 2Checkout events', 'wp-crowdfunding' ), wc_get_log_file_path( 'twocheckout' ) )
  186.                 ),
  187.  
  188.  
  189.  
  190.             );
  191.  
  192.         }
  193.  
  194.  
  195.  
  196.         /**
  197.          * Generate the credit card payment form
  198.          *
  199.          * @access public
  200.          * @param none
  201.          * @return string
  202.          */
  203.         function payment_fields() {
  204.  
  205.               $plugin_dir = plugin_dir_url(__FILE__);
  206.               // Description of payment method from settings
  207.               if ($this->description) { ?>
  208.                   <p><?php
  209.                   echo $this->description; ?>
  210.                   </p><?php
  211.               } ?>
  212.  
  213.               <ul class="woocommerce-error" style="display:none" id="twocheckout_error_creditcard">
  214.               <li>Credit Card details are incorrect, please try again.</li>
  215.               </ul>
  216.  
  217.               <fieldset>
  218.  
  219.               <input id="sellerId" type="hidden" maxlength="16" width="20" value="<?php echo $this->seller_id ?>">
  220.               <input id="publishableKey" type="hidden" width="20" value="<?php echo $this->publishable_key ?>">
  221.               <input id="token" name="token" type="hidden" value="">
  222.  
  223.               <!-- Credit card number -->
  224.               <p class="form-row form-row-first">
  225.                   <label for="ccNo"><?php echo __( 'Credit Card number', 'wp-crowdfunding' ) ?> <span class="required">*</span></label>
  226.                   <input type="text" class="input-text" id="ccNo" autocomplete="off" value="" />
  227.  
  228.               </p>
  229.  
  230.               <div class="clear"></div>
  231.  
  232.               <!-- Credit card expiration -->
  233.               <p class="form-row form-row-first">
  234.                   <label for="cc-expire-month"><?php echo __( 'Expiration date', 'wp-crowdfunding') ?> <span class="required">*</span></label>
  235.                   <select id="expMonth" class="woocommerce-select woocommerce-cc-month">
  236.                       <option value=""><?php _e( 'Month', 'wp-crowdfunding' ) ?></option><?php
  237.                       $months = array();
  238.                       for ( $i = 1; $i <= 12; $i ++ ) {
  239.                           $timestamp = mktime( 0, 0, 0, $i, 1 );
  240.                           $months[ date( 'n', $timestamp ) ] = date( 'F', $timestamp );
  241.                       }
  242.                       foreach ( $months as $num => $name ) {
  243.                           printf( '<option value="%02d">%s</option>', $num, $name );
  244.                       } ?>
  245.                   </select>
  246.                   <select id="expYear" class="woocommerce-select woocommerce-cc-year">
  247.                       <option value=""><?php _e( 'Year', 'wp-crowdfunding' ) ?></option>
  248.                       <?php
  249.                       $years = array();
  250.                       for ( $i = date( 'y' ); $i <= date( 'y' ) + 15; $i ++ ) {
  251.                           printf( '<option value="20%u">20%u</option>', $i, $i );
  252.                       }
  253.                       ?>
  254.                   </select>
  255.               </p>
  256.               <div class="clear"></div>
  257.  
  258.               <!-- Credit card security code -->
  259.               <p class="form-row">
  260.               <label for="cvv"><?php _e( 'Card security code', 'wp-crowdfunding' ) ?> <span class="required">*</span></label>
  261.               <input type="text" class="input-text" id="cvv" autocomplete="off" maxlength="4" style="width:55px" />
  262.               <span class="help"><?php _e( '3 or 4 digits usually found on the signature strip.', 'wp-crowdfunding' ) ?></span>
  263.               </p>
  264.  
  265.               <div class="clear"></div>
  266.  
  267.               </fieldset>
  268.  
  269.              <script type="text/javascript">
  270.                   var formName = "order_review";
  271.                   var myForm = document.getElementsByName('checkout')[0];
  272.                   if(myForm) {
  273.                       myForm.id = "tcoCCForm";
  274.                       formName = "tcoCCForm";
  275.                   }
  276.                   jQuery('#' + formName).on("click", function(){
  277.                       jQuery('#place_order').unbind('click');
  278.                       jQuery('#place_order').click(function(e) {
  279.                           e.preventDefault();
  280.                           retrieveToken();
  281.                       });
  282.                   });
  283.  
  284.                   function successCallback(data) {
  285.                       clearPaymentFields();
  286.                       jQuery('#token').val(data.response.token.token);
  287.                       jQuery('#place_order').unbind('click');
  288.                       jQuery('#place_order').click(function(e) {
  289.                           return true;
  290.                       });
  291.                       jQuery('#place_order').click();
  292.                   }
  293.  
  294.                   function errorCallback(data) {
  295.                       if (data.errorCode === 200) {
  296.                           TCO.requestToken(successCallback, errorCallback, formName);
  297.                       } else if(data.errorCode == 401) {
  298.                           clearPaymentFields();
  299.                           jQuery('#place_order').click(function(e) {
  300.                               e.preventDefault();
  301.                               retrieveToken();
  302.                           });
  303.                           jQuery("#twocheckout_error_creditcard").show();
  304.  
  305.                       } else{
  306.                           clearPaymentFields();
  307.                           jQuery('#place_order').click(function(e) {
  308.                               e.preventDefault();
  309.                               retrieveToken();
  310.                           });
  311.                           alert(data.errorMsg);
  312.                       }
  313.                   }
  314.  
  315.                   var retrieveToken = function () {
  316.                       jQuery("#twocheckout_error_creditcard").hide();
  317.                       if (jQuery('div.payment_method_twocheckout:first').css('display') === 'block') {
  318.                           jQuery('#ccNo').val(jQuery('#ccNo').val().replace(/[^0-9\.]+/g,''));
  319.                           TCO.requestToken(successCallback, errorCallback, formName);
  320.                       } else {
  321.                           jQuery('#place_order').unbind('click');
  322.                           jQuery('#place_order').click(function(e) {
  323.                               return true;
  324.                           });
  325.                           jQuery('#place_order').click();
  326.                       }
  327.                   }
  328.  
  329.                   function clearPaymentFields() {
  330.                       jQuery('#ccNo').val('');
  331.                       jQuery('#cvv').val('');
  332.                       jQuery('#expMonth').val('');
  333.                       jQuery('#expYear').val('');
  334.                   }
  335.  
  336.               </script>
  337.  
  338.               <?php if ($this->sandbox == 'yes'): ?>
  339.                   <script type="text/javascript" src="https://sandbox.2checkout.com/checkout/api/script/publickey/<?php echo $this->seller_id ?>"></script>
  340.                   <script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
  341.               <?php else: ?>
  342.                   <script type="text/javascript" src="https://www.2checkout.com/checkout/api/script/publickey/<?php echo $this->seller_id ?>"></script>
  343.                   <script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
  344.               <?php endif ?>
  345.           <?php
  346.         }
  347.  
  348.  
  349.  
  350.  
  351.  
  352.         /**
  353.          * Process the payment and return the result
  354.          *
  355.          * @access public
  356.          * @param int $order_id
  357.          * @return array
  358.          */
  359.         function process_payment( $order_id ) {
  360.             global $woocommerce;
  361.  
  362.             $order = new WC_Order($order_id);
  363.  
  364.             if ( 'yes' == $this->debug )
  365.                 $this->log( 'Generating payment form for order ' . $order->get_order_number() . '. Notify URL: ' . $this->notify_url );
  366.  
  367.             // 2Checkout Args
  368.             $twocheckout_args = array(
  369.                                     'token'         => $_POST['token'],
  370.                                     'sellerId'      => $this->seller_id,
  371.                                     'currency' => get_woocommerce_currency(),
  372.                                     'total'         => $order->get_total(),
  373.  
  374.                                     // Order key
  375.                                     'merchantOrderId'    => $order->get_order_number(),
  376.  
  377.                                     // Billing Address info
  378.                                     "billingAddr" => array(
  379.                                         'name'          => $order->billing_first_name . ' ' . $order->billing_last_name,
  380.                                         'addrLine1'     => $order->billing_address_1,
  381.                                         'addrLine2'     => $order->billing_address_2,
  382.                                         'city'          => $order->billing_city,
  383.                                         'state'         => $order->billing_state,
  384.                                         'zipCode'       => $order->billing_postcode,
  385.                                         'country'       => $order->billing_country,
  386.                                         'email'         => $order->billing_email,
  387.                                         'phoneNumber'   => $order->billing_phone
  388.                                     )
  389.                                 );
  390.  
  391.             try {
  392.                 if ($this->sandbox == 'yes') {
  393.                     TwocheckoutApi::setCredentials($this->seller_id, $this->private_key, 'sandbox');
  394.                 } else {
  395.                     TwocheckoutApi::setCredentials($this->seller_id, $this->private_key);
  396.                 }
  397.                 update_option( 'anik', $twocheckout_args );
  398.                 $charge = Twocheckout_Charge::auth($twocheckout_args);
  399.                 if ($charge['response']['responseCode'] == 'APPROVED') {
  400.                     $order->payment_complete();
  401.                     return array(
  402.                         'result' => 'success',
  403.                         'redirect' => $this->get_return_url( $order )
  404.                     );
  405.                 }
  406.             } catch (Twocheckout_Error $e) {
  407.                 wc_add_notice($e->getMessage(), $notice_type = 'error' );
  408.                 return;
  409.             }
  410.  
  411.         }
  412.  
  413.  
  414.         /**
  415.          * Output for the order received page.
  416.          *
  417.          * @access public
  418.          * @return void
  419.          */
  420.         function receipt_page( $order ) {
  421.             echo '<p>'.__( 'Thank you for your order, please click the button below to pay with PayPal.', 'wp-crowdfunding' ).'</p>';
  422.             echo $this->generate_twocheckout_form( $order );
  423.         }
  424.  
  425.     }
  426.  
  427.  
  428.  
  429.  
  430.  
  431.  
  432.     include plugin_dir_path(__FILE__).'twocheckout/TwocheckoutApi.php';
  433.  
  434.     /**
  435.      * Add the gateway to WooCommerce
  436.      **/
  437.     function add_twocheckout_gateway($methods){
  438.         $methods[] = 'WC_Gateway_Twocheckout';
  439.         return $methods;
  440.     }
  441.  
  442.     add_filter('woocommerce_payment_gateways', 'add_twocheckout_gateway');
  443.  
  444. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement