Need Help Reviewing Woo-commerce Shipping Extension Script

I’d like your help reviewing a PHP WooCommerce extension script I wrote for custom rate calculation with the national postal service in my country.
I’m not quite sure if I’m making proper use of the returned JSON to calculate the rates and if I’m sending them to the front end the right way.
I will be much grateful if you could help.

Please see Code below:

<?php

if ( ! defined( 'WPINC' ) ) {
 
    die;
 
}

/**
 * Check if WooCommerce is active
 */
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

	function visitghana_shipping_method_init() {
		if ( ! class_exists( 'WC_Visit_Ghana_Shipping_Method' ) ) {
			class WC_Visit_Ghana_Shipping_Method extends WC_Shipping_Method {
				/**
				 * Constructor for your shipping class
				 *
				 * @access public
				 * @return void
				 */
				public function __construct( $instance_id = 0 ) {
					$this->id                 = 'visitghana_shipping'; // Id for your shipping method. Should be uunique.
					$this->instance_id 		  = absint( $instance_id );
					$this->method_title       = __( 'Visit Ghana Shipping Method', 'visitghana_shipping' );  // Title shown in admin
					$this->method_description = __( 'Description of Visit Ghana shipping method', 'visitghana_shipping' ); // Description shown in admin

					// Availability & Countries
					$this->availability = 'including';
					$this->countries = array(
					    'GH', // Ghana
					    'US', // Unites States of America
                        'CA', // Canada
                        'DE', // Germany
                        'GB', // United Kingdom
                        'IT',   // Italy
                        'ES', // Spain
                        'HR'  // Croatia
					    );

					/*$this->supports 		  = array(
							'',
							'',
						);*/

					$this->init();

					$this->enabled            =  isset( $this->settings['enabled'] ) ? $this->settings['enabled'] : 'yes'; // This can be added as an setting but for this example its forced enabled
					$this->title              = isset( $this->settings['title'] ) ? $this->settings['title'] : __( 'Visit Ghana Shipping Method', 'visitghana_shipping' ); // This can be added as an setting but for this example its forced.

					//$this->init();
				}

				/**
				 * Init your settings
				 *
				 * @access public
				 * @return void
				 */
				function init() {
					// Load the settings API
					$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
					$this->init_settings(); // This is part of the settings API. Loads settings you previously init.

					// Save settings in admin if you have any defined
					add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
				}

				 /**
                 * Define settings field for this shipping
                 * @return void 
                 */
                function init_form_fields() { 
 
                    // We will add our settings here
                    $this->form_fields = array(
                     
                             'enabled' => array(
                                  'title' => __( 'Enable', 'visitghana_shipping' ),
                                  'type' => 'checkbox',
                                  'description' => __( 'Enable this shipping.', 'visitghana_shipping' ),
                                  'default' => 'yes'
                                  ),
                     
                             'title' => array(
                                'title' => __( 'Title', 'visitghana_shipping' ),
                                  'type' => 'text',
                                  'description' => __( 'Title to be display on site', 'visitghana_shipping' ),
                                  'default' => __( 'Visit Ghana Shipping', 'visitghana_shipping' )
                                  ),
                            'rateurl' => array(
                                'title' => __( 'API URL', 'visitghana_shipping' ),
                                  'type' => 'text',
                                  'description' => __( 'URL to connect to GhanaPost Rate API', 'visitghana_shipping' ),
                                  'default' => __( 'https://api.ghanapost.com/rate', 'visitghana_shipping' )
                                  ),

                             'apikey' => array(
                                'title' => __( 'GP API KEY', 'visitghana_shipping' ),
                                  'type' => 'text',
                                  'description' => __( 'Special unique GhanaPost API key', 'visitghana_shipping' ),
                                  'default' => __( 'xxxxx xxxxx xxxxx xxxxx', 'visitghana_shipping' )
                                  ),

                             'username' => array(
                                'title' => __( 'API User Name', 'visitghana_shipping' ),
                                  'type' => 'text',
                                  'description' => __( 'Special unique GhanaPost API key', 'visitghana_shipping' ),
                                  'default' => __( 'xxxxx xxxxx xxxxx xxxxx', 'visitghana_shipping' )
                                  ),
                            'userpwd' => array(
                                'title' => __( 'API Password', 'visitghana_shipping' ),
                                  'type' => 'password',
                                  'description' => __( 'Password for your GhanaPost API key', 'visitghana_shipping' ),
                                  'default' => __( '#############', 'visitghana_shipping' )
                                  ),
                             'clientid' => array(
                                'title' => __( 'CLIENT ID', 'visitghana_shipping' ),
                                  'type' => 'text',
                                  'description' => __( 'CLIENT ID to connect to GhanaPost Rate API', 'visitghana_shipping' ),
                                  'default' => __( '#############', 'visitghana_shipping' )
                                  ),

                             
                     
                             );
 
                }

				/**
				 * calculate_shipping function.
				 *
				 * @access public
				 * @param mixed $package
				 * @return void
				 */
				public function calculate_shipping( $package ) {

          $WC_Visit_Ghana_Shipping_Method = new WC_Visit_Ghana_Shipping_Method();


          if(isset($_POST['calc_shipping'])){
            $username = $WC_Visit_Ghana_Shipping_Method->settings['username'];
            $userpwd = $WC_Visit_Ghana_Shipping_Method->settings['userpwd'];
            $apikey = $WC_Visit_Ghana_Shipping_Method->settings['apikey'];
            $rateurl = $WC_Visit_Ghana_Shipping_Method->settings['rateurl'];
            $clientid = $WC_Visit_Ghana_Shipping_Method->settings['clientid'];

            $cityinput = $_POST['calc_shipping_city'];
            $postalinput = $_POST['calc_shipping_postcode'];
            $countryinput = $_POST['calc_shipping_country'];
            $typeinput = $_POST['address-type'];

            switch ($countryinput){
              case 'Canada':
                $selectedcountry = "CA";
                break;

              case 'United States (US)':
                $selectedcountry = "US";
                break;

              case 'Ghana':
                $selectedcountry = "GH";
                break;

              default:
                $selectedcountry ="GH";
                break;
            }

            $packageweight = WC()->cart->cart_contents_weight;

            $shiprateinfo = json_encode(array(
              "APIKey" => $apikey,
              "username" => $username,
              "userpassword" => $userpwd,
              "clientid" => $clientid,
              "TOAddress" => array(
                "PostalCode" => $postalinput,
                "City" => $cityinput,
                "CountryCode" => $selectedcountry
              ),
              "Packages" => array(
                array(
                  "Weight" => $packageweight,
                  "WeightUnits" => "Kg"
                )
              )
            ));
            /*$ch = curl_init($rateurl);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $shiprateinfo);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic " . base64_encode($username . ":" . $userpwd . ":" . $apikey)));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            */
            $curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $rateurl,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS =>"{\n\"APIKEY\":\$apikey,\n\"CLIENTID\":\$clientid,\n\"USERNAME\":\$username,\n\"PASSWORD\":\$userpwd,\n\"METHOD\":\"CHECKSHIPMENTCOST\"\n}",
  CURLOPT_HTTPHEADER => array(
    "Accept: application/json",
    "Accept-Encoding: gzip, deflate",
    "Cache-Control: no-cache",
    "Connection: keep-alive",
    "Content-Length: 198",
    "Content-Type: application/json",
    "Host: eps.ghanapost.com.gh"
  ),
));

$response = curl_exec($curl);

curl_close($curl);

            $fullarray = json_decode($response, TRUE); //Parse json string to array
            $showarray = $fullarray['Rates'];

            $ratenum = 0;
            foreach ($showarray as $i => $item) {
              # code...
              $ratenum++;
              $ratearr = 'rate' . $ratenum;

              $ratecost = "$ ".number_format($showarray[$i]['Total'], 2);
              $rateid = $showarray[$i]['ServiceName'];
              $ratearr = array(
                'id' => $rateid,
                'label' => $showarray[$i]['ServiceName'],
                'cost' => $ratecost,
                'calc_tax' => 'per_item'
              );

              // Register the rate

              $this->add_rate($ratearr);
            }

            /*$packageweight = 0;
            $cost = 0;
            $country = $package["destination"]["country"];

            foreach ( $package['contents'] as $item_id => $values ) 
                    { 
                        $_product = $values['data']; 
                        $packageweight = $packageweight + $_product->get_weight() * $values['quantity']; 
                    }
 
                    $packageweight = wc_get_weight( $packageweight, 'kg' );*/
          }

					/*$weight = 0;
					$cost = 0;
					$country = $package["destination"]["country"];

					foreach ( $package['contents'] as $item_id => $values ) 
                    { 
                        $_product = $values['data']; 
                        $weight = $weight + $_product->get_weight() * $values['quantity']; 
                    }
 
                    $weight = wc_get_weight( $weight, 'kg' );*/



					/*$rate = array(
						'id' => $this->id,
						'label' => $this->title,
						'cost' => '$cost',
						'calc_tax' => 'per_item'
					);

					// Register the rate
					$this->add_rate( $rate );*/
				}
			}
		}
	}

	add_action( 'woocommerce_shipping_init', 'visitghana_shipping_method_init' );

	function add_visitghana_shipping_method( $methods ) {
		$methods['visitghana_shipping_method'] = 'WC_Visit_Ghana_Shipping_Method';
		return $methods;
	}

	add_filter( 'woocommerce_shipping_methods', 'add_visitghana_shipping_method' );

	function visitghana_shipping_validate_order( $posted )   {
 
        $packages = WC()->shipping->get_packages();
 
        $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
         
        if( is_array( $chosen_methods ) && in_array( 'visitghana_shipping', $chosen_methods ) ) {
             
            foreach ( $packages as $i => $package ) {
 
                if ( $chosen_methods[ $i ] != "visitghana_shipping" ) {
                             
                    continue;
                             
                }
 
                
            }       
        } 
    }
 
    add_action( 'woocommerce_review_order_before_cart_contents', 'visitghana_shipping_validate_order' , 10 );
    add_action( 'woocommerce_after_checkout_validation', 'visitghana_shipping_validate_order' , 10 );
}
Sponsor our Newsletter | Privacy Policy | Terms of Service