ParcelPro_Carrier - Version 1.0.2

Version Notes

Version 1.0.2
Improved logging

Version 1.0.1
Actually use default location for ShipFrom
Some error logging added

Version 1.0.0
New release.

Download this release

Release Info

Developer Parcel Pro, Inc. Joey Chan, Project Lead Jasper Lynn, Project Manager
Extension ParcelPro_Carrier
Version 1.0.2
Comparing to
See all releases


Code changes from version 1.0.1 to 1.0.2

app/code/community/ParcelPro/Carrier/Helper/Parcelpro.php CHANGED
@@ -230,9 +230,16 @@ class ParcelPro_Carrier_Helper_Parcelpro extends Mage_Core_Helper_Abstract
230
  }
231
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
232
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 
233
 
234
  $data = curl_exec ($ch);
 
 
 
235
  curl_close ($ch);
 
 
 
236
  if($data){
237
  if($isPost){
238
  $result = json_decode($data);
230
  }
231
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
232
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
233
+ curl_setopt($ch, CURLOPT_HEADER, true);
234
 
235
  $data = curl_exec ($ch);
236
+ list($header,$data) = explode("\r\n\r\n",$data,2);
237
+ $header = explode("\r\n",$header);
238
+ $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
239
  curl_close ($ch);
240
+ if($http_status == '400'){
241
+ Mage::log("Query failed:".explode(" ",$header[0])[2],null,'ppimagento.log');
242
+ }
243
  if($data){
244
  if($isPost){
245
  $result = json_decode($data);
app/code/community/ParcelPro/Carrier/Helper/Parcelpro.php~ ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Magento
4
+ *
5
+ * NOTICE OF LICENSE
6
+ *
7
+ * This source file is subject to the Open Software License (OSL 3.0)
8
+ * that is bundled with this package in the file LICENSE.txt.
9
+ * It is also available through the world-wide-web at this URL:
10
+ * http://opensource.org/licenses/osl-3.0.php
11
+ * If you did not receive a copy of the license and are unable to
12
+ * obtain it through the world-wide-web, please send an email
13
+ * to license@magentocommerce.com so we can send you a copy immediately.
14
+ *
15
+ * DISCLAIMER
16
+ *
17
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
18
+ * versions in the future. If you wish to customize Magento for your
19
+ * needs please refer to http://www.magentocommerce.com for more information.
20
+ *
21
+ * @category Mage
22
+ * @package Mage_Usa
23
+ * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
24
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25
+ */
26
+
27
+ /**
28
+ * Usa data helper
29
+ *
30
+ * @author Magento Core Team <core@magentocommerce.com>
31
+ */
32
+ class ParcelPro_Carrier_Helper_Parcelpro extends Mage_Core_Helper_Abstract
33
+ {
34
+ private $_base_url;
35
+ private $_version;
36
+ private $_auth_path;
37
+ private $_location_path;
38
+ private $_addressbook_path;
39
+
40
+ private $_single_quote_path;
41
+ private $_shipment_path;
42
+ private $_highvalue_path;
43
+ private $_estimator_path;
44
+ private $_carrierservices_path;
45
+ private $_packagetypes_path;
46
+ private $_zipcodevalidator_path;
47
+ private $_addressvalidator_path;
48
+
49
+ private $_sessionId = null;
50
+
51
+ protected $_code = 'parcelpro_carrier';
52
+
53
+ public function __construct()
54
+ {
55
+ $this->_base_url = 'https://apibeta.parcelpro.com/';
56
+
57
+ if(Mage::getStoreConfig('carriers/parcelpro/sandbox_mode') == 1){
58
+ $this->_base_url = 'https://apibeta.parcelpro.com/';
59
+ }else{
60
+ $this->_base_url = 'https://api.parcelpro.com/';
61
+ }
62
+
63
+ $this->_version = 'v1.1/';
64
+ //$this->_version = 'v1/';
65
+ $this->_auth_path = 'auth';
66
+ $this->_location_path = 'location';
67
+ $this->_addressbook_path = 'addressbook';
68
+ $this->_quote_path = 'quote';
69
+ $this->_shipment_path = 'shipment';
70
+ $this->_highvalue_path = 'highvalue';
71
+ $this->_estimator_path = 'estimator';
72
+ $this->_carrierservices_path = 'carrierservices';
73
+ $this->_packagetypes_path = 'packagetypes';
74
+ $this->_zipcodevalidator_path = 'zipcodevalidator';
75
+ $this->_addressvalidator_path = 'addressvalidator';
76
+
77
+ }
78
+ public function updateSpecialServices(){
79
+ $this->_deleteConfig('special_services');
80
+ $model = Mage::getModel('carrier/config');
81
+ $upsSpecialServices = array(
82
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
83
+ 'DIRECT' => Mage::helper('usa')->__('Direct Signature'),
84
+ 'saturday_pickup' => Mage::helper('usa')->__('Saturday pickup'),
85
+ 'saturday_delivery' => Mage::helper('usa')->__('Saturday delivery'),
86
+ 'thermal_label' => Mage::helper('usa')->__('Thermal label'),
87
+ );
88
+ foreach ($upsSpecialServices as $key => $val){
89
+ $model->setCarrier('UPS')
90
+ ->setConfigType('special_services')
91
+ ->setConfigKey($key)
92
+ ->setConfigValue($val)
93
+ ->setApplyTo('UPS')
94
+ ->save();
95
+ $model->unsetData();
96
+ }
97
+ $fedexSpecialServices = array(
98
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
99
+ 'ADULT' => Mage::helper('usa')->__('Adult Signature'),
100
+ 'DIRECT' => Mage::helper('usa')->__('Direct Signature'),
101
+ 'saturday_pickup' => Mage::helper('usa')->__('Saturday pickup'),
102
+ 'saturday_delivery' => Mage::helper('usa')->__('Saturday delivery'),
103
+ 'thermal_label' => Mage::helper('usa')->__('Thermal label'),
104
+
105
+ );
106
+ foreach ($fedexSpecialServices as $key => $val){
107
+ $model->setCarrier('FEDEX')
108
+ ->setConfigType('special_services')
109
+ ->setConfigKey($key)
110
+ ->setConfigValue($val)
111
+ ->setApplyTo('FEDEX')
112
+ ->save();
113
+ $model->unsetData();
114
+ }
115
+ }
116
+
117
+ public function updatePackageTypes(){
118
+ $model = Mage::getModel('carrier/config');
119
+ $collection = $model->getCollection()
120
+ ->addFieldToFilter('config_type',array('eq'=>'carrier'));
121
+ foreach($collection as $row){
122
+ $this->_deleteConfig('packaging', $row->getConfigValue());
123
+ $carrierServices = $model->getCollection()
124
+ ->addFieldToFilter('config_type',array('eq'=>'method'))->addFieldToFilter('carrier',array('eq'=>$row->getConfigValue()));
125
+ foreach ($carrierServices as $carrierService){
126
+ $queryString = 'carrierservicecode='.$carrierService->getConfigKey().'&carriercode='.$row->getConfigValue();
127
+ $packageTypes = $this->_sendRequest($this->_packagetypes_path, $queryString, array());
128
+ if($packageTypes){
129
+ foreach ($packageTypes as $packageType){
130
+ $model->setCarrier($row->getConfigValue())
131
+ ->setConfigType('packaging')
132
+ ->setConfigKey($packageType->PackageTypeCode)
133
+ ->setConfigValue($packageType->PackageTypeDesc)
134
+ ->setApplyTo($carrierService->getConfigKey())
135
+ ->save();
136
+ $model->unsetData();
137
+ }
138
+ }
139
+ }
140
+ }
141
+ }
142
+
143
+ public function updateCarrierServices(){
144
+ $model = Mage::getModel('carrier/config');
145
+ $collection = $model->getCollection()
146
+ ->addFieldToFilter('config_type',array('eq'=>'carrier'));
147
+ foreach($collection as $row){
148
+ $this->_deleteConfig('method', $row->getConfigValue());
149
+ $queryString = 'carriercode='.$row->getConfigValue().'&domesticonly=False';
150
+ $carrierServices = $this->_sendRequest($this->_carrierservices_path, $queryString, array());
151
+ if($carrierServices){
152
+ foreach ($carrierServices as $service){
153
+ $model->setCarrier($row->getConfigValue())
154
+ ->setConfigType('method')
155
+ ->setConfigKey($service->ServiceCode)
156
+ ->setConfigValue($service->ServiceCodeDesc)
157
+ ->save();
158
+ $model->unsetData();
159
+ }
160
+ }
161
+
162
+ $queryString = 'carriercode='.$row->getConfigValue().'&domesticonly=True';
163
+ $carrierServices = $this->_sendRequest($this->_carrierservices_path, $queryString, array());
164
+ if($carrierServices){
165
+ foreach ($carrierServices as $service){
166
+ $model->setCarrier($row->getConfigValue())
167
+ ->setConfigType('method')
168
+ ->setConfigKey($service->ServiceCode)
169
+ ->setConfigValue($service->ServiceCodeDesc)
170
+ ->save();
171
+ $model->unsetData();
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+ public function updateCarriers(){
178
+ $model = Mage::getModel('carrier/config');
179
+ $this->_deleteConfig('carrier');
180
+ $model->setCarrier('')
181
+ ->setConfigType('carrier')
182
+ ->setConfigKey('UPS')
183
+ ->setConfigValue('UPS')
184
+ ->setApplyTo('1')
185
+ ->save();
186
+ $model->unsetData();
187
+ $model->setCarrier('')
188
+ ->setConfigType('carrier')
189
+ ->setConfigKey('FEDEX')
190
+ ->setConfigValue('FEDEX')
191
+ ->setApplyTo('2')
192
+ ->save();
193
+ return true;
194
+ }
195
+
196
+ private function _deleteConfig($type, $carrier = null){
197
+ $model = Mage::getModel('carrier/config');
198
+ if($carrier){
199
+ $collection = $model->getCollection()
200
+ ->addFieldToFilter('config_type',array('eq'=>$type))->addFieldToFilter('carrier',array('eq'=>$carrier));
201
+ }else{
202
+ $collection = $model->getCollection()
203
+ ->addFieldToFilter('config_type',array('eq'=>$type));
204
+ }
205
+ foreach($collection as $row){
206
+ $row->delete();
207
+ }
208
+ }
209
+ private function _sendRequest($requestPath, $queryString, $parrams, $isPost = false){
210
+ if(!$this->_sessionId){
211
+ $this->_getSessionId();
212
+ }
213
+
214
+ if($this->_sessionId){
215
+ $url = $this->_base_url . $this->_version . $requestPath . '?' . $queryString .'&sessionID=' . $this->_sessionId;
216
+ $ch = curl_init();
217
+ curl_setopt($ch, CURLOPT_URL, $url);
218
+ if($isPost){
219
+ curl_setopt($ch, CURLOPT_POST, 1);
220
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parrams));
221
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
222
+ 'Content-Type: application/json',
223
+ 'Content-Length: ' . strlen(json_encode($parrams)))
224
+ );
225
+ }else{
226
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
227
+ 'Content-Type: application/json',
228
+ )
229
+ );
230
+ }
231
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
232
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
233
+ curl_setopt($ch, CURLOPT_HEADER, true);
234
+
235
+ $data = curl_exec ($ch);
236
+ curl_close ($ch);
237
+ if($data){
238
+ if($isPost){
239
+ $result = json_decode($data);
240
+ }else{
241
+ $result = json_decode($data);
242
+ }
243
+ return $result;
244
+ }else{
245
+ return null;
246
+ }
247
+ }else{
248
+ return null;
249
+ }
250
+ }
251
+
252
+ private function _getSessionId(){
253
+ $model = Mage::getModel('carrier/config');
254
+ $collection = $model->getCollection()
255
+ ->addFieldToFilter('config_type',array('eq'=>'session_id'));
256
+ if($collection->count()){
257
+ $item = $collection->getFirstItem();
258
+ if($this->_checkInvalideSession($item->getConfigValue())){
259
+ $this->_sessionId = $item->getConfigValue();
260
+ return $item->getConfigValue();
261
+ }else{
262
+ $item->delete();
263
+ }
264
+ }
265
+
266
+ $username = Mage::helper('core')->decrypt(Mage::getStoreConfig('carriers/parcelpro/account'));
267
+ $password = Mage::helper('core')->decrypt(Mage::getStoreConfig('carriers/parcelpro/password'));
268
+ $apikey = Mage::helper('core')->decrypt(Mage::getStoreConfig('carriers/parcelpro/key'));
269
+
270
+ $ch = curl_init();
271
+ $auth_url = $this->_base_url . $this->_version . $this->_auth_path;
272
+ $auth_url .= '?username='.$username.'&password='.$password.'&apikey='.$apikey;
273
+
274
+ curl_setopt($ch, CURLOPT_URL, $auth_url);
275
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
276
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
277
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
278
+ 'Content-Type: application/json',
279
+ )
280
+ );
281
+
282
+ $authData = curl_exec ($ch);
283
+ curl_close ($ch);
284
+ if($authData){
285
+ $result = json_decode($authData);
286
+ $this->_sessionId = $result->SessionID;
287
+ $this->_checkInvalideSession($result->SessionID);
288
+ if($result->Message)
289
+ Mage::log('getSessionId:'.$result->Message,null,'ppimagento.log');
290
+
291
+ $model->setCarrier("")
292
+ ->setConfigType('session_id')
293
+ ->setConfigKey('session_id')
294
+ ->setConfigValue($result->SessionID)
295
+ ->save();
296
+ $model->unsetData();
297
+
298
+ return $result->SessionID;
299
+ }else{
300
+ return false;
301
+ }
302
+ }
303
+
304
+ private function _checkInvalideSession($sessionId){
305
+ if($sessionId == null || $sessionId == ""){
306
+ return false;
307
+ }
308
+ $ch = curl_init();
309
+ $location_url = $this->_base_url . $this->_version . $this->_location_path;
310
+ $location_url .= '?sessionID=' . $sessionId;
311
+
312
+ curl_setopt($ch, CURLOPT_URL, $location_url);
313
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
314
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
315
+ $locationData = curl_exec ($ch);
316
+ $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
317
+ curl_close ($ch);
318
+ if($http_status == '401'){
319
+ return false;
320
+ }else{
321
+ return true;
322
+ }
323
+ }
324
+ }
app/code/community/ParcelPro/Carrier/Model/Carrier.php CHANGED
@@ -482,11 +482,8 @@ class ParcelPro_Carrier_Model_Carrier extends Mage_Shipping_Model_Carrier_Abstra
482
 
