Jump to content
  • Checkout
  • Login
  • Get in touch

osCommerce

The e-commerce.

Canada Post Automatic Labels


greasemonkey

Recommended Posts

  • 2 years later...

I have been able to get past the login on this program, but I am stuck at the next step.

 

Here is my code up to where it breaks down - works up to the point where the destination is selected. If you replace your code with this up to the same line (fill in your password, etc. but NOT your credit card info!) you will see that the screen for est.canadapost.ca/esto appears twice near the bottom of your test posting to CP.

Do not fill in any credit card info so the process will always crash near the end once it gets to payment.

Next best thing to a sandbox...

<?php
/*
$Id: index.php 1692 2012-02-26 01:26:50Z [email protected] $
 - lines 15 to 23 here were borrowed from index.php to be inserted at the top of ship_canadapost.php - delete second instance of require(includes/application_top.php'); for it to work - otherwise the search tabs are broken in osCmax 2.5.x
  osCmax e-Commerce
  http://www.oscmax.com

  Copyright 2000 - 2011 osCmax

  Released under the GNU General Public License
  
  fresh edit from previously (to 2013) ship_canadapost.php by John Robertson
*/

//  require('includes/application_top.php'); // can delete this line...
  
  if (isset($_GET['setasdefault'])) {
    tep_db_query("update " . TABLE_CONFIGURATION . " set configuration_value = '" . $_GET['setasdefault'] . "' where configuration_key = 'INDEX_TAB'");
	// Configuration Cache modification start
    require ('includes/configuration_cache.php');
    // Configuration Cache modification end
    tep_redirect(tep_href_link(FILENAME_DEFAULT));
  }
?>
<!-- end of additional section to enable ship_canadapost.php to work correctly with osCmax 2.5.x -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<link rel="stylesheet" type="text/css" href="includes/javascript/jquery-ui-1.8.2.custom.css">
<script type="text/javascript" src="includes/general.js"></script>	
</head>
<body>
<?php
$debug = 1; // setting to 1 displays all responses from Canada Post, 0 is off.
  
require('includes/application_top.php');
require(DIR_WS_FUNCTIONS . 'ship_canadapost.php'); // in languages/english/
require_once(DIR_FS_ADMIN . DIR_WS_CLASSES . 'shipping_form.php'); //labels for shipping form
include(DIR_WS_INCLUDES . 'abbreviate.php'); // used to abbreviate state & country names

$action = $_GET['action'];
$order_id = $_GET['oID'];

$form = new shipping_form();
// Enable next two lines to activate error levels for debugging 
error_reporting(E_ALL & E_STRICT & ~E_DEPRECATED);
ini_set('display_errors',1); 

/*******************************************************************************
*** EDIT VARIABLES BELOW                                                     ***
*******************************************************************************/
// Canada Post account
$cp_user = '';
$cp_password = '';
$cp_contract = '';  // if you have a CP contract, put it here to pay via
                           // account instead of credit card
$cp_use_account = 0;       // set to 1 to pay via account instead of credit card (0)

// Sender data (the address is already stored in Canada Post account)
$cp_shipper_name = '';
$cp_shipper_phone = '';
$cp_shipper_pc = ''; // postal code of the form A1B 2C3
$cp_cc_alias = 'xxxx********xxxx'; // card number on file at CP only fill in below if you do not have (or want to have) CC number stored at CP

// Credit card data (more secure to store it here than in the database, but use SFTP...)
$cp_cc_hard_code = FALSE; // set to TRUE if you would like to use the values below
$cp_cc_type = 'MC1'; // AME1, MC1 or VIS1 for Amex, MasterCard or Visa
$cp_cc_number = '<cc number>';
$cp_cc_expiry = 'xx/yy'; // MM/YY
$cp_cc_owner = '<name on cc>';
$cp_cc_cvv = '<security code>';

// Other configuration
$send_email_on_shipping = TRUE; // notify customer that the order has shipped
                                // and provide tracking number if available
                                
$default_length = '35.0';       // provide package size (could add some kind
$default_width = '25.0';        // of manager in the future)
$default_height = '4.0';        // FYI Canada Post breaks with some combinations

$default_reason_for_export = 'OTH'; // SAM, GIF, TRD, REP, DOC, OTH
$weight_factor = 1.000; // factor to convert weight in database to kg

// Order status to set when order shipped
define('CANADAPOST_ORDER_STATUS_SHIPPED', 4);

/*******************************************************************************
*** No need to edit anything below                                           ***
*******************************************************************************/



