· 6 years ago · Dec 30, 2019, 05:58 AM
1<?php
2/**
3* Plugin Name: Sureship API Integration
4* Plugin URI: https://wphero.io/
5* Description: This plugin integrates Sureship API with the Orders in site.
6* Version: 1.0
7* Author: WP Hero
8* Author URI: https://wphero.io/
9**/
10
11/* Sureship API integration START */
12
13//The token is a unique ID setup at Sureship for the client
14$token = '06e73d8a-7f2d-4f12-b6ac-7166967f5a82';
15//This is the path of our log file
16//$log_path = dirname(__FILE__) . '/sureship_log.txt';
17$log_path = plugin_dir_path(__FILE__).'/sureship_log.txt';
18
19/*
20 * Dev/Staging Variables
21 * Uncomment these when testing. Re-comment when moving to Live
22 */
23
24$api_url = 'https://api-dev.sureshiponline.com/orders';
25$ss_failure_mail_to = 'david@wphero.io';
26$embroidery_alert_mail_to = 'david@wphero.io';
27
28
29/*
30 * Live Variables
31 * Uncomment these when making Live. Re-comment when testing
32 */
33
34//$api_url = 'https://api.sureshiponline.com/orders';
35//$ss_failure_mail_to = 'support@wphero.io, orders@baydog.com';
36//$embroidery_alert_mail_to = 'orders@baydog.com';
37
38
39// logEvent writes the string $message to a log file, prefaced with a timestamp
40function logEvent($message){
41 global $log_path;
42 if ($message != '') {
43 // Add a timestamp to the start of the $message
44 $message = date("Y/m/d H:i:s").' :: '.$message;
45 $fp = fopen($log_path, "a");
46 fwrite($fp, $message.PHP_EOL);
47 fclose($fp);
48 }
49}
50
51
52//List the order when it gets complete
53//add_action('woocommerce_payment_complete', 'sureship_create_orders_api');
54add_action('woocommerce_order_status_processing', 'sureship_create_orders_api');
55function sureship_create_orders_api($order_id){
56 global $api_url;
57 global $token;
58 global $ss_failure_mail_to;
59 global $embroidery_alert_mail_to;
60 global $log_path;
61 $order_contains_embroidery = false;
62 $order_number = get_post_meta($order_id,"_order_number", true);
63
64 //Make a clear divider in the log file before we begin processing this order.
65 logEvent(PHP_EOL . PHP_EOL . PHP_EOL . "==================================================================================================" .
66 PHP_EOL . "==================================================================================================" .
67 PHP_EOL . "==================================================================================================" .
68 PHP_EOL . "<<<<<<<<<<<<<<<<<<< Begin logging for order # " . $order_number . " >>>>>>>>>>>>>>>>>>>>" . PHP_EOL);
69
70 // get order object and order details
71 $order = new WC_Order( $order_id );
72 //Get total products in an order
73 $total_products = count( $order->get_items() );
74 // Get the customer ID
75 $user_id = $order->get_user_id();
76 $items = array();
77 $count = 0;
78 // Get data from Items
79 foreach ( $order->get_items() as $item_key => $item_values ) {
80// logEvent('irfan1111');
81// $demo_array = print_r($item_values, true);
82// logEvent($demo_array);
83// logEvent('irfan1100001');
84 $product_id = $item_values->get_product_id(); // the Product id
85 $product = $item_values->get_product(); // the WC_Product object
86 $item_data = $item_values->get_data();
87 //We need to ignore known or possible embroidered items when building the list of products for sureship
88 if(($product_id != 6323) && (false === stripos($product->get_name(), 'embroider'))) {
89 //if($count === 0){
90 $sku = $product->get_sku();
91 if($sku == 'CB'){
92 $newsku = 'CB-BLU';
93 }else{
94 $newsku = $sku;
95 }
96 $items[] = array(
97 'sku' => $newsku,
98 'qty' => $item_data['quantity'],
99 'price' => floatval($item_values->get_total()),
100 'weight' => floatval($product->get_weight()),
101 'discount' => $order_data['discount_total']);
102 }
103 else {
104 $order_contains_embroidery = true;
105 }
106 /*else{
107 $items[] = array(
108 'sku' => $product->get_sku(),
109 'qty' => $item_data['quantity'],
110 );
111 }*/
112 //}
113 $count++ ;
114 }
115
116 /*Condtion check if total products in an order is greater then the number of product send to Sureship.
117 If condition satisfies this means the ignored product is Collar Product with Embroidery Add On.
118 So, mail is send to admin to notify him about the Order Id.
119 */
120 //if($total_products > count($items)){
121 if($order_contains_embroidery){
122 $subject = "Embroidered Order Notification " ;
123 $message = "Message from " . site_url() . ": " . PHP_EOL . PHP_EOL . "Order #" . $order_number . " contains one or more embroidery products.";
124 wp_mail( $embroidery_alert_mail_to, $subject, $message );
125 logEvent(PHP_EOL . "***** Order contains embroidery item(s). Alert email sent to " . $embroidery_alert_mail_to . " ******" . PHP_EOL);
126 }
127
128 if(!empty($items)){ // This condition checks, if there is any product or not except Collar Embroidery Add On
129
130 // Get data from Order
131 $order_data = $order->get_data();
132 //Get value for 'ship_to' key
133 $shipping_email = $order_data['billing']['email'] ;
134 $ship_to = array(
135 'name_line1' => $order_data['shipping']['first_name'] ." ". $order_data['shipping']['last_name'],
136 'name_line2' => $order_data['shipping']['company'],
137 'addr_line1' => $order_data['shipping']['address_1'],
138 'addr_line2' => $order_data['shipping']['address_2'],
139 'city' => $order_data['shipping']['city'],
140 'state' => $order_data['shipping']['state'],
141 'zip' => $order_data['shipping']['postcode'],
142 'country' => $order_data['shipping']['country'],
143 'phone' => $order_data['shipping']['phone'],
144 'email' => $shipping_email,
145 );
146
147 //Get value for 'bill_to' key
148 $bill_to = array(
149 'name_line1' => $order_data['billing']['first_name'] ." ". $order_data['billing']['last_name'],
150 'name_line2' => $order_data['billing']['company'],
151 'addr_line1' => $order_data['billing']['address_1'],
152 'addr_line2' => $order_data['billing']['address_2'],
153 'city' => $order_data['billing']['city'],
154 'state' => $order_data['billing']['state'],
155 'zip' => $order_data['billing']['postcode'],
156 'country' => $order_data['billing']['country'],
157 'phone' => $order_data['billing']['phone'],
158 'email' => $order_data['billing']['email'],
159 );
160
161 //Get value for 'ship_method' key
162 $shipping_type = $order->get_shipping_method();
163 $ship_type = "USPS_FRSTCLS";
164
165 if(!isset($ship_type)){
166 $ship_type = "USPS_FRSTCLS";
167 }
168
169 //Get value for 'payment_info' key
170 $payment_type = $order_data['payment_method'];
171
172 $body = array(
173 'xref' => strval($order_number),
174 'items' => $items,
175 "ship_to" => $ship_to,
176 "bill_to" => $bill_to,
177 "ship_method" => $ship_type,
178 );
179
180 //Log the json request to sureship
181 logEvent(PHP_EOL .'Outbound request ==========>>>>>> ' . PHP_EOL . PHP_EOL .
182 json_encode($body));
183
184 // API Callout to Sureship URL
185 $response = wp_remote_post( $api_url,
186 array(
187 'method' => 'POST',
188 'headers' => array('Content-Type' => 'application/json; charset=utf-8', 'Authorization' => $token),
189 'sslverify' => false,
190 'body' => json_encode($body),
191 )
192 );
193
194 //Format the response data nicely for printing to our log file
195 $response_string = print_r($response, true);
196 //Log the json reply from sureship
197 logEvent(PHP_EOL . PHP_EOL . 'Inbound response ==========>>>>>> ' . PHP_EOL . $response_string);
198
199 //200 is the successful reply code. Any other code, eg. 404, 500, etc. is an error
200 if(200 != (int)($response['response']['code'])) {
201 wp_mail( $ss_failure_mail_to, 'Order #' . $order_number . ' rejected by Sureship',
202 'Message from ' . site_url() . ': ' . PHP_EOL . PHP_EOL . 'Order number ' . $order_number . ' was rejected by Sureship. Check the log file for more information: ' . $log_path );
203 logEvent(PHP_EOL . "***** Order rejected by Sureship. Error email sent to " . $ss_failure_mail_to . "******" . PHP_EOL);
204 }
205
206 if ( is_wp_error( $response ) ) {
207 $error_message = $response->get_error_message();
208 echo "Something went wrong: $error_message";
209 } else {
210 echo 'Response:<pre>';
211 print_r( $response );
212 echo '</pre>';
213 }
214 }
215}
216
217/* Sureship API integration END */