483
  private function _collectShipmentRequestData(Varien_Object $request){
484
  $this->_prepareShipmentRequest($request);
485
- $contacts = $this->_sendRequest($this->_location_path, array(), false);
486
- if(!$contacts){
487
- return null;
488
- }
489
- $contactId = $contacts[0]->ContactId;
490
 
491
  if ($request->getShipperAddressCountryCode() != $request->getRecipientAddressCountryCode()) {
492
  $IsResidential = false;
@@ -1223,7 +1220,7 @@ class ParcelPro_Carrier_Model_Carrier extends Mage_Shipping_Model_Carrier_Abstra
1223
  $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1224
  curl_close ($ch);
1225
  if($http_status == '400'){
1226
- Mage::log("Query failed:".explode(" ",$header[0])[3],null,'ppimagento.log');
1227
  }
1228
  if($data){
1229
  if($requestPath == $this->_quote_path){
482
 
483
  private function _collectShipmentRequestData(Varien_Object $request){
484
  $this->_prepareShipmentRequest($request);
485
+ $user = $this->_sendRequest($this->_user_path, array(), false);
486
+ $contactId = $user->DefaultLocation;
 
 
 
487
 
488
  if ($request->getShipperAddressCountryCode() != $request->getRecipientAddressCountryCode()) {
489
  $IsResidential = false;
1220
  $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1221
  curl_close ($ch);
1222
  if($http_status == '400'){
1223
+ Mage::log("Query failed:".explode(" ",$header[0])[2],null,'ppimagento.log');
1224
  }
1225
  if($data){
1226
  if($requestPath == $this->_quote_path){
app/code/community/ParcelPro/Carrier/Model/Carrier.php~ ADDED
@@ -0,0 +1,1314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class ParcelPro_Carrier_Model_Carrier extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface {
3
+
4
+ private $_base_url;
5
+ private $_version;
6
+ private $_auth_path;
7
+ private $_location_path;
8
+ private $_addressbook_path;
9
+
10
+ private $_single_quote_path;
11
+ private $_quote_path;
12
+ private $_shipment_path;
13
+ private $_highvalue_path;
14
+ private $_estimator_path;
15
+ private $_carrierservices_path;
16
+ private $_packagetypes_path;
17
+ private $_zipcodevalidator_path;
18
+ private $_addressvalidator_path;
19
+
20
+ private $_sessionId = null;
21
+
22
+ protected $_code = 'parcelpro';
23
+
24
+ /**
25
+ * Rate result data
26
+ *
27
+ * @var Mage_Shipping_Model_Rate_Result|null
28
+ */
29
+ protected $_result = null;
30
+
31
+ public function __construct()
32
+ {
33
+ if($this->getConfigData('sandbox_mode') == 1){
34
+ $this->_base_url = 'https://apibeta.parcelpro.com/';
35
+ }else{
36
+ $this->_base_url = 'https://api.parcelpro.com/';
37
+ }
38
+ $this->_version = 'v1.1/';
39
+ //$this->_version = 'v1/';
40
+ $this->_auth_path = 'auth';
41
+ $this->_location_path = 'location';
42
+ $this->_addressbook_path = 'addressbook';
43
+ $this->_quote_path = 'quote';
44
+ $this->_shipment_path = 'shipment';
45
+ $this->_highvalue_path = 'highvalue';
46
+ $this->_estimator_path = 'estimator';
47
+ $this->_carrierservices_path = 'carrierservices';
48
+ $this->_packagetypes_path = 'packagetypes';
49
+ $this->_zipcodevalidator_path = 'zipcodevalidator';
50
+ $this->_addressvalidator_path = 'addressvalidator';
51
+ $this->_user_path = 'user';
52
+
53
+ }
54
+
55
+ public function collectRates(Mage_Shipping_Model_Rate_Request $request) {
56
+ $result = Mage::getModel('shipping/rate_result');
57
+ if($this->getConfigData('allowed_carriers')){
58
+ $_rawRequest = $this->_collectRequestData($request);
59
+ //Mage::log(json_encode($_rawRequest));
60
+ $estimatorData = $this->_sendRequest($this->_estimator_path, $_rawRequest, true);
61
+
62
+ $rateList = $this->_parseShippingRates($estimatorData);
63
+
64
+ if($rateList){
65
+ foreach ($rateList as $rate){
66
+ $result->append($rate);
67
+ }
68
+ }
69
+ $this->_result = $result;
70
+ }
71
+ return $result;
72
+
73
+ }
74
+ public function getAllowedMethods() {
75
+ $arr = array();
76
+ $allMethods = $this->getCode('method');
77
+
78
+ $allMethodOptions = array();
79
+ if($allMethods){
80
+ foreach ($allMethods as $key =>$val){
81
+ $allMethodOptions[$key] = $val;
82
+ }
83
+ }
84
+ $upsAllowed = explode(',', $this->getConfigData('allowed_ups_methods'));
85
+ foreach ($upsAllowed as $k) {
86
+ if(isset($allMethodOptions[$k])){
87
+ $arr[$k] = $allMethodOptions[$k];
88
+ }
89
+ }
90
+
91
+ $fedexAllowed = explode(',', $this->getConfigData('allowed_fedex_methods'));
92
+ foreach ($fedexAllowed as $k) {
93
+ if(isset($allMethodOptions[$k])){
94
+ $arr[$k] = $allMethodOptions[$k];
95
+ }
96
+ }
97
+ return $arr;
98
+ }
99
+
100
+ /**
101
+ * Check if carrier has shipping tracking option available
102
+ * All Mage_Usa carriers have shipping tracking option available
103
+ *
104
+ * @return boolean
105
+ */
106
+ public function isTrackingAvailable()
107
+ {
108
+ return true;
109
+ }
110
+
111
+ public function isShippingLabelsAvailable()
112
+ {
113
+ return true;
114
+ }
115
+
116
+ /**
117
+ * Return items for further shipment rate evaluation. We need to pass children of a bundle instead passing the
118
+ * bundle itself, otherwise we may not get a rate at all (e.g. when total weight of a bundle exceeds max weight
119
+ * despite each item by itself is not)
120
+ *
121
+ * @param Mage_Shipping_Model_Rate_Request $request
122
+ * @return array
123
+ */
124
+ public function getAllItems(Mage_Shipping_Model_Rate_Request $request)
125
+ {
126
+ $items = array();
127
+ if ($request->getAllItems()) {
128
+ foreach ($request->getAllItems() as $item) {
129
+ /* @var $item Mage_Sales_Model_Quote_Item */
130
+ if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
131
+ // Don't process children here - we will process (or already have processed) them below
132
+ continue;
133
+ }
134
+
135
+ if ($item->getHasChildren() && $item->isShipSeparately()) {
136
+ foreach ($item->getChildren() as $child) {
137
+ if (!$child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
138
+ $items[] = $child;
139
+ }
140
+ }
141
+ } else {
142
+ // Ship together - count compound item as one solid
143
+ $items[] = $item;
144
+ }
145
+ }
146
+ }
147
+ return $items;
148
+ }
149
+
150
+ /**
151
+ * Processing additional validation to check if carrier applicable.
152
+ *
153
+ * @param Mage_Shipping_Model_Rate_Request $request
154
+ * @return Mage_Shipping_Model_Carrier_Abstract|Mage_Shipping_Model_Rate_Result_Error|boolean
155
+ */
156
+ /*
157
+ public function proccessAdditionalValidation(Mage_Shipping_Model_Rate_Request $request)
158
+ {
159
+ //Skip by item validation if there is no items in request
160
+ if(!count($this->getAllItems($request))) {
161
+ return $this;
162
+ }
163
+
164
+ $maxAllowedWeight = (float) $this->getConfigData('max_package_weight');
165
+ $errorMsg = '';
166
+ $configErrorMsg = $this->getConfigData('specificerrmsg');
167
+ $defaultErrorMsg = Mage::helper('shipping')->__('The shipping module is not available.');
168
+ $showMethod = $this->getConfigData('showmethod');
169
+
170
+ foreach ($this->getAllItems($request) as $item) {
171
+ if ($item->getProduct() && $item->getProduct()->getId()) {
172
+ $weight = $item->getProduct()->getWeight();
173
+ $stockItem = $item->getProduct()->getStockItem();
174
+ $doValidation = true;
175
+
176
+ if ($stockItem->getIsQtyDecimal() && $stockItem->getIsDecimalDivided()) {
177
+ if ($stockItem->getEnableQtyIncrements() && $stockItem->getQtyIncrements()) {
178
+ $weight = $weight * $stockItem->getQtyIncrements();
179
+ } else {
180
+ $doValidation = false;
181
+ }
182
+ } elseif ($stockItem->getIsQtyDecimal() && !$stockItem->getIsDecimalDivided()) {
183
+ $weight = $weight * $item->getQty();
184
+ }
185
+
186
+ if ($doValidation && $weight > $maxAllowedWeight) {
187
+ $errorMsg = ($configErrorMsg) ? $configErrorMsg : $defaultErrorMsg;
188
+ break;
189
+ }
190
+ }
191
+ }
192
+
193
+ if (!$errorMsg && !$request->getDestPostcode() && $this->isZipCodeRequired($request->getDestCountryId())) {
194
+ $errorMsg = Mage::helper('shipping')->__('This shipping method is not available, please specify ZIP-code');
195
+ }
196
+
197
+ if ($errorMsg && $showMethod) {
198
+ $error = Mage::getModel('shipping/rate_result_error');
199
+ $error->setCarrier($this->_code);
200
+ $error->setCarrierTitle($this->getConfigData('title'));
201
+ $error->setErrorMessage($errorMsg);
202
+ return $error;
203
+ } elseif ($errorMsg) {
204
+ return false;
205
+ }
206
+ return $this;
207
+ }
208
+ */
209
+ /**
210
+ * Returns cache key for some request to carrier quotes service
211
+ *
212
+ * @param string|array $requestParams
213
+ * @return string
214
+ */
215
+ protected function _getQuotesCacheKey($requestParams)
216
+ {
217
+ if (is_array($requestParams)) {
218
+ $requestParams = implode(',', array_merge(
219
+ array($this->getCarrierCode()),
220
+ array_keys($requestParams),
221
+ $requestParams)
222
+ );
223
+ }
224
+ return crc32($requestParams);
225
+ }
226
+
227
+ /**
228
+ * Checks whether some request to rates have already been done, so we have cache for it
229
+ * Used to reduce number of same requests done to carrier service during one session
230
+ *
231
+ * Returns cached response or null
232
+ *
233
+ * @param string|array $requestParams
234
+ * @return null|string
235
+ */
236
+ protected function _getCachedQuotes($requestParams)
237
+ {
238
+ $key = $this->_getQuotesCacheKey($requestParams);
239
+ return isset(self::$_quotesCache[$key]) ? self::$_quotesCache[$key] : null;
240
+ }
241
+
242
+ /**
243
+ * Sets received carrier quotes to cache
244
+ *
245
+ * @param string|array $requestParams
246
+ * @param string $response
247
+ * @return Mage_Usa_Model_Shipping_Carrier_Abstract
248
+ */
249
+ protected function _setCachedQuotes($requestParams, $response)
250
+ {
251
+ $key = $this->_getQuotesCacheKey($requestParams);
252
+ self::$_quotesCache[$key] = $response;
253
+ return $this;
254
+ }
255
+
256
+ /**
257
+ * Prepare service name. Strip tags and entities from name
258
+ *
259
+ * @param string|object $name service name or object with implemented __toString() method
260
+ * @return string prepared service name
261
+ */
262
+ protected function _prepareServiceName($name)
263
+ {
264
+ $name = html_entity_decode((string)$name);
265
+ $name = strip_tags(preg_replace('#&\w+;#', '', $name));
266
+ return trim($name);
267
+ }
268
+
269
+
270
+ public function getTrackingInfo($tracking)
271
+ {
272
+ $info = array();
273
+
274
+ $result = $this->getTracking($tracking);
275
+
276
+ if($result instanceof Mage_Shipping_Model_Tracking_Result){
277
+ if ($trackings = $result->getAllTrackings()) {
278
+ return $trackings[0];
279
+ }
280
+ }
281
+ elseif (is_string($result) && !empty($result)) {
282
+ return $result;
283
+ }
284
+
285
+ return false;
286
+ }
287
+
288
+ /**
289
+ * Get tracking
290
+ *
291
+ * @param mixed $trackings
292
+ * @return mixed
293
+ */
294
+ public function getTracking($trackings)
295
+ {
296
+ $return = array();
297
+
298
+ if (!is_array($trackings)) {
299
+ $trackings = array($trackings);
300
+ }
301
+
302
+ $this->_getCgiTracking($trackings);
303
+
304
+ return $this->_result;
305
+ }
306
+
307
+ /**
308
+ * Prepare shipment request.
309
+ * Validate and correct request information
310
+ *
311
+ * @param Varien_Object $request
312
+ *
313
+ */
314
+ protected function _prepareShipmentRequest(Varien_Object $request)
315
+ {
316
+ $phonePattern = '/[\s\_\-\(\)]+/';
317
+ $phoneNumber = $request->getShipperContactPhoneNumber();
318
+ $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
319
+ $request->setShipperContactPhoneNumber($phoneNumber);
320
+ $phoneNumber = $request->getRecipientContactPhoneNumber();
321
+ $phoneNumber = preg_replace($phonePattern, '', $phoneNumber);
322
+ $request->setRecipientContactPhoneNumber($phoneNumber);
323
+ }
324
+
325
+ /**
326
+ * Do request to shipment
327
+ *
328
+ * @param Mage_Shipping_Model_Shipment_Request $request
329
+ * @return array
330
+ */
331
+ public function requestToShipment(Mage_Shipping_Model_Shipment_Request $request)
332
+ {
333
+ $packages = $request->getPackages();
334
+ if (!is_array($packages) || !$packages) {
335
+ Mage::throwException(Mage::helper('usa')->__('No packages for request'));
336
+ }
337
+ if ($request->getStoreId() != null) {
338
+ $this->setStore($request->getStoreId());
339
+ }
340
+ $data = array();
341
+ foreach ($packages as $packageId => $package) {
342
+ $request->setPackageId($packageId);
343
+ $request->setPackagingType($package['params']['container']);
344
+ $request->setPackageWeight($package['params']['weight']);
345
+ $request->setPackageParams(new Varien_Object($package['params']));
346
+ $request->setPackageItems($package['items']);
347
+ $result = $this->_doShipmentRequest($request);
348
+
349
+ if ($result->hasErrors()) {
350
+ $this->rollBack($data);
351
+ break;
352
+ } else {
353
+ $data[] = array(
354
+ 'tracking_number' => $result->getTrackingNumber(),
355
+ 'label_content' => $result->getShippingLabelContent()
356
+ );
357
+ }
358
+ if (!isset($isFirstRequest)) {
359
+ $request->setMasterTrackingId($result->getTrackingNumber());
360
+ $isFirstRequest = false;
361
+ }
362
+ }
363
+
364
+ $response = new Varien_Object(array(
365
+ 'info' => $data
366
+ ));
367
+ if ($result->getErrors()) {
368
+ $response->setErrors($result->getErrors());
369
+ }
370
+ return $response;
371
+ }
372
+
373
+ /**
374
+ * Do request to RMA shipment
375
+ *
376
+ * @param $request
377
+ * @return array
378
+ */
379
+ public function returnOfShipment($request)
380
+ {
381
+ $request->setIsReturn(true);
382
+ $packages = $request->getPackages();
383
+ if (!is_array($packages) || !$packages) {
384
+ Mage::throwException(Mage::helper('usa')->__('No packages for request'));
385
+ }
386
+ if ($request->getStoreId() != null) {
387
+ $this->setStore($request->getStoreId());
388
+ }
389
+ $data = array();
390
+ foreach ($packages as $packageId => $package) {
391
+ $request->setPackageId($packageId);
392
+ $request->setPackagingType($package['params']['container']);
393
+ $request->setPackageWeight($package['params']['weight']);
394
+ $request->setPackageParams(new Varien_Object($package['params']));
395
+ $request->setPackageItems($package['items']);
396
+ $result = $this->_doShipmentRequest($request);
397
+
398
+ if ($result->hasErrors()) {
399
+ $this->rollBack($data);
400
+ break;
401
+ } else {
402
+ $data[] = array(
403
+ 'tracking_number' => $result->getTrackingNumber(),
404
+ 'label_content' => $result->getShippingLabelContent()
405
+ );
406
+ }
407
+ if (!isset($isFirstRequest)) {
408
+ $request->setMasterTrackingId($result->getTrackingNumber());
409
+ $isFirstRequest = false;
410
+ }
411
+ }
412
+
413
+ $response = new Varien_Object(array(
414
+ 'info' => $data
415
+ ));
416
+ if ($result->getErrors()) {
417
+ $response->setErrors($result->getErrors());
418
+ }
419
+ return $response;
420
+ }
421
+
422
+ /**
423
+ * Return container types of carrier
424
+ *
425
+ * @param Varien_Object|null $params
426
+ * @return array
427
+ */
428
+ public function getContainerTypes(Varien_Object $params = null)
429
+ {
430
+ $model = Mage::getModel('carrier/config');
431
+ if($params){
432
+ $collection = $model->getCollection()
433
+ ->addFieldToFilter('config_type',array('eq'=>'packaging'))->addFieldToFilter('apply_to',array('eq'=>$params->getMethod()));
434
+ if($collection){
435
+ $containerTypes = array();
436
+ foreach ($collection as $row){
437
+ $containerTypes[$row->getConfigKey()] = $row->getConfigValue();
438
+ }
439
+ return $containerTypes;
440
+ }else{
441
+ return array();
442
+ }
443
+ }else{
444
+ return $this->_getAllowedContainers($params);
445
+ }
446
+ return array();
447
+ }
448
+
449
+ public function rollBack($data)
450
+ {
451
+ return true;
452
+ }
453
+
454
+ protected function _doShipmentRequest(Varien_Object $request)
455
+ {
456
+ $result = new Varien_Object();
457
+ $_rawShipmentRequest = $this->_collectShipmentRequestData($request);
458
+
459
+ $quoteResult = $this->_sendRequest($this->_quote_path, $_rawShipmentRequest, true);
460
+ if($quoteResult){
461
+ if(isset($quoteResult->ErrorMessage) && $quoteResult->ErrorMessage != 'OK'){
462
+ $result->setErrors($quoteResult->ErrorMessage);
463
+ }else if($quoteResult->Estimator){
464
+ $quoteData = $quoteResult->Estimator[0];
465
+ $quoteID = $quoteData->QuoteID;
466
+ $shipmentResult = $this->_sendRequestShipment($this->_shipment_path. '/' . $quoteID);
467
+
468
+ if($shipmentResult){
469
+ $result->setShippingLabelContent(base64_decode($shipmentResult->LabelImage));
470
+ //$result->setTrackingNumber($shipmentResult->TrackingNumber);
471
+ $result->setTrackingNumber($shipmentResult->InternalTrackingNumber);
472
+
473
+ }else{
474
+ $result->setErrors(Mage::helper('sales')->__('An error occurred while creating shipping label..'));
475
+ }
476
+ }else{
477
+ $result->setErrors(Mage::helper('sales')->__('An error occurred while creating shipping label. Separate your shipment or change the package type.'));
478
+ }
479
+ }
480
+ return $result;
481
+ }
482
+
483
+ private function _collectShipmentRequestData(Varien_Object $request){
484
+ $this->_prepareShipmentRequest($request);
485
+ $user = $this->_sendRequest($this->_user_path, array(), false);
486
+ $contactId = $user->DefaultLocation;
487
+
488
+ if ($request->getShipperAddressCountryCode() != $request->getRecipientAddressCountryCode()) {
489
+ $IsResidential = false;
490
+ }else{
491
+ $IsResidential = true;
492
+ }
493
+ $packageType = $request->getPackagingType();
494
+
495
+ $CarrierCode = "2";
496
+ $model = Mage::getModel('carrier/config');
497
+ $collection = $model->getCollection()
498
+ ->addFieldToFilter('config_type',array('eq'=>'method'))->addFieldToFilter('config_key',array('eq'=>$request->getShippingMethod()));
499
+ if($collection){
500
+ $Carrier = $collection->getFirstItem()->getCarrier();
501
+ $CarrierData = $model->getCollection()
502
+ ->addFieldToFilter('config_type',array('eq'=>'carrier'))->addFieldToFilter('config_key',array('eq'=>$Carrier));
503
+ if($CarrierData){
504
+ $CarrierCode = $CarrierData->getFirstItem()->getApplyTo();
505
+ }
506
+ }
507
+ $CarrierCode = intval($CarrierCode);
508
+
509
+ $productIds = array();
510
+ $packageParams = $request->getPackageParams();
511
+ $packageItems = $request->getPackageItems();
512
+ $insured = 0;
513
+
514
+ foreach ($packageItems as $itemShipment) {
515
+ $item = new Varien_Object();
516
+ $item->setData($itemShipment);
517
+
518
+ $product = Mage::getModel('catalog/product')->load( $item->getProductId() );
519
+ if ($product->isVirtual() || $product->getParentItem()) {
520
+ continue;
521
+ }
522
+
523
+ if ($item->getHasChildren() && $item->isShipSeparately()) {
524
+ foreach ($item->getChildren() as $child) {
525
+ if (!$child->getProduct()->isVirtual()) {
526
+ $product = Mage::getModel('catalog/product')->load( $item->getProductId() );
527
+ if($product->getInsured()){
528
+ $insured += $product->getInsured() * $item->getQty();
529
+ }else if($product->getCost()){
530
+ $insured += $product->getCost() * $item->getQty();
531
+ }else{
532
+ $insured += $product->getPrice() * $item->getQty();
533
+ }
534
+ }
535
+ }
536
+ } else{
537
+ if($product->getInsured()){
538
+ $insured += $product->getInsured() * $item->getQty();
539
+ }else if($product->getCost()){
540
+ $insured += $product->getCost() * $item->getQty();
541
+ }else{
542
+ $insured += $product->getPrice() * $item->getQty();
543
+ }
544
+ }
545
+ }
546
+
547
+ // get countries of manufacture
548
+ $productCollection = Mage::getResourceModel('catalog/product_collection')
549
+ ->addStoreFilter($request->getStoreId())
550
+ ->addFieldToFilter('entity_id', array('in' => $productIds))
551
+ ->addAttributeToSelect('country_of_manufacture');
552
+ foreach ($productCollection as $product) {
553
+ $countriesOfManufacture[] = $product->getCountryOfManufacture();
554
+ }
555
+
556
+
557
+ if($this->getConfigData('saturday_pickup') == '0'){
558
+ $isSaturdayPickUp = false;
559
+ }else{
560
+ $isSaturdayPickUp = true;
561
+ }
562
+
563
+ if($this->getConfigData('saturday_delivery') == '0'){
564
+ $isSaturdayDelivery = false;
565
+ }else{
566
+ $isSaturdayDelivery = true;
567
+ }
568
+
569
+ if($this->getConfigData('delivery_confirmation') == '0'){
570
+ $isDeliveryConfirmation = false;
571
+ }else{
572
+ $isDeliveryConfirmation = true;
573
+ }
574
+
575
+ if($this->getConfigData('regular_pickup') == '0'){
576
+ $isRegularPickUp = false;
577
+ }else{
578
+ $isRegularPickUp = true;
579
+ }
580
+ if($this->getConfigData('drop_off') == '0'){
581
+ $isDropoff = false;
582
+ }else{
583
+ $isDropoff = true;
584
+ }
585
+ if($this->getConfigData('thermal_label') == '0'){
586
+ $isThermal = false;
587
+ }else{
588
+ $isThermal = true;
589
+ }
590
+
591
+ if($request->getRecipientContactCompanyName()){
592
+ $IsResidential = false;
593
+ }else{
594
+ $IsResidential = true;
595
+ }
596
+ $isDirectSignature = false;
597
+ $deliveryConfirmation = $packageParams->getDeliveryConfirmation();
598
+
599
+ if($deliveryConfirmation == 'ADULT'){
600
+ $isDeliveryConfirmation = true;
601
+ }else if($deliveryConfirmation == 'DIRECT'){
602
+ $isDirectSignature = true;
603
+ }else if($deliveryConfirmation == 'thermal_label'){
604
+ $isThermal = true;
605
+ }
606
+
607
+ if($IsResidential && $CarrierCode == 2){
608
+ $isDirectSignature = true;
609
+ }
610
+
611
+ $requestShipmentData = array(
612
+ "ShipmentId" => "NOID",
613
+ "QuoteId" => "",
614
+ "CustomerId" => "NOID",
615
+ "UserId" => "NOID",
616
+ "ShipToResidential" => $IsResidential,
617
+ "ServiceCode" => $request->getShippingMethod(),
618
+ "CarrierCode" => $CarrierCode,
619
+ "ShipTo" => array(
620
+ "ContactId" => "NOID",
621
+ "CustomerId" => "",
622
+ "UserId" => "",
623
+ "ContactType" => 11,
624
+ "CompanyName" => $request->getRecipientContactCompanyName()."",
625
+ "FirstName" => $request->getRecipientContactPersonFirstName(),
626
+ "LastName" => $request->getRecipientContactPersonLastName(),
627
+ "StreetAddress" => $request->getRecipientAddressStreet1(),
628
+ "ApartmentSuite" => "",
629
+ "ProvinceRegion" => "",
630
+ "City" => $request->getRecipientAddressCity(),
631
+ "State" => $request->getRecipientAddressStateOrProvinceCode(),
632
+ "Country" => $request->getRecipientAddressCountryCode(),
633
+ "Zip" => $request->getRecipientAddressPostalCode(),
634
+ "TelephoneNo" => $request->getRecipientContactPhoneNumber(),
635
+ "FaxNo" => "",
636
+ "Email" => $request->getOrderShipment()->getOrder()->getCustomerEmail(),
637
+ "NickName" => "",
638
+ "IsExpress" => false,
639
+ "IsResidential" => $IsResidential,
640
+ "IsUserDefault" => false,
641
+ "UPSPickUpType" => 0,
642
+ "TotalContacts" => "0"
643
+ ),
644
+ "UpdateAddressBook" => false,
645
+ "NotifyRecipient" => false,
646
+ "ShipFrom" => array(
647
+ "ContactId" => $contactId,
648
+ //"ContactId" => "NOID",
649
+ "CustomerId" => "",
650
+ "UserId" => "",
651
+ "ContactType" => 3,
652
+ "CompanyName" => "",
653
+ "FirstName" => "",
654
+ "LastName" => "",
655
+ "StreetAddress" => "",
656
+ "ApartmentSuite" => "",
657
+ "ProvinceRegion" => "",
658
+ "City" => "",
659
+ "State" => "",
660
+ "Country" => "",
661
+ "Zip" => "",
662
+ "TelephoneNo" => "",
663
+ "FaxNo" => "",
664
+ "Email" => "",
665
+ "NickName" => "",
666
+ "IsExpress" => false,
667
+ "IsResidential" => false,
668
+ "IsUserDefault" => false,
669
+ "UPSPickUpType" => 0,
670
+ "TotalContacts" => "0"
671
+ ),
672
+ "ShipDate" => date("Y-m-d"), //"2014-04-13",
673
+ "PackageCode" => $request->getPackagingType(),
674
+ "Height" => $packageParams->getHeight()?$packageParams->getHeight():0,
675
+ "Width" => $packageParams->getWidth()?$packageParams->getWidth():0,
676
+ "Length" => $packageParams->getLength()?$packageParams->getLength():0,
677
+ "Weight" => $request->getPackageWeight()?floatval($request->getPackageWeight()):0,
678
+ "InsuredValue" => $insured,
679
+ "IsSaturdayPickUp" => $isSaturdayPickUp,
680
+ "IsSaturdayDelivery" => $isSaturdayDelivery,
681
+ "IsDeliveryConfirmation" => $isDeliveryConfirmation,
682
+ //"IsCod" => false,
683
+ //"CodAmount" => 0.0,
684
+ "IsSecuredCod" => false,
685
+ "IsRegularPickUp" => $isRegularPickUp,
686
+ "IsDropoff" => $isDropoff,
687
+ "IsPickUpRequested" => false,
688
+ "IsSmartPickUp" => false,
689
+ "PickUpContactName" => "",
690
+ "PickUpTelephone" => "",
691
+ "PickUpAtHour" => "",
692
+ "PickUpAtMinute" => "",
693
+ "PickUpByHour" => "",
694
+ "PickUpByMinute" => "",
695
+ "PickUpDate" => "",
696
+ "DispatchConfirmationNumber" => "",
697
+ "DispatchLocation" => "",
698
+ "NotifySender" => false,
699
+ "ReferenceNumber" => "",
700
+ "TrackingNumber" => "",
701
+ "CustomerReferenceNumber" => "",
702
+ "IsDirectSignature" => $isDirectSignature,
703
+ "IsThermal" => $isThermal,
704
+ "IsMaxCoverageExceeded" => false,
705
+ "Estimator" => array(
706
+
707
+ ),
708
+ "LabelImage" => null,
709
+ "IsBillToThirdParty" => false,
710
+ "BillToThirdPartyPostalCode" => "",
711
+ "BillToAccount" => "",
712
+ "IsShipFromRestrictedZip" => false,
713
+ "IsShipToRestrictedZip" => false,
714
+ "IsShipToHasRestrictedWords" => false,
715
+ "IsShipFromHasRestrictedWords" => false,
716
+ "IsHighValueShipment" => false,
717
+ "IsHighValueReport" => false,
718
+ "ReceivedBy" => "",
719
+ "ReceivedTime" => "",
720
+ "TotalShipments" => "0"
721
+ );
722
+ //echo json_encode($requestShipmentData);
723
+ return $requestShipmentData;
724
+ }
725
+
726
+ /**
727
+ * Get cgi tracking
728
+ *
729
+ * @param mixed $trackings
730
+ * @return mixed
731
+ */
732
+ protected function _getCgiTracking($trackings)
733
+ {
734
+ //ups no longer support tracking for data streaming version
735
+ //so we can only reply the popup window to ups.
736
+ $result = Mage::getModel('shipping/tracking_result');
737
+ $defaults = $this->getDefaults();
738
+ foreach($trackings as $tracking){
739
+ $status = Mage::getModel('shipping/tracking_result_status');
740
+ $status->setCarrier($this->_code);
741
+ $status->setCarrierTitle($this->getConfigData('title'));
742
+ $status->setTracking($tracking);
743
+ $status->setPopup(1);
744
+ $status->setUrl("http://notify.parcelpro.com/track/$tracking");
745
+ $result->append($status);
746
+ }
747
+
748
+ $this->_result = $result;
749
+ return $result;
750
+ }
751
+
752
+ /**
753
+ * Get result of request
754
+ *
755
+ * @return mixed
756
+ */
757
+ public function getResult()
758
+ {
759
+ return $this->_result;
760
+ }
761
+
762
+ /**
763
+ * Return delivery confirmation types of carrier
764
+ *
765
+ * @param Varien_Object|null $params
766
+ * @return array
767
+ */
768
+ public function getDeliveryConfirmationTypes(Varien_Object $params = null)
769
+ {
770
+ $shipment = Mage::registry('current_shipment');
771
+ if($shipment){
772
+ $order = $shipment->getOrder();
773
+ $model = Mage::getModel('carrier/config');
774
+ $collection = $model->getCollection()
775
+ ->addFieldToFilter('config_type',array('eq'=>'method'))->addFieldToFilter('config_key',array('eq'=>str_replace("parcelpro_", "", $order->getShippingMethod())));
776
+ if($collection){
777
+ if(count($collection) == 1){
778
+ $carrier = $collection;
779
+ }else{
780
+ $carrier = $collection[0];
781
+ }
782
+
783
+ if($carrier->carrier == 'UPS'){
784
+ return array(
785
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
786
+ 'ADULT' => Mage::helper('usa')->__('Adult Signature'),
787
+ );
788
+ }else{
789
+ return array(
790
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
791
+ 'DIRECT' => Mage::helper('usa')->__('Direct Signature'),
792
+ );
793
+ }
794
+ }else{
795
+ return array(
796
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
797
+ 'ADULT' => Mage::helper('usa')->__('Adult Signature'),
798
+ 'DIRECT' => Mage::helper('usa')->__('Direct Signature'),
799
+ );
800
+ }
801
+
802
+ }else{
803
+ return array(
804
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
805
+ 'ADULT' => Mage::helper('usa')->__('Adult Signature'),
806
+ 'DIRECT' => Mage::helper('usa')->__('Direct Signature'),
807
+ );
808
+ }
809
+ }
810
+
811
+ /**
812
+ * Get configuration data of carrier
813
+ *
814
+ * @param string $type
815
+ * @param string $code
816
+ * @return array|bool
817
+ */
818
+ public function getCode($type, $carrier='')
819
+ {
820
+ /*
821
+ $codes = array(
822
+ 'method' => array(
823
+ '01' => Mage::helper('usa')->__('Next Day Air'),
824
+ '02' => Mage::helper('usa')->__('2nd Day Air'),
825
+ '01-INT' => Mage::helper('usa')->__('International Priority'),
826
+ '01-DOM' => Mage::helper('usa')->__('Priority Overnight'),
827
+ '03-DOM' => Mage::helper('usa')->__('2 Day'),
828
+ '05' => Mage::helper('usa')->__('Standard Overnight'),
829
+ ),
830
+ 'dropoff' => array(
831
+ 'REGULAR_PICKUP' => Mage::helper('usa')->__('Regular Pickup'),
832
+ 'REQUEST_COURIER' => Mage::helper('usa')->__('Request Courier'),
833
+ 'DROP_BOX' => Mage::helper('usa')->__('Drop Box'),
834
+ 'BUSINESS_SERVICE_CENTER' => Mage::helper('usa')->__('Business Service Center'),
835
+ 'STATION' => Mage::helper('usa')->__('Station')
836
+ ),
837
+ 'packaging' => array(
838
+ '25' => Mage::helper('usa')->__('10KG BOX'),
839
+ '24' => Mage::helper('usa')->__('25KG BOX'),
840
+ '21' => Mage::helper('usa')->__('EXPRESS BOX'),
841
+ '01' => Mage::helper('usa')->__('LETTER'),
842
+ '04' => Mage::helper('usa')->__('PAK'),
843
+ '03' => Mage::helper('usa')->__('TUBE'),
844
+ 'LARGE BOX' => Mage::helper('usa')->__('LARGE FEDEX BOX'),
845
+ 'MEDIUM BOX' => Mage::helper('usa')->__('MEDIUM FEDEX BOX'),
846
+ 'SMALL BOX' => Mage::helper('usa')->__('SMALL FEDEX BOX'),
847
+ '02' => Mage::helper('usa')->__('Your Packaging...')
848
+ ),
849
+ 'containers_filter' => array(
850
+ array(
851
+ 'containers' => array('FEDEX_ENVELOPE', 'FEDEX_PAK'),
852
+ 'filters' => array(
853
+ 'within_us' => array(
854
+ 'method' => array(
855
+ 'FEDEX_EXPRESS_SAVER',
856
+ 'FEDEX_2_DAY',
857
+ 'FEDEX_2_DAY_AM',
858
+ 'STANDARD_OVERNIGHT',
859
+ 'PRIORITY_OVERNIGHT',
860
+ 'FIRST_OVERNIGHT',
861
+ )
862
+ ),
863
+ 'from_us' => array(
864
+ 'method' => array(
865
+ 'INTERNATIONAL_FIRST',
866
+ 'INTERNATIONAL_ECONOMY',
867
+ 'INTERNATIONAL_PRIORITY',
868
+ )
869
+ )
870
+ )
871
+ ),
872
+ array(
873
+ 'containers' => array('FEDEX_BOX', 'FEDEX_TUBE'),
874
+ 'filters' => array(
875
+ 'within_us' => array(
876
+ 'method' => array(
877
+ 'FEDEX_2_DAY',
878
+ 'FEDEX_2_DAY_AM',
879
+ 'STANDARD_OVERNIGHT',
880
+ 'PRIORITY_OVERNIGHT',
881
+ 'FIRST_OVERNIGHT',
882
+ 'FEDEX_FREIGHT',
883
+ 'FEDEX_1_DAY_FREIGHT',
884
+ 'FEDEX_2_DAY_FREIGHT',
885
+ 'FEDEX_3_DAY_FREIGHT',
886
+ 'FEDEX_NATIONAL_FREIGHT',
887
+ )
888
+ ),
889
+ 'from_us' => array(
890
+ 'method' => array(
891
+ 'INTERNATIONAL_FIRST',
892
+ 'INTERNATIONAL_ECONOMY',
893
+ 'INTERNATIONAL_PRIORITY',
894
+ )
895
+ )
896
+ )
897
+ ),
898
+ array(
899
+ 'containers' => array('FEDEX_10KG_BOX', 'FEDEX_25KG_BOX'),
900
+ 'filters' => array(
901
+ 'within_us' => array(),
902
+ 'from_us' => array('method' => array('INTERNATIONAL_PRIORITY'))
903
+ )
904
+ ),
905
+ array(
906
+ 'containers' => array('YOUR_PACKAGING'),
907
+ 'filters' => array(
908
+ 'within_us' => array(
909
+ 'method' =>array(
910
+ 'FEDEX_GROUND',
911
+ 'GROUND_HOME_DELIVERY',
912
+ 'SMART_POST',
913
+ 'FEDEX_EXPRESS_SAVER',
914
+ 'FEDEX_2_DAY',
915
+ 'FEDEX_2_DAY_AM',
916
+ 'STANDARD_OVERNIGHT',
917
+ 'PRIORITY_OVERNIGHT',
918
+ 'FIRST_OVERNIGHT',
919
+ 'FEDEX_FREIGHT',
920
+ 'FEDEX_1_DAY_FREIGHT',
921
+ 'FEDEX_2_DAY_FREIGHT',
922
+ 'FEDEX_3_DAY_FREIGHT',
923
+ 'FEDEX_NATIONAL_FREIGHT',
924
+ )
925
+ ),
926
+ 'from_us' => array(
927
+ 'method' =>array(
928
+ 'INTERNATIONAL_FIRST',
929
+ 'INTERNATIONAL_ECONOMY',
930
+ 'INTERNATIONAL_PRIORITY',
931
+ 'INTERNATIONAL_GROUND',
932
+ 'FEDEX_FREIGHT',
933
+ 'FEDEX_1_DAY_FREIGHT',
934
+ 'FEDEX_2_DAY_FREIGHT',
935
+ 'FEDEX_3_DAY_FREIGHT',
936
+ 'FEDEX_NATIONAL_FREIGHT',
937
+ 'INTERNATIONAL_ECONOMY_FREIGHT',
938
+ 'INTERNATIONAL_PRIORITY_FREIGHT',
939
+ )
940
+ )
941
+ )
942
+ )
943
+ ),
944
+
945
+ 'delivery_confirmation_types' => array(
946
+ 'NO_SIGNATURE_REQUIRED' => Mage::helper('usa')->__('Not Required'),
947
+ 'ADULT' => Mage::helper('usa')->__('Adult'),
948
+ 'DIRECT' => Mage::helper('usa')->__('Direct'),
949
+ 'INDIRECT' => Mage::helper('usa')->__('Indirect'),
950
+ ),
951
+
952
+ 'unit_of_measure'=>array(
953
+ 'LB' => Mage::helper('usa')->__('Pounds'),
954
+ 'KG' => Mage::helper('usa')->__('Kilograms'),
955
+ ),
956
+ );
957
+ */
958
+ $model = Mage::getModel('carrier/config');
959
+ if($carrier){
960
+ $collection = $model->getCollection()
961
+ ->addFieldToFilter('config_type',array('eq'=>$type))->addFieldToFilter('carrier',array('eq'=>$carrier));
962
+ }else{
963
+ $collection = $model->getCollection()
964
+ ->addFieldToFilter('config_type',array('eq'=>$type));
965
+ }
966
+ if($collection){
967
+ $data = array();
968
+ foreach ($collection as $row){
969
+ $data[$row->getConfigKey()] = $row->getConfigValue();
970
+ }
971
+ return $data;
972
+ }else{
973
+ return null;
974
+ }
975
+
976
+ }
977
+ private function _parseShippingRates($estimatorData){
978
+ if(!isset( $estimatorData->Estimator)){
979
+ return null;
980
+ }
981
+
982
+ $allowed_carriers = explode(',', strtoupper($this->getConfigData('allowed_carriers')));
983
+ $estimatorList = $estimatorData->Estimator;
984
+ if($estimatorList){
985
+ $allowedMethods = $this->getAllowedMethods();
986
+ if($allowedMethods){
987
+ $alloewdMethodIds = array();
988
+
989
+ foreach ($allowedMethods as $key => $val){
990
+ $alloewdMethodIds[] = $key;
991
+ }
992
+
993
+ $rateList = array();
994
+ foreach ($estimatorList as $estimator){
995
+ if(in_array($estimator->ServiceCode, $alloewdMethodIds) && in_array(strtoupper($estimator->CarrierCode), $allowed_carriers) ){
996
+ $rate = Mage::getModel('shipping/rate_result_method');
997
+ /* @var $rate Mage_Shipping_Model_Rate_Result_Method */
998
+
999
+ $rate->setCarrier($this->_code);
1000
+ $rate->setCarrierTitle($this->getConfigData('title'));
1001
+
1002
+ $rate->setMethod($estimator->ServiceCode);
1003
+ $rate->setMethodTitle($estimator->ServiceCodeDescription);
1004
+
1005
+ $rate->setPrice($estimator->TotalCharges);
1006
+ $rate->setCost($estimator->AccessorialsCost);
1007
+
1008
+ $rateList[] = $rate;
1009
+ }
1010
+ }
1011
+ return $rateList;
1012
+ }else{
1013
+ return null;
1014
+ }
1015
+ }else{
1016
+ return null;
1017
+ }
1018
+ }
1019
+
1020
+ private function _collectRequestData($request){
1021
+ //Mage::log($request->debug());
1022
+ $_rawRequest = array();
1023
+
1024
+ $insured = 0;
1025
+ if ($request->getAllItems()) {
1026
+ foreach ($request->getAllItems() as $item) {
1027
+ $product = Mage::getModel('catalog/product')->load( $item->getProductId() );
1028
+ if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
1029
+ continue;
1030
+ }
1031
+
1032
+ if ($item->getHasChildren() && $item->isShipSeparately()) {
1033
+ foreach ($item->getChildren() as $child) {
1034
+ if (!$child->getProduct()->isVirtual()) {
1035
+ $product = Mage::getModel('catalog/product')->load( $item->getProductId() );
1036
+ if($product->getInsured()){
1037
+ $insured += $product->getInsured() * $item->getQty();
1038
+ }else if($product->getCost()){
1039
+ $insured += $product->getCost() * $item->getQty();
1040
+ }else{
1041
+ $insured += $product->getPrice() * $item->getQty();
1042
+ }
1043
+ }
1044
+ }
1045
+ } else{
1046
+ if($product->getInsured()){
1047
+ $insured += $product->getInsured() * $item->getQty();
1048
+ }else if($product->getCost()){
1049
+ $insured += $product->getCost() * $item->getQty();
1050
+ }else{
1051
+ $insured += $product->getPrice() * $item->getQty();
1052
+ }
1053
+ }
1054
+ }
1055
+ }
1056
+
1057
+ $user = $this->_sendRequest($this->_user_path, array(), false);
1058
+ $contactId = $user->DefaultLocation;
1059
+
1060
+ if($this->getConfigData('saturday_pickup') == '0'){
1061
+ $isSaturdayPickUp = false;
1062
+ }else{
1063
+ $isSaturdayPickUp = true;
1064
+ }
1065
+
1066
+ if($this->getConfigData('saturday_delivery') == '0'){
1067
+ $isSaturdayDelivery = false;
1068
+ }else{
1069
+ $isSaturdayDelivery = true;
1070
+ }
1071
+
1072
+ if($this->getConfigData('delivery_confirmation') == '0'){
1073
+ $isDeliveryConfirmation = false;
1074
+ }else{
1075
+ $isDeliveryConfirmation = true;
1076
+ }
1077
+
1078
+ if($this->getConfigData('regular_pickup') == '0'){
1079
+ $isRegularPickUp = false;
1080
+ }else{
1081
+ $isRegularPickUp = true;
1082
+ }
1083
+ if($this->getConfigData('drop_off') == '0'){
1084
+ $isDropoff = false;
1085
+ }else{
1086
+ $isDropoff = true;
1087
+ }
1088
+
1089
+ $_rawRequest = array(
1090
+ //"ShipToResidential" => false,
1091
+ "ShipTo" => array(
1092
+ "ContactId" => "NOID",
1093
+ "CustomerId" => "",
1094
+ "UserId" => "",
1095
+ "ContactType" =>3,
1096
+ "CompanyName" => "",
1097
+ "FirstName" => "",
1098
+ "LastName" => "",
1099
+ "StreetAddress" => $request->getDestStreet()?$request->getDestStreet(): "",
1100
+ "ApartmentSuite" => "",
1101
+ "ProvinceRegion" => $request->getDestRegionCode()?$request->getDestRegionCode():"",
1102
+ "City" => $request->getDestCity()?$request->getDestCity():"",
1103
+ "State" => $request->getDestRegionCode()?$request->getDestRegionCode():"",
1104
+ "Country" => $request->getDestCountryId(),
1105
+ "Zip" => $request->getDestPostcode(),
1106
+ "TelephoneNo" => '',
1107
+ "FaxNo" => "",
1108
+ "Email" => "",
1109
+ "NickName" => "",
1110
+ "IsExpress" => false,
1111
+ "IsResidential" => false,
1112
+ "IsUserDefault" =>false,
1113
+ "UPSPickUpType" => 0,
1114
+ "TotalContacts" => "0"
1115
+ ),
1116
+ "ShipFrom" => array(
1117
+ //"ContactId" => "NOID",
1118
+ "ContactId" => $contactId,
1119
+ "CustomerId" => "",
1120
+ "UserId" => "",
1121
+ "ContactType" => 3,
1122
+ "CompanyName" => "",
1123
+ "FirstName" => "",
1124
+ "LastName" => "",
1125
+ "StreetAddress" => "",
1126
+ "ApartmentSuite" => "",
1127
+ "ProvinceRegion" => "",
1128
+ "City" => "",
1129
+ "State" => "",
1130
+ "Country" => "",
1131
+ "Zip" => "",
1132
+ "TelephoneNo" => "",
1133
+ "FaxNo" => "",
1134
+ "Email" => "",
1135
+ "NickName" => "",
1136
+ "IsExpress" => false,
1137
+ "IsResidential" => false,
1138
+ "IsUserDefault" => false,
1139
+ "UPSPickUpType" => 0,
1140
+ "TotalContacts" => "0"
1141
+ ),
1142
+ "Height" => $request->getPackageHeight()?$request->getPackageHeight(): 0,
1143
+ "Width" => $request->getPackageWidth()?$request->getPackageWidth():0,
1144
+ "Length" => $request->getPackageDepth()?$request->getPackageDepth():0,
1145
+ "Weight" => $request->getPackageWeight()?$request->getPackageWeight():0,
1146
+ "InsuredValue" => $insured,
1147
+ "IsSaturdayPickUp" => $isSaturdayPickUp,
1148
+ "IsSaturdayDelivery" => $isSaturdayDelivery,
1149
+ "IsDeliveryConfirmation" => $isDeliveryConfirmation,
1150
+ //"IsCod" => false,
1151
+ //"CodAmount" => 0.0,
1152
+ "PackageCode" => $this->getConfigData('packaging'),
1153
+ "IsSecuredCod" => false,
1154
+ "IsRegularPickUp" => $isRegularPickUp,
1155
+ "IsDropoff" => $isDropoff,
1156
+ );
1157
+ //Mage::log(json_encode($_rawRequest));
1158
+ return $_rawRequest;
1159
+ }
1160
+
1161
+ private function _sendRequestShipment($requestPath){
1162
+ if(!$this->_sessionId){
1163
+ $this->_getSessionId();
1164
+ }
1165
+
1166
+ if($this->_sessionId){
1167
+ $url = $this->_base_url . $this->_version . $requestPath . '?sessionID=' . $this->_sessionId;
1168
+ $ch = curl_init();
1169
+ curl_setopt($ch, CURLOPT_URL, $url);
1170
+ curl_setopt($ch, CURLOPT_POST, 1);
1171
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1172
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1173
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
1174
+ 'Content-Type: application/xml',
1175
+ 'Content-Length: 0'
1176
+ )
1177
+ );
1178
+
1179
+ $data = curl_exec ($ch);
1180
+ curl_close ($ch);
1181
+ if($data){
1182
+ $result = json_encode(simplexml_load_string($data));
1183
+ return json_decode($result, false);
1184
+ }else{
1185
+ return null;
1186
+ }
1187
+ }else{
1188
+ return null;
1189
+ }
1190
+ }
1191
+ private function _sendRequest($requestPath, $parrams, $isPost = false){
1192
+ if(!$this->_sessionId){
1193
+ $this->_getSessionId();
1194
+ }
1195
+
1196
+ if($this->_sessionId){
1197
+ $url = $this->_base_url . $this->_version . $requestPath . '?sessionID=' . $this->_sessionId;
1198
+ $ch = curl_init();
1199
+ curl_setopt($ch, CURLOPT_URL, $url);
1200
+ if($isPost){
1201
+ curl_setopt($ch, CURLOPT_POST, 1);
1202
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parrams));
1203
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
1204
+ 'Content-Type: application/json',
1205
+ 'Content-Length: ' . strlen(json_encode($parrams)))
1206
+ );
1207
+ }else{
1208
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
1209
+ 'Content-Type: application/json',
1210
+ )
1211
+ );
1212
+ }
1213
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1214
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1215
+ curl_setopt($ch, CURLOPT_HEADER, true);
1216
+
1217
+ $data = curl_exec ($ch);
1218
+ list($header,$data) = explode("\r\n\r\n",$data,2);
1219
+ $header = explode("\r\n",$header);
1220
+ $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1221
+ curl_close ($ch);
1222
+ if($http_status == '400'){
1223
+ Mage::log("Query failed:".explode(" ",$header[0])[3],null,'ppimagento.log');
1224
+ }
1225
+ if($data){
1226
+ if($requestPath == $this->_quote_path){
1227
+ //echo $url;
1228
+ //echo $data;
1229
+ //var_dump($data);
1230
+ }
1231
+ if($isPost){
1232
+ $result = json_decode($data);
1233
+ }else{
1234
+ $result = json_decode($data);
1235
+ }
1236
+ return $result;
1237
+ }else{
1238
+ return null;
1239
+ }
1240
+ }else{
1241
+ return null;
1242
+ }
1243
+ }
1244
+ private function _getSessionId(){
1245
+ $model = Mage::getModel('carrier/config');
1246
+ $collection = $model->getCollection()
1247
+ ->addFieldToFilter('config_type',array('eq'=>'session_id'));
1248
+ if($collection->count()){
1249
+ $item = $collection->getFirstItem();
1250
+ if($this->_checkInvalideSession($item->getConfigValue())){
1251
+ $this->_sessionId = $item->getConfigValue();
1252
+ return $item->getConfigValue();
1253
+ }else{
1254
+ $item->delete();
1255
+ }
1256
+ }
1257
+
1258
+ $username = Mage::helper('core')->decrypt($this->getConfigData('account'));
1259
+ $password = Mage::helper('core')->decrypt($this->getConfigData('password'));
1260
+ $apikey = Mage::helper('core')->decrypt($this->getConfigData('key'));
1261
+
1262
+ $ch = curl_init();
1263
+ $auth_url = $this->_base_url . $this->_version . $this->_auth_path;
1264
+ $auth_url .= '?username='.$username.'&password='.$password.'&apikey='.$apikey;
1265
+
1266
+ curl_setopt($ch, CURLOPT_URL, $auth_url);
1267
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1268
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1269
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array(
1270
+ 'Content-Type: application/json',
1271
+ )
1272
+ );
1273
+
1274
+ $authData = curl_exec ($ch);
1275
+ curl_close ($ch);
1276
+ if($authData){
1277
+ $result = json_decode($authData);
1278
+ $this->_sessionId = $result->SessionID;
1279
+ $this->_checkInvalideSession($result->SessionID);
1280
+
1281
+ $model->setCarrier("")
1282
+ ->setConfigType('session_id')
1283
+ ->setConfigKey('session_id')
1284
+ ->setConfigValue($result->SessionID)
1285
+ ->save();
1286
+ $model->unsetData();
1287
+
1288
+ return $result->SessionID;
1289
+ }else{
1290
+ return false;
1291
+ }
1292
+ }
1293
+
1294
+ private function _checkInvalideSession($sessionId){
1295
+ if($sessionId == null || $sessionId == ""){
1296
+ return false;
1297
+ }
1298
+ $ch = curl_init();
1299
+ $location_url = $this->_base_url . $this->_version . $this->_location_path;
1300
+ $location_url .= '?sessionID=' . $sessionId;
1301
+
1302
+ curl_setopt($ch, CURLOPT_URL, $location_url);
1303
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1304
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1305
+ $locationData = curl_exec ($ch);
1306
+ $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1307
+ curl_close ($ch);
1308
+ if($http_status == '401'){
1309
+ return false;
1310
+ }else{
1311
+ return true;
1312
+ }
1313
+ }
1314
+ }
app/code/community/ParcelPro/Carrier/etc/config.xml CHANGED
@@ -88,7 +88,7 @@
88
  <!--