if (!$order_id) {
  die (ERROR_NO_ORDER_NUMBER);
}

// get all information from the order record
$order_query = tep_db_query("select * from orders where orders_id = '$order_id'");
$order_info = tep_db_fetch_array($order_query);

$countries_query = tep_db_query("select countries_iso_code_2 from " . TABLE_COUNTRIES . " where countries_id = '" . tep_get_country_id($order_info['delivery_country']) . "'");
$countries = tep_db_fetch_array($countries_query);
$delivery_country_iso_code_2 = $countries['countries_iso_code_2'];
// abbreviate the delivery state (function is in abbreviate.php)
$delivery_state_abbrev = abbreviate_state($order_info['delivery_state']);
  
$label_file = DIR_WS_IMAGES . 'canadapost/' . $order_id . '.pdf';

/*******************************************************************************
  Make a new ship request
    Shows configuration page 
*******************************************************************************/

if($action=='new') {
  $order_id = $_GET['oID'];

  // arrays for shipping options; include as many or as few as you like
  
  $reason_for_export = array();
  $reason_for_export[] = array('id' => 'SAM', 'text' => 'Commercial Sample'); 
  $reason_for_export[] = array('id' => 'GIF', 'text' => 'Gift');
  $reason_for_export[] = array('id' => 'TRD', 'text' => 'Trade Show Exhibit');
  $reason_for_export[] = array('id' => 'REP', 'text' => 'Repair/Warranty');
  $reason_for_export[] = array('id' => 'DOC', 'text' => 'Document');
  $reason_for_export[] = array('id' => 'OTH', 'text' => 'Other');

  $service_type = array();
  $shipping_method_keywords = array();
  if ($delivery_country_iso_code_2 == 'CA') { // Canada
    $service_type[] = array('id' => '000000000000000967', 'text' => 'Expedited Parcel Piece Rated');
    $service_type[] = array('id' => '000000000000000966', 'text' => 'Regular Parcel Piece Rated');
    $service_type[] = array('id' => '000000000000001469', 'text' => 'Priority Courier Piece Rated');
    $service_type[] = array('id' => '000000000000001654', 'text' => 'Priority Courier Prepaid Ind');
    $service_type[] = array('id' => '000000000000000908', 'text' => 'Xpresspost Piece Rated');
    $service_type[] = array('id' => '000000000000000926', 'text' => 'Xpresspost Prepaid Induction');
    
    $shipping_method_keywords = array('000000000000000966' => 'Regular',
                                      '000000000000000967' => 'Expedited',
                                      '000000000000000908' => 'Xpresspost',
                                      '000000000000001469' => 'Priority');
  } elseif ($delivery_country_iso_code_2 == 'US') { // USA
    $service_type[] = array('id' => '000000000000010103', 'text' => 'Priority Worldwide EnvelopeUSA');
    $service_type[] = array('id' => '000000000000010104', 'text' => 'Priority Worldwide Pak USA');
    $service_type[] = array('id' => '000000000000010105', 'text' => 'Priority Worldwide Parcel USA');
    $service_type[] = array('id' => '000000000000001917', 'text' => 'Xpresspost USA');
    $service_type[] = array('id' => '000000000000002125', 'text' => 'Xpresspost USA Prepaid Ind');
    $service_type[] = array('id' => '000000000000006461', 'text' => 'Commercial* Expedited-USA');
    $service_type[] = array('id' => '000000000000006470', 'text' => 'Expedited Parcel-USA');
    $service_type[] = array('id' => '000000000000001123', 'text' => 'USA Small Packets Air Mail');
    $service_type[] = array('id' => '000000000000001124', 'text' => 'USA Small Packets Surface');
    
    $shipping_method_keywords = array('000000000000001123' => 'Small Packets Air',
                                      '000000000000001124' => 'Small Packets Surface',
                                      '000000000000006461' => 'Expedited US Business',
                                      '000000000000001917' => 'Xpresspost',
                                      '000000000000002020' => 'Purolator');
  } else {  // International
    $service_type[] = array('id' => '000000000000010100', 'text' => 'Priority Worldwide EnvelopeINT');
    $service_type[] = array('id' => '000000000000010101', 'text' => 'Priority Worldwide Pak INTL');
    $service_type[] = array('id' => '000000000000010102', 'text' => 'Priority Worldwide Parcel INTL');
    $service_type[] = array('id' => '000000000000006210', 'text' => 'Xpresspost - International');
    $service_type[] = array('id' => '000000000000000985', 'text' => 'International Parcel Air');
    $service_type[] = array('id' => '000000000000000984', 'text' => 'International Parcel Surface');
    $service_type[] = array('id' => '000000000000009611', 'text' => 'Intl Small Packets Surface');
    $service_type[] = array('id' => '000000000000009610', 'text' => 'Intl Small Packets Air');
    
    $shipping_method_keywords = array('000000000000009610' => 'Small Packets Air',
                                      '000000000000009611' => 'Small Packets Surface',
                                      '000000000000006210' => 'Xpresspost',
                                      '000000000000002020' => 'Purolator',
                                      '000000000000000985' => 'Parcel Air',
                                      '000000000000000984' => 'Parcel Surface');
  }

  // get the shipping method
  $shipping_type = '';
  $shipping_query = tep_db_query("select title from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . $order_id . "' and class='ot_shipping'");
  $shipping_method = tep_db_fetch_array($shipping_query);
  $shipping_method = trim($shipping_method['title'], ':');

  while (list($shipping_index, $shipping_keyword) = each($shipping_method_keywords)){
    if (false !== stripos($shipping_method, $shipping_keyword, 1)){
          $shipping_type = $shipping_index;
          break 1;
      }
    }

// get the order qty and item weights
  $order_qty_query = tep_db_query("select * from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $order_id . "'");
  $order_qty = 0;
  $order_weight = 0;
  $order_item_html = '';
  if (tep_db_num_rows($order_qty_query)) {
    while ($order_qtys = tep_db_fetch_array($order_qty_query)) {
      $order_item_html = $order_item_html . '          <tr>' . "\n" .
                                            '            <td class="smallText" align="left">' . $order_qtys['products_quantity'] . ' * ' . $order_qtys['products_name'] . '</td>' . "\n" .
                                            '            <td class="smallText" align="left">';
      $order_qty = $order_qty + $order_qtys['products_quantity'];
      $products_id = $order_qtys['products_id'];
      $products_weight_query = tep_db_query("select * from " . TABLE_PRODUCTS . " where products_id = '" . $products_id . "'");
      if (tep_db_num_rows($products_weight_query)) {
        $products_weights = tep_db_fetch_array($products_weight_query);
        $order_weight = $order_weight + ($order_qtys['products_quantity'] * ($products_weights['products_weight']));
        $item_weights[] = $products_weights['products_weight'];
      }
    }

    $order_weight = $order_weight + SHIPPING_BOX_WEIGHT;
    
    /*
    // Find out which weighs more tare or percentage shipping rate and display that rate
    $order_weight_tar = $order_weight + SHIPPING_BOX_WEIGHT;
    $order_weight_percent = ($order_weight * (SHIPPING_BOX_PADDING / 100 + 1));

    if ($order_weight_percent < $order_weight_tar) {
    $order_weight = $order_weight_tar;
    } else {
    $order_weight = $order_weight_percent;
    }
    */
        
    $order_weight = round($order_weight * $weight_factor,3);
    $order_weight = sprintf("%01.3f", $order_weight);
  }
}

/*******************************************************************************
  Start writing webpage HTML
*******************************************************************************/
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/general.js"></script>
<?php $form->print_js(); ?>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- header //-->
<?php
  require(DIR_WS_INCLUDES . 'header.php');
?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr>
    <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="1" cellpadding="1" class="columnLeft">
<!-- left_navigation //-->
<?php require(DIR_WS_INCLUDES . 'column_left.php'); ?>
<!-- left_navigation_eof //-->
    </table></td>
<!-- body_text //-->
    <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
      <tr>
              <td width="100%">
<?
/*******************************************************************************
  Make a new ship request
    Shows form to fill out
*******************************************************************************/

if ($action=='new') {
  $form->dim_type = 'cm';
  $form->weight_type = 'kg';
  $form->weight_factor = 1.0;
  
  $check_status_query = tep_db_query("select orders_status from " . TABLE_ORDERS . " where orders_id = '" . (int)$order_id . "'");
  $check_status = tep_db_fetch_array($check_status_query);
  if ($check_status['orders_status'] == CANADAPOST_ORDER_STATUS_SHIPPED) {
    echo '<div style="font-weight: bold; color: white; background-color: red; border: 1px solid gray; padding: 5px;">Warning: Order already shipped</div>';
  }
  
  /*
  $address1 = trim($order_info['delivery_street_address']);
  $address2 = '';
  if (strlen($address1) > 44) { // maximum is 44 letters
    if(strstr($address1, '-') !== FALSE) {
      ereg("(.+)-([^-]+)$", $address1, $matches);
      $address1 = trim($matches[1]);
      $address2 = trim($matches[2]);
    } else if(strstr($address1, ',') !== FALSE) {
      ereg("(.+),([^,]+)$", $address1, $matches);
      $address1 = trim($matches[1]);
      $address2 = trim($matches[2]);
    } else if(stristr($address1, ' ') !== FALSE) {
      ereg("(.+) ([^ ]+)$", $address1, $matches);
      $address1 = trim($matches[1]);
      $address2 = trim($matches[2]);
    }http://www.canadapost.ca/cpo/mc/default.jsf?LOCALE=en
  }
  */
  
  echo tep_draw_form('ship_form', FILENAME_SHIP_CANADAPOST, 'cPath=' . $cPath . '&cID=' . $_GET['cID'] . '&oID=' . $order_id . '&action=ship', 'post', 'enctype="multipart/form-data"  onsubmit=""');
  $form->print_form($order_id, !$cp_use_account && !$cp_cc_hard_code, $order_weight, $default_length, $default_width, $default_height, $service_type, $shipping_type, $reason_for_export, $default_reason_for_export);
  echo '</form>';
} else if($action=='ship') {
/*******************************************************************************
  Process shipment with Canada Post
    Does all the transactions with Canada Post servers and provides a label
*******************************************************************************/
  $check_status_query = tep_db_query("select orders_status from " . TABLE_ORDERS . " where orders_id = '" . (int)$order_id . "'");
  $check_status = tep_db_fetch_array($check_status_query);
  if ($check_status['orders_status'] == CANADAPOST_ORDER_STATUS_SHIPPED) {
    echo '<div style="font-weight: bold; color: white; background-color: red; border: 1px solid gray; padding: 5px;">Error: Order already shipped</div>';
    die();
  }


  $countries_query = tep_db_query("select countries_iso_code_2 from " . TABLE_COUNTRIES . " where countries_id = '" . tep_get_country_id(cp_post_var('delivery_country')) . "'");
  $countries = tep_db_fetch_array($countries_query);
  $delivery_country_iso_code_2 = $countries['countries_iso_code_2'];
  // abbreviate the delivery state (function is in abbreviate.php)
  $delivery_state_abbrev = abbreviate_state(cp_post_var('delivery_state'));


  echo '<div class="pageHeading">Canada Post Automatic Labels</div>';
  echo tep_draw_separator('pixel_trans.gif', 1, 20);
  
  // array of characters we don't want in phone numbers
  $unwanted = array('(',')','-','.',' ','/');
  // get rid of dashes, parentheses and periods in customer's telephone number
  $delivery_phone = trim(str_replace($unwanted, '', cp_post_var('delivery_phone')));

  ////
  // 1. INITIALIZE
  
  if (file_exists('temp/cp_cookies')) {
    unlink('temp/cp_cookies'); // delete old cookie file
  }
  
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_POST, 0);
  curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
  curl_setopt($ch, CURLOPT_REFERER, 'https://est.canadapost.ca/esto/');
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  //Windows 2003 Compatibility 
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
  curl_setopt($ch, CURLOPT_HEADER, 1);
  
  curl_setopt($ch, CURLOPT_COOKIEFILE, 'temp/cp_cookies');
  curl_setopt($ch, CURLOPT_COOKIEJAR, 'temp/cp_cookies');
  
  // Sanity Check and Progress Report
  cp_progress(1, 'Initialized.');
  
  ////
  // 2. LOG IN
echo "<br>" . "hi! - log in" . "<br>"; //Test
//  $response = cp_get_page($ch, 'https://sso.epost.ca/sso/lfe/ui/login?'); is this line needed? Sept 2, 2015
  
  // original  was 'https://www.canadapost.ca/cpid/login.jsp?SSO_REFERRER_URL=https://www.canadapost.ca');
  
  $query_string = 'cpidSignIn:signIn.x=46&cpidSignIn:signIn.y=11&cpidSignIn_SUBMIT=1'
                . '&cpidSignIn:sso_username=' . urlencode($cp_user)
                . '&cpidSignIn:sso_password=' . urlencode($cp_password)
                . '&cpidSignIn:rememberUserName=true'
                . '&destination=https://est.canadapost.ca';

// one ends up here: https://www.canadapost.ca/web/en/home.page?forceVouchFor=true                     
  $response = cp_post_page($ch, 'https://sso.epost.ca', $query_string);

  echo "<br>" . "Hi! Sign in query string: " . $query_string . '<br>' . "<br>" ;

  
echo  "<b>Seems to work to here, line 368 - get to login page fine. Below is on the page https://sso.epost.ca/...</b><br><br>";  

  $response = cp_get_page($ch, 'https://sso.epost.ca/sso/lfe/ui/login?');
  
  $query_string = 'SHOP=CPFRCOMM&SSO_ITS_URL=%2Fcpid%2Flogin.jsp&SSO_ACTION=0&P_SHOP=CPFRCOMM'
                . '&login_type=2&password_length=0&%7Elanguage=EN&APP_ID=B2B'
                . '&SSO_USERNAME=' . urlencode($cp_user)
                . '&SSO_PASSWORD=' . urlencode($cp_password);
echo "hi from line 378!";  //Test               
  $response = cp_post_page($ch, 'https://est.canadapost.ca/esto/', $query_string);
 echo $response;  //Test


  // get Canada Post customer number - is this step needed??
  $regexp = "SSO_CUSTOMER_NUMBER\" value=\"([0123456789]*)(,|\")";
  $matches = '';
  preg_match("/$regexp/siU", $response, $matches);
  $cp_customer = $matches[1];
 echo "hi from line 388!<br>";   
  $response = cp_submit_page($ch, $response, 'https://est.canadapost.ca/esto/');
 
echo "hi from line 395!<br>"; //Test
echo $response; //Test

  // Sanity Check and Progress Report - 
echo "we are getting to the login test, and we actually have reached the page after login successfull!, looking for hidden name = sso_version_major, value of '3'";
  if (strstr($response, '<input type=hidden name="Set-Cookie:">') === ESTO_JSESSIONID) {
    cp_error(2, 'Log-In Failed check in ' . __FILE__ . ' at line ' . __LINE__  . '. This most likely means that Canada Post has changed their user interface or your login info is incorrect. You need to update your Canada Post Automatic Shipping Labels module.');
    curl_close($ch); die(); /////////////////////
  } else {
    cp_progress(2, 'Logged in.');
  }
  echo "logged in!<br><br>"; //Test
   
echo "Start Shipping<br><br>"; //Test
  ////
  // 3. START SHIPPING - Select iso code
  
  $form_prefix = '';
  if ($delivery_country_iso_code_2 == 'CA') {
    $form_prefix = 'domestic';
  } elseif ($delivery_country_iso_code_2 == 'US') {
    $form_prefix = 'us';
  } else {
    $form_prefix = 'international';
  }
  
//  $response = cp_get_page($ch, 'https://est-oee.canadapost-postescanada.ca/shipping/estShipping.jsp?locale=en_CA&formId=' . $form_prefix . '0&isV1=true');
 $response = cp_get_page($ch, 'https://est.canadapost.ca/esto/app/shipment/' . $form_prefix . '?execution=e1s1'); 
 
  $regexp = "URL=([^\"]*)\"";
  $matches = '';
  preg_match("/$regexp/siU", $response, $matches);
  $url = $matches[1];
  echo "regexp= ";
  echo $regexp;
       echo ", url= ";
    echo $url;
    echo ", ch= ";
    echo $ch;
//      echo ", response= ";
//    echo $response;
      echo ", form_prefix= ";
    echo $form_prefix;
 // $response = cp_get_page($ch, $url);
  $response = cp_submit_page($ch, $response);
echo $response;  //test
  /**/
  $regexp = "URL=([^\"]*)\"";
  $matches = '';
  preg_match("/$regexp/siU", $response, $matches);
  $url = $matches[1];
  
  $response = cp_get_page($ch, $url);
      echo ", response2 = ";
    echo $response;
  $response = cp_submit_page($ch, $response);
     echo "matches = ";
    echo $matches;
    echo ", ch1 = ";
    echo $ch;
      echo ", response1 = ";
    echo $response;
      echo ", form_prefix = ";
    echo $form_prefix;
  /**/
  
  // Sanity Check and Progress Report
  if (stristr($response, '<input type="hidden" name="formId" value="' . $form_prefix . '0">') === FALSE) {
    cp_error(3, 'Ship To Country Select Failed check in ' . __FILE__ . ' at line ' . __LINE__  . '. This most likely means that Canada Post has changed their user interface. You need to update your Canada Post Automatic Shipping Labels module.');
    curl_close($ch); die(); /////////////////////
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...