-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommerce_shipstation.module
310 lines (279 loc) · 11.5 KB
/
commerce_shipstation.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
/**
* @file
*
* Contains primary functions for the Commerce Shipstation module.
*/
/**
* Implements hook_help().
*/
function commerce_shipstation_help($path, $arg) {
switch ($path) {
case 'admin/commerce/config/fulfilment/shipstation':
return t('This module provides integration with ShipStation using the !url.
To connect your store to ShipStation using this service, fill in
the "URL to custom XML page" field in the Custom Store Setup dialog
with the following URL: !endpoint',
array('!url' => l(t('Custom Store Development Integration'), "http://api.shipstation.com/"),
'!endpoint' => 'http://' . $_SERVER['HTTP_HOST'] . base_path() . 'shipstation/api-endpoint'));
}
}
/**
* Implements hook_menu().
*/
function commerce_shipstation_menu() {
$items['admin/commerce/config/fulfilment/shipstation'] = array(
'title' => 'ShipStation',
'description' => 'Configure fulfilment for ShipStation',
'page callback' => 'drupal_get_form',
'page arguments' => array('commerce_shipstation_admin_page'),
'access arguments' => array('configure commerce fulfilment'),
'file' => 'commerce_shipstation.admin.inc',
'type' => MENU_LOCAL_TASK,
);
$items['shipstation/api-endpoint'] = array(
'title' => 'ShipStation API Callback URI',
'page callback' => 'commerce_shipstation_endpoint',
'access callback' => TRUE,
'access arguments' => array('access commerce fulfilment'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* establish a service endpoint for shipstation to communicate with
*
* @TODO: implement logging
*/
function commerce_shipstation_endpoint() {
$authorized = FALSE;
$logging = variable_get('commerce_shipstation_logging', 0);
$auth_key = variable_get('commerce_shipstation_alternate_auth', '');
$username = variable_get('commerce_shipstation_username', '');
$password = variable_get('commerce_shipstation_password', '');
// allow shipstation to authenticate using token
if (!empty ( $_GET['auth_key'] ) ) {
if ( $auth_key == $_GET['auth_key'] ) {
$authorized = TRUE;
}
elseif ( $auth_key != $_GET['auth_key'] ) {
watchdog('commerce_shipstation', 'Wrong auth_key passed', WATCHDOG_ERROR);
}
}
// allow shipstation to authenticate using HTTP Basic
if ( $authorized == FALSE ) {
// no u/p combo
if ( !isset( $_SERVER['PHP_AUTH_USER'] ) ) {
header( "WWW-Authenticate: Basic realm =\"ShipStation XML API for Drupal Commerce" );
header( "HTTP/1.0 401 Unauthorized" );
print t( 'Error: You must enter a username and password.');
exit;
}
// empty u/p combo
if ( empty( $_SERVER['PHP_AUTH_USER'] ) || empty( $_SERVER['PHP_AUTH_PW'] ) ) {
print t( 'Error: Basic HTTP authentication is required. Please add username and password to URL string.');
exit;
}
// bad u/p combo
//if ( $_SERVER['PHP_AUTH_USER'] != $username || user_hash_password($_SERVER['PHP_AUTH_PW']) != $password ) {
if ( $_SERVER['PHP_AUTH_USER'] != $username || md5($_SERVER['PHP_AUTH_PW']) != $password ) {
print t( 'Error: Basic HTTP authentication failed. Please check your credentials and try again.');
exit;
}
}
// if shipstation gets past the door, run the call based on the action it defines
switch ($_GET['action']) {
case "export":
$start_date = $_GET['start_date'];
$end_date = $_GET['end_date'];
$page = $_GET['page'];
return commerce_shipstation_export_orders($start_date, $end_date, $page);
case "shipnotify":
$order_number = $_GET['order_number'];
$tracking_number = $_GET['tracking_number'];
$carrier = $_GET['carrier'];
$service = $_GET['service'];
if ($order_number && $tracking_number && $carrier && $service) {
$commerce_order = commerce_order_load_by_number($order_number);
return rules_invoke_event('commerce_shipstation_order_success', $commerce_order, $tracking_number, $carrier, $service);
}
else return t('Error: missing order info.');
default:
return t( 'Error: Invalid action, or no action defined.');
}
}
/**
* Identify orders to send back to shipstation
*/
function commerce_shipstation_export_orders($start_date, $end_date, $page = 0) {
$status = variable_get('commerce_shipstation_export_status', '');
$field_billing_phone_number = variable_get('commerce_shipstation_billing_phone_number_field', '');
$field_shipping_phone_number = variable_get('commerce_shipstation_shipping_phone_number_field', '');
// grab a set of orders between $start_date and $end_date
$page_size = variable_get('commerce_shipstation_export_paging', '100');
// generate the page size we need
if ($page > 0) {
$start_page = $page - 1;
}
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_order')
->propertyCondition('created', array(strtotime($start_date), strtotime($end_date)), 'BETWEEN')
->propertyCondition('status', $status, '=')
->range($start_page * $page_size, $page_size);
$result = $query->execute();
if (isset($result['commerce_order'] )) {
$order_ids = array_keys($result['commerce_order']);
$orders = commerce_order_load_multiple($order_ids);
}
else {
return t('Error: check query string parameters and try again.');
}
$bundle_type = variable_get('commerce_shipstation_bundle_field', '');
$output = new SimpleXMLElement( "<Orders></Orders>" );
// insert the number of pages
$output['pages'] = ceil( count($orders) / $page_size);
$output['page'] = $page;
// build the order export page
foreach ($orders as $order) {
// fetch most of the data we need to define an order for shipstation
$data = entity_metadata_wrapper('commerce_order', $order);
$bill = $data->commerce_customer_billing->commerce_customer_address;
$ship = $data->commerce_customer_shipping->commerce_customer_address;
// get the exposed shipping methods
$available_methods = variable_get('commerce_shipstation_exposed_shipping_methods', '');
$chosen_method = commerce_fulfilment_get_shipping_lineitem($data);
// sanity check for a shipping method on the order
if ($chosen_method) {
$chosen_ship = $chosen_method->value()->data['shipping_service']['shipping_method'];
}
// only process orders which have authorized shipping methods
if ( $chosen_method && in_array($chosen_ship, $available_methods) ) {
/*
* @TODO: create lines with the following information:
* -- tax amount [NEED]
* -- order notes [NEED]
* -- private order notes [NEED]
* -- coupons used [provided, sort of]
*/
// set up the xml schema
$ss_order = $output->addChild( 'Order' );
// order number
$ss_order->OrderNumber = $data->order_number->value();
//order_date
$ss_order->OrderDate = date(DATE_W3C, $data->created->value());
// order status
$ss_order->OrderStatus = $data->status->value();
// last modified
$ss_order->LastModified = date(DATE_W3C, $data->changed->value());
// shipping method
$ss_order->ShippingMethod = $chosen_method->value()->data['shipping_service']['display_title'];
// order total
$ss_order->OrderTotal = $data->commerce_order_total->amount_decimal->value();
// tax amount
// shipping amount
$ss_order->ShippingAmount = $chosen_method->commerce_unit_price->amount_decimal->value();
// order notes
// coupons and discounts
// billing address
$customer = $ss_order->addChild( 'Customer' );
// billing email
$customer->CustomerCode = $data->mail->value();
// billing info
$billing = $customer->addChild( 'BillTo' );
$billing->Name = $bill->name_line->value();
$billing->Company = $bill->organisation_name->value();
if (!empty($field_billing_phone_number)) {
$billing->Phone = $data->commerce_customer_billing->$field_billing_phone_number->value();
}
$billing->Email = $data->mail->value();
// shipping info
$shipping = $customer->addChild( 'ShipTo' );
$shipping->Name = $ship->name_line->value();
$shipping->Address1 = $ship->thoroughfare->value();
$shipping->Address2 = $ship->premise->value();
$shipping->City = $ship->locality->value();
$shipping->State = $ship->administrative_area->value();
$shipping->PostalCode = $ship->postal_code->value();
$shipping->Country = $ship->country->value();
if (!empty($field_shipping_phone_number)) {
$shipping->Phone = $data->commerce_customer_billing->$field_shipping_phone_number->value();
}
// line item details
$line_items = $ss_order->addChild( 'Items' );
foreach ($data->commerce_line_items as $id => $item) {
// make sure it's a product
if ($item->type->value() !== 'product' ) {
continue;
}
//otherwise, process it as normal
$raw_product = commerce_product_load($item->commerce_product->raw());
$product = entity_metadata_wrapper('commerce_product', $raw_product);
$line_item = $line_items->addChild( 'Item' );
// sku
$line_item->SKU = $product->sku->value();
//name
$line_item->Name = $product->title->value();
// weight
if (isset($product->field_weight)) {
if ($product->field_weight->unit->value() == "kg") {
$line_item->Weight = 1000 * $product->field_weight->weight->value();
}
else {
$line_item->Weight = $product->field_weight->weight->value();
}
$line_item->WeightUnits = $product->field_weight->unit->value();
}
// quantity
$line_item->Quantity = $item->quantity->value();
// unit price
$line_item->UnitPrice = $item->commerce_unit_price->amount_decimal->value();
// image
// line item options
// if the product contains an entity reference field (e.g., for a product bundle)
if ( isset($item->$bundle_type) ) {
foreach ( $item->$bundle_type as $bundle_item ) {
if ( $bundle_item->type() == 'commerce_product' ) {
$line_item = $line_items->addChild( 'Item' );
// sku
$line_item->SKU = $bundle_item->sku->value();
//name
$line_item->Name = $bundle_item->title->value();
// weight
if (isset($bundle_item->field_weight)) {
if ($bundle_item->field_weight->unit->value() == "kg") {
$line_item->Weight = 1000 * $bundle_item->field_weight->weight->value();
}
else {
$line_item->Weight = $bundle_item->field_weight->weight->value();
}
$line_item->WeightUnits = $bundle_item->field_weight->unit->value();
}
// quantity
$line_item->Quantity = $item->quantity->value();
// unit price
$line_item->UnitPrice = 0.00;
// image
// line item options
}
}
}
}
}
}
Header( 'Content-type: text/xml' );
$dom = dom_import_simplexml($output)->ownerDocument;
$dom->formatOutput = TRUE;
print $dom->saveXML();
}
/**
* Returns a list of shipping service options.
*/
function commerce_shipstation_shipping_methods($methods) {
$options = array();
foreach ($methods as $method) {
$title = $method["name"];
$display = $method['display_title'];
$options[$title] = $display;
}
return $options;
}