89
  The title as referenced in the carrier class
90
  -->
91
- <title>Parcel Pro</title>
92
  <!--
93
  The sort order specifies the position that
94
  this carrier appears relative to the other
88
  <!--
89
  The title as referenced in the carrier class
90
  -->
91
+ <title>Parcel Pro Carrier</title>
92
  <!--
93
  The sort order specifies the position that
94
  this carrier appears relative to the other
package.xml CHANGED
@@ -1,14 +1,17 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>ParcelPro_Carrier</name>
4
- <version>1.0.1</version>
5
  <stability>stable</stability>
6
  <license uri="https://www.mozilla.org/MPL/2.0/">MPL 2.0</license>
7
  <channel>community</channel>
8
  <extends/>
9
  <summary>Parcel Pro for Magento is a web-based Insured Shipping solution that integrates with your Magento online store, adding Parcel Pro as one of your shipping options. It allows you to set the price of shipping and insurance coverage quickly and easily.</summary>
10
  <description>Parcel Pro for Magento is a web-based Insured Shipping solution that integrates with your Magento online store. It adds Parcel Pro as one of your shipping options, allowing you to set the price of shipping and insurance coverage easily. You must have a Magento store. By having Parcel Pro for Magento installed into your Magento store, you&#x2019;ll have a powerful new option for your customers to choose from when selecting Insured Shipping. With solid integration with your favorite carriers, Parcel Pro for Magento lets your customers check out in a breeze, with the costs of shipping and insurance embedded into your price.</description>
