Support » Plugin: WooCommerce » Loading API content in WooCommerce Shipping Method API Plugin

  • Resolved Bethany Fisher

    (@bethleppard)


    I am building a shipping method plugin for Woocommerce, which pulls rates from a service called SecureShip. The Secureship Rates API info is here: https://secureship.ca/api/rates.aspx

    Currently, I have it set up to load the rates (at least for Canada) when info is input through the built-in WooCommerce shipping calculator.

    THE PROBLEM: the rates disappear when one is chosen!

    Here is my plugin code:

    <?php
    if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    
    function woo_secureship_init() {
      if ( ! class_exists( 'Woo_SecureShip' ) ) {
        class Woo_SecureShip extends WC_Shipping_Method {
    	public function __construct() {
    	  $this->id                 = 'heartbeat_secureship'; // Id for your shipping method. Should be uunique.
    	  $this->method_title       = __( 'SecureShip' );  // Title shown in admin
              $this->method_description = __( 'No options available. Rates are provided by SecureShip API.' ); // Description shown in admin
    
    	  $this->enabled            = "yes"; // This can be added as an setting but for this example its forced enabled
    	  $this->title              = "SecureShip"; // 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' ) );
    	}
    
    	/**
    	* calculate_shipping function.
    	*
    	* @access public
    	* @param mixed $package
    	* @return void
    	*/
    	public function calculate_shipping( $package ) {
    
    	  if (isset($_POST['calc_shipping'])) {
              $username = '****USERLOGIN IS HERE******';
    	  $apikey = '*****APIKEY IS HERE******';
    	  $rateurl = 'https://secureship.ca/webship/api/rates';
    
    	  $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;
                 default:
                  $selectedcountry = "CA";
                  break;
                }
    
                packageweight = WC()->cart->cart_contents_weight;
    
    	    $shipinfo = json_encode(array(
    	      "ApiKey" => "**********",
    	      "CurrencyCode" => "CAD",
    	      "AccountNumber" => "*****",
    	      "Username" => "*****",
    	      "FromAddress" => array(
                     "PostalCode" => "P7A4C7",
                     "City" => "Thunder Bay",
    		 "CountryCode" => "CA",
    		 "Residential" => "false"
    		),
    		"ToAddress" => array(
    		  "PostalCode" => $postalinput,
    		  "City" => $cityinput,
    		  "CountryCode" => $selectedcountry,
    		  "Residential" => true
    		),
    		"PackageType" => "MyPackage",
    		"Packages" => array(
    		  array(
    	            "Weight" => $packageweight,
    		    "WeightUnits" => "LBS"
    		)
    	)
    
    	));
    
    	$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, $shipinfo);
    	curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic " .
    					base64_encode($username . ":" . $apikey)));
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	$output = curl_exec($ch);
    	curl_close($ch);
    	$fullarray = json_decode($output, TRUE); // parse json string to array
    	$showarray = $fullarray['Rates'];
    
    	$ratenum = 0;
    	foreach($showarray as $i => $item) {
    		$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'
    		);
    
    		$this->add_rate( $ratearr );
        }
    
        }
    				  	
    					
    }
    }
    }
    }
    
    	add_action( 'woocommerce_shipping_init', 'woo_secureship_init' );
    
    	function add_secureship( $methods ) {
    		$methods['heartbeat_secureship'] = 'Woo_SecureShip';
    		return $methods;
    	}
    
    	add_filter( 'woocommerce_shipping_methods', 'add_secureship' );
    
    	add_filter( 'woocommerce_shipping_calculator_enable_city', '__return_true' );
    
    }
    
    ?>
    

    NOTE:
    If I don’t use dynamic variables for the city, postal code, etc, the plugin works perfectly. i.e. it works if I change $shipinfo to:

    $shipinfo = json_encode(array(
      "ApiKey" => "******",
      "CurrencyCode" => "CAD",
      "AccountNumber" => "******",
      "Username" => "******",
      "FromAddress" => array(
          "PostalCode" => "P7A4C7",
          "City" => "Thunder Bay",
          "CountryCode" => "CA",
          "Residential" => "false"
       ),
       "ToAddress" => array(
          "PostalCode" => "P7A5R9",
          "City" => "Thunder Bay",
          "CountryCode" => "CA",
          "Residential" => true
        ),
        "PackageType" => "MyPackage",
        "Packages" => array(
           array(
    	 "Weight" => $packageweight,
    	 "WeightUnits" => "LBS"
         )
      )
    ));

    Visit this link to go to the cart page with a product added to it: https://www.heartbeathotsauce.com/cart/?add-to-cart=1199

    Try the shipping calculator with Canadian info, as U.S. doesn’t seem to load at the moment. If you need example data, use Canada / Ontario / Thunder Bay / P7A 5R9

    Any advice would be appreciated!

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.