forked from jaafit/bitpayWoocommerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
callback.php
231 lines (198 loc) · 6.91 KB
/
callback.php
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
<?php
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) )
{
function bitpay_callback()
{
if(isset($_GET['bitpay_callback']))
{
bplog(file_get_contents("php://input"));
ini_set('error_log', plugin_dir_path(__FILE__).'bplog.txt');
ini_set('error_reporting', E_ALL & ~E_STRICT & ~E_NOTICE);
global $woocommerce;
require(plugin_dir_path(__FILE__).'bp_lib.php');
$gateways = $woocommerce->payment_gateways->payment_gateways();
if (!isset($gateways['bitpay']))
{
bplog('bitpay plugin not enabled in woocommerce');
return;
}
$bp = $gateways['bitpay'];
$response = bpVerifyNotification( $bp->settings['apiKey'] );
if (isset($response['error']))
bplog($response);
else
{
$orderId = $response['posData'];
$order = new WC_Order( $orderId );
switch($response['status'])
{
case 'paid':
break;
case 'confirmed':
case 'complete':
if ( in_array($order->status, array('on-hold', 'pending', 'failed' ) ) )
{
$order->payment_complete();
processOrderFBA($bp, $order);
}
break;
}
}
}
}
function processOrderFBA($bitpay, $order)
{
if (!$bitpay->settings['fbaEnabled'])
return;
$orderInfo = 'order '.$order->id.':'; // for log
require_once (plugin_dir_path(__FILE__).'FBAOutboundServiceMWS/config.inc.php');
$optionsFile = plugin_dir_path(__FILE__).'fba_options.php';
if (!file_exists($optionsFile)) {
bplog($orderInfo.'fba_options.php not found. Copy fba_options.php.sample and fill in details.');
return;
}
require_once ($optionsFile);
// gather order info
$items = $order->get_items();
$orderItems = array();
$hasSkus = false; // does this order have any skus?
$hasBlanks = false; // does this order have any blank skus?
foreach ($items as $i)
{
$product = get_product($i['product_id']);
if (strlen($product->get_sku()))
$hasSkus = true;
else
{
$hasBlanks = true;
continue;
}
$orderItems[] = array(
'currency' => get_woocommerce_currency(),
'value' => $i['line_subtotal'],
'sku' => $product->get_sku(),
'quantity' => $i['qty']);
}
if (!$hasSkus)
return true; // nothing to do
$prefix = ($order->shipping_address_1) ? 'shipping_' : 'billing_';
$address = array(
'name' => $order->{$prefix.first_name}.' '.$order->{$prefix.last_name},
'line1' => $order->{$prefix.address_1},
'line2' => $order->{$prefix.address_2},
'line3' => '',
'city' => $order->{$prefix.city},
'state' => $order->{$prefix.state},
'country' => $order->{$prefix.country},
'zip' => $order->{$prefix.postcode},
'phone' => $order->billing_phone); // there is no shipping_phone
if (strlen($order->{$prefix.company}))
$address['name'] = $order->{$prefix.company}.' c/o '.$address['name'];
// find fba options by looking for country
foreach($bpfbaOptions as $o) {
if (!strlen($o['countries'])) {
$bpfba = $o; // blank country means "use this if above entries don't match"
break;
}
$countries = array_map('trim', explode(',',$o['countries']));
if (in_array($address['country'], $countries) === TRUE) {
$bpfba = $o;
break;
}
}
if (!isset($bpfba)) {
bplog($orderInfo.'Destination address not found in fba_options.php');
$order->update_status('failed');
return false;
}
// apply fba options
$orderId = $order->id;
$shippingSpeed = $bpfba['shippingSpeed'];
$fulfillmentPolicy = $bpfba['fulfillmentPolicy'];
$awsAccessKey = $bpfba['awsAccessKey'];
$secretKey = $bpfba['secretAccessKey'];
$merchantId = $bpfba['merchantId'];
$marketplaceId = $bpfba['marketplaceId'];
$endpointUrl = $bpfba['endpointUrl'];
// create required FBA objects
$config = array (
'ServiceURL' => $endpointUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'MaxErrorRetry' => 3
);
$service = new FBAOutboundServiceMWS_Client(
$awsAccessKey,
$secretKey,
$config,
APPLICATION_NAME,
APPLICATION_VERSION);
$items = array();
$orderItemId=1;
foreach($orderItems as $i)
{
$value = new FBAOutboundServiceMWS_Model_Currency();
$value->setCurrencyCode($i['currency']);
$value->setValue($i['value']);
$item = new FBAOutboundServiceMWS_Model_FulfillmentOrderItem();
$item->setSellerSKU($i['sku']); // must be amazon's SKU
$item->setSellerFulfillmentOrderItemId($orderItemId++); // seller can choose this
$item->setQuantity( (int)$i['quantity'] ); // must be integer or FBA server fails
//$item->setPerUnitDeclaredValue($value);
$items[] = $item;
}
$list = new FBAOutboundServiceMWS_Model_FulfillmentOrderItemList();
$list->setMember($items);
$emails = new FBAOutboundServiceMWS_Model_NotificationEmailList();
$fbaAddress = new FBAOutboundServiceMWS_Model_Address();
$fbaAddress->setName($address['name']);
$fbaAddress->setLine1($address['line1']);
$fbaAddress->setLine2($address['line2']);
$fbaAddress->setLine3($address['line3']);
$fbaAddress->setCity($address['city']);
$fbaAddress->setStateOrProvinceCode($address['state']);
$fbaAddress->setCountryCode($address['country']);
$fbaAddress->setPostalCode($address['zip']);
$fbaAddress->setPhoneNumber($address['phone']);
$request = new FBAOutboundServiceMWS_Model_CreateFulfillmentOrderRequest();
$request->setSellerId($merchantId);
$request->setMarketplace($marketplaceId);
$request->setSellerFulfillmentOrderId($orderId);
$request->setDisplayableOrderId($orderId);
$request->setDisplayableOrderDateTime(date('Y-m-d', time()));
$request->setDisplayableOrderComment("Thank you for your order.");
$request->setShippingSpeedCategory($shippingSpeed);
$request->setDestinationAddress($fbaAddress);
$request->setFulfillmentPolicy($fulfillmentPolicy);
$request->setFulfillmentMethod('Consumer');
$request->setNotificationEmailList($emails);
$request->setItems($list);
// send request to amazon
try {
$response = $service->createFulfillmentOrder($request);
bplog($orderInfo);
bplog("CreateFulfillmentOrderResponse");
if ($response->isSetResponseMetadata()) {
bplog(" ResponseMetadata");
$responseMetadata = $response->getResponseMetadata();
if ($responseMetadata->isSetRequestId())
{
bplog(" RequestId");
bplog(" " . $responseMetadata->getRequestId());
// success!
if (!$hasBlanks)
$order->update_status('completed');
}
}
} catch (FBAOutboundServiceMWS_Exception $ex) {
$order->update_status('failed');
bplog("Caught Exception: " . $ex->getMessage());
bplog("Response Status Code: " . $ex->getStatusCode());
bplog("Error Code: " . $ex->getErrorCode());
bplog("Error Type: " . $ex->getErrorType());
bplog("Request ID: " . $ex->getRequestId());
bplog("XML: " . $ex->getXML());
}
}
add_action('init', 'bitpay_callback');
}