11
- <notes>Version 1.0.1&#xD;
 
 
 
12
  Actually use default location for ShipFrom&#xD;
13
  Some error logging added&#xD;
14
  &#xD;
@@ -16,8 +19,8 @@ Version 1.0.0&#xD;
16
  New release.</notes>
17
  <authors><author><name>Parcel Pro, Inc.</name><user>ParcelProInc</user><email>techsupport@parcelpro.com</email></author></authors>
18
  <date>2014-09-23</date>
19
- <time>21:19:30</time>
20
- <contents><target name="magecommunity"><dir name="ParcelPro"><dir name="Carrier"><dir name="Block"><dir name="Adminhtml"><dir name="Button"><dir name="Refresh"><file name="Cms.php" hash="4e17c2e2488321dec06785af3b3c3706"/></dir></dir></dir></dir><dir name="Helper"><file name="Parcelpro.php" hash="274e40cd23bb5ef6fcaaa2b01004c2dd"/></dir><dir name="Model"><file name="Carrier.php" hash="8d76613b4d87785722534a63ba22e1a3"/><file name="Config.php" hash="1a524a99e831bcbad22ffd50316aec44"/><dir name="Mysql4"><dir name="Config"><file name="Collection.php" hash="60720e05a974b362891d4dba01694132"/></dir><file name="Config.php" hash="ac407fcd7973e28342bc99a24fad7b4a"/></dir><dir name="Resource"><dir name="Mysql4"><file name="Setup.php" hash="4c6b2c661d616ccce831185d30cc340e"/></dir></dir><dir name="Source"><file name="Carriers.php" hash="fbae840c7a2bb07d36f61aab7cf4d960"/><file name="Dropoff.php" hash="ab1c1c54e22ed3f1c628cd2f34b50ea8"/><file name="Fedexmethod.php" hash="1966f6b0e4cb1f5a8cbb8be5a2b38981"/><file name="Freemethod.php" hash="2f590b14abae6718abdd8ab1ebbca2b8"/><file name="Packaging.php" hash="85e5e9416c4ba68bedd12558edafe384"/><file name="Unitofmeasure.php" hash="4048107787504d7aef1b662de777e93d"/><file name="Upsmethod.php" hash="4eed70c1e0f051622251377dd2ffe050"/></dir></dir><dir name="controllers"><dir name="Adminhtml"><file name="RefreshController.php" hash="01dc45dd06e8af8968cce7fbaa554cb9"/></dir><file name="IndexController.php" hash="dd116c50612320505894e151b43a8fcc"/></dir><dir name="etc"><file name="config.xml" hash="81cec73e236e689be83576e56cb8ae98"/><file name="system.xml" hash="25e4b2b1e7c61b4bf55d5015d5cab0df"/></dir><dir name="sql"><dir name="carrier_setup"><file name="mysql4-install-1.0.0.php" hash="42faff48ed0752ba42739316ac02e890"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="ParcelPro_Carrier.xml" hash=""/></dir></target></contents>
21
  <compatible/>
22
  <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php></required></dependencies>
23
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>ParcelPro_Carrier</name>
4
+ <version>1.0.2</version>
5
  <stability>stable</stability>
6
  <license uri="https://www.mozilla.org/MPL/2.0/">MPL 2.0</license>
7
  <channel>community</channel>
8
  <extends/>
9
  <summary>Parcel Pro for Magento is a web-based Insured Shipping solution that integrates with your Magento online store, adding Parcel Pro as one of your shipping options. It allows you to set the price of shipping and insurance coverage quickly and easily.</summary>
10
  <description>Parcel Pro for Magento is a web-based Insured Shipping solution that integrates with your Magento online store. It adds Parcel Pro as one of your shipping options, allowing you to set the price of shipping and insurance coverage easily. You must have a Magento store. By having Parcel Pro for Magento installed into your Magento store, you&#x2019;ll have a powerful new option for your customers to choose from when selecting Insured Shipping. With solid integration with your favorite carriers, Parcel Pro for Magento lets your customers check out in a breeze, with the costs of shipping and insurance embedded into your price.</description>
11
+ <notes>Version 1.0.2&#xD;
12
+ Improved logging&#xD;
13
+ &#xD;
14
+ Version 1.0.1&#xD;
15
  Actually use default location for ShipFrom&#xD;
16
  Some error logging added&#xD;
17
  &#xD;
19
  New release.</notes>
20
  <authors><author><name>Parcel Pro, Inc.</name><user>ParcelProInc</user><email>techsupport@parcelpro.com</email></author></authors>
21
  <date>2014-09-23</date>
22
+ <time>21:47:04</time>
23
+ <contents><target name="magecommunity"><dir name="ParcelPro"><dir name="Carrier"><dir name="Block"><dir name="Adminhtml"><dir name="Button"><dir name="Refresh"><file name="Cms.php" hash="4e17c2e2488321dec06785af3b3c3706"/></dir></dir></dir></dir><dir name="Helper"><file name="Parcelpro.php" hash="9694e1ad02c00e31df2c6435e3b84e7f"/><file name="Parcelpro.php~" hash="3a81bf4729e365f752b04bcf6a4031f1"/></dir><dir name="Model"><file name="Carrier.php" hash="4997bdd0cc7cb2a15d3f83419dfd3a52"/><file name="Carrier.php~" hash="184781b8dbc7552cfa2bd86c22bae184"/><file name="Config.php" hash="1a524a99e831bcbad22ffd50316aec44"/><dir name="Mysql4"><dir name="Config"><file name="Collection.php" hash="60720e05a974b362891d4dba01694132"/></dir><file name="Config.php" hash="ac407fcd7973e28342bc99a24fad7b4a"/></dir><dir name="Resource"><dir name="Mysql4"><file name="Setup.php" hash="4c6b2c661d616ccce831185d30cc340e"/></dir></dir><dir name="Source"><file name="Carriers.php" hash="fbae840c7a2bb07d36f61aab7cf4d960"/><file name="Dropoff.php" hash="ab1c1c54e22ed3f1c628cd2f34b50ea8"/><file name="Fedexmethod.php" hash="1966f6b0e4cb1f5a8cbb8be5a2b38981"/><file name="Freemethod.php" hash="2f590b14abae6718abdd8ab1ebbca2b8"/><file name="Packaging.php" hash="85e5e9416c4ba68bedd12558edafe384"/><file name="Unitofmeasure.php" hash="4048107787504d7aef1b662de777e93d"/><file name="Upsmethod.php" hash="4eed70c1e0f051622251377dd2ffe050"/></dir></dir><dir name="controllers"><dir name="Adminhtml"><file name="RefreshController.php" hash="01dc45dd06e8af8968cce7fbaa554cb9"/></dir><file name="IndexController.php" hash="dd116c50612320505894e151b43a8fcc"/></dir><dir name="etc"><file name="config.xml" hash="2e9655e356b5609e5b50f90c94bb79df"/><file name="system.xml" hash="25e4b2b1e7c61b4bf55d5015d5cab0df"/></dir><dir name="sql"><dir name="carrier_setup"><file name="mysql4-install-1.0.0.php" hash="42faff48ed0752ba42739316ac02e890"/></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="ParcelPro_Carrier.xml" hash=""/></dir></target></contents>
24
  <compatible/>
25
  <dependencies><required><php><min>5.1.0</min><max>6.0.0</max></php></required></dependencies>
26
  </package>