/
Psigate.php
360 lines (310 loc) · 12.9 KB
/
Psigate.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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
namespace AktiveMerchant\Billing\Gateways;
use AktiveMerchant\Billing\Interfaces as Interfaces;
use AktiveMerchant\Billing\Gateway;
use AktiveMerchant\Billing\CreditCard;
use AktiveMerchant\Billing\Exception;
use AktiveMerchant\Billing\Response;
/**
* Merchant driver for {link http://www.psigate.com/ PSiGate}.
*
* @package Aktive-Merchant
* @author Scott Gifford
* @license http://www.opensource.org/licenses/mit-license.php
* @see http://www.psigate.com/
*/
class Psigate extends Gateway implements
Interfaces\Charge,
Interfaces\Credit
{
const LIVE_URL = "https://secure.psigate.com:7934/Messenger/XMLMessenger";
const TEST_URL = "https://dev.psigate.com:7989/Messenger/XMLMessenger";
const SUCCESS_MESSAGE = "Success";
const UNKNOWN_ERROR_MESSAGE = "The transaction was declined";
const AUTHSTR_VERSION = 1;
const TEST_MODE_ALWAYS_AUTH = 'A';
const TEST_MODE_ALWAYS_DECLINE = 'D';
const TEST_MODE_RANDOM = 'R';
const TEST_MODE_FRAUD = 'F';
public static $supported_countries = array('CA');
public static $supported_cardtypes = array('visa', 'master', 'american_express');
public static $homepage_url = 'http://www.psigate.com/';
public static $display_name = 'Psigate';
private $options = array();
private $test_mode = 0;
public function __construct($options)
{
$this->required_options('login, password', $options);
$this->options = $options;
}
/**
* Configure how the gateway will respond to test requests.
*
* The gateway can be configured to always allow requests (the default), to always fail,
* etc. You can call this function to set the mode. You must also call {@see mode()} to
* set the mode to 'test'.
*
* Values are:
* <ul>
* <li>Psigate::TEST_MODE_ALWAYS_AUTH - Authorize every request (default)
* <li>Psigate::TEST_MODE_ALWAYS_DECLINE - Decline every request
* <li>Psigate::TEST_MODE_RANDOM - Randomly authorize or decline requests
* <li>Psigate::TEST_MODE_FRAUD - Treat every request as a fraud alert
* </ul>
*
* @param string $mode New value for test mode (unset or NULL to keep current value)
* @return string Current value for test mode, or previous value if $mode is set
*/
public function test_mode($mode = NULL)
{
$last_mode = $this->test_mode;
if ($mode !== NULL) $this->test_mode = $mode;
return $last_mode;
}
public function authorize($money, CreditCard $creditcard, $options = array())
{
// Ruby code required order_id, but PSiGate doesn't require this, so we don't either
$options['CardAction'] = 1;
return $this->commit($money, $creditcard, $options);
}
public function purchase($money, CreditCard $creditcard, $options = array())
{
// Ruby code required order_id, but PSiGate doesn't require this, so we don't either
$options['CardAction'] = 0;
return $this->commit($money, $creditcard, $options);
}
public function capture($money, $authorization, $options = array())
{
$options['CardAction'] = 2;
$authdata = $this->unpack_authorization_string($authorization);
$options['order_id'] = $authdata['order_id'];
return $this->commit($money, NULL, $options);
}
public function credit($money, $authorization, $options = array())
{
$options['CardAction'] = 3;
$authdata = $this->unpack_authorization_string($authorization);
$options['order_id'] = $authdata['order_id'];
return $this->commit($money, NULL, $options);
}
public function void($authorization, $options = array())
{
$options['CardAction'] = 9;
$authdata = $this->unpack_authorization_string($authorization);
$options['transaction_id'] = $authdata['transaction_id'];
$options['order_id'] = $authdata['order_id'];
return $this->commit(NULL, NULL, $options);
}
/**
* Create a string with required transaction data.
*
* PSiGate always requires the order ID to complete or modify past transactions,
* and sometimes requires the transaction ID. This function packs them both into
* one string, which can be used for any of these purposes.
*
* @param unknown_type $orderid
* @param unknown_type $transactionid
*/
private function pack_authorization_values($orderid, $transactionid)
{
return join("&", array(self::AUTHSTR_VERSION,urlencode($orderid), urlencode($transactionid)));
}
private function unpack_authorization_string($authstr)
{
$split = split("&",$authstr);
if ($split === FALSE) {
throw new Exception("Invalid authorization string");
}
if ($split[0] != self::AUTHSTR_VERSION) {
throw new Exception("Invalid authorization string version");
}
if (count($split) != 3) {
throw new Exception("Error parsing authorization string");
}
return array(
'order_id' => urldecode($split[1]),
'transaction_id' => urldecode($split[2]),
);
}
private function commit($money, CreditCard $creditcard = NULL, $options = array())
{
$url = $this->isTest() ? self::TEST_URL : self::LIVE_URL;
// Log request, but mask real user information
if ($creditcard === NULL) {
$log_card = NULL;
} else {
$log_card = clone $creditcard;
$log_card->number = $this->mask_cardnum($log_card->number);
if ($log_card->verification_value) {
$log_card->verification_value = $this->mask_cvv($log_card->verification_value);
}
}
// Make the request
$data = $this->ssl_post($url, $this->post_data($money, $creditcard, $options));
$response = $this->parse($data);
// Make sure the response is valid and doesn't contain an error
if (empty($response['approved'])) {
throw new Exception("Error parsing merchant response: No status information");
}
if ($response['approved'] == 'ERROR') {
throw new Exception("Merchant error: " . (isset($response['errmsg']) ? $response['errmsg'] : 'Unknown error'));
}
if ( $response['approved'] != 'APPROVED'
&& $response['approved'] != 'DECLINED'
) {
throw new Exception("Merchant error: Unknown status '$response[approved]'");
}
return new Response(
$this->success_from($response),
$this->message_from($response),
$response,
array(
'test' => $this->isTest(),
'authorization' => (isset($response['orderid']) && isset($response['transrefnumber']))
? $this->pack_authorization_values($response['orderid'],$response['transrefnumber'])
: NULL,
'avs_result' => isset($response['avsresult'])
? array('code' => $response['avsresult'])
: NULL,
'cvv_result' => isset($response['cardidresult'])
? $response['cardidresult']
: NULL,
));
}
private function message_from($response)
{
if ($this->success_from($response)) {
return self::SUCCESS_MESSAGE;
} else {
if (isset($response['errmsg'])) {
return $response['errmsg'];
} else {
return self::UNKNOWN_ERROR_MESSAGE;
}
}
}
private function success_from($response)
{
return $response['approved'] == "APPROVED";
}
private function parse($response_xml)
{
$response = array(
'errmsg' => 'Unknown Error',
'complete' => false,
);
try {
// This will throw an exception in case of a severe error
$xml = simplexml_load_string($response_xml);
$results = $xml->xpath('//Result/*');
if ($results === FALSE) {
throw new Exception("Xpath parsing failed");
}
foreach ($results as $elt) {
$response[strtolower($elt->getName())] = (string) $elt;
}
} catch (\Exception $ex) {
throw new Exception("Error parsing XML response from merchant", 0, $ex);
}
return $response;
}
protected function post_data($money, $creditcard, $options)
{
$params = $this->parameters($money, $creditcard, $options);
$xml = new \SimpleXMLElement("<Order />");
foreach ($params as $k => $v) {
if ($v !== NULL) $xml->addChild($k, $v);
}
return $xml->asXML();
}
private function parameters($money, CreditCard $creditcard = NULL, $options = array())
{
$params = array(
'StoreID' => $this->options['login'],
'Passphrase' => $this->options['password'],
'TestResult' => isset($options['test_result']) ? $options['test_result'] : NULL,
'OrderID' => isset($options['order_id']) ? $options['order_id'] : NULL,
'UserID' => isset($options['user_id']) ? $options['user_id'] : NULL,
'Phone' => isset($options['phone']) ? $options['phone'] : NULL,
'Fax' => isset($options['fax']) ? $options['fax'] : NULL,
'Email' => isset($options['email']) ? $options['email'] : NULL,
'PaymentType' => 'CC',
'CardAction' => isset($options['CardAction']) ? $options['CardAction'] : NULL,
'CustomerIP' => isset($options['ip']) ? $options['ip'] : NULL,
'SubTotal' => isset($money) ? $this->amount($money) : NULL,
'Tax1' => isset($options['tax1']) ? $options['tax1'] : NULL,
'Tax2' => isset($options['tax2']) ? $options['tax2'] : NULL,
'ShippingTotal' => isset($options['shipping_total']) ? $options['shipping_total'] : NULL,
);
if (isset($creditcard)) {
$params['CardNumber'] = $creditcard->number;
if (isset($creditcard->month)) $params['CardExpMonth'] = sprintf("%02d", $creditcard->month);
if (isset($creditcard->year)) $params['CardExpYear'] = substr($creditcard->year,-2);
if (isset($creditcard->verification_value)) {
$params['CardIDNumber'] = $creditcard->verification_value;
$params['CardIDCode'] = '1';
}
}
// Copy address information into request
// psigate_name => options_name
$addrfields = array(
'name' => 'name',
'address1' => 'address1',
'address2' => 'address2',
'city' => 'city',
'province' => 'state',
'postalcode' => 'zip',
'country' => 'country',
'company' => 'company',
);
if (isset($options['billing_address'])) {
foreach($addrfields as $p => $o) {
if (isset($options['billing_address'][$o])) $params['B'.$p] = $options['billing_address'][$o];
}
}
if (isset($options['shipping_address'])) {
foreach($addrfields as $o => $p) {
if (isset($options['shipping_address'][$o])) $params['S'.$p] = $options['shipping_address'][$o];
}
}
if (isset($options['transaction_id'])) {
$params['TransRefNumber'] = $options['transaction_id'];
}
if ($this->isTest()) {
if (empty($this->test_mode)) $this->test_mode = self::TEST_MODE_ALWAYS_AUTH;
switch($this->test_mode) {
case self::TEST_MODE_ALWAYS_AUTH: $params['TestResult'] = 'A'; break;
case self::TEST_MODE_ALWAYS_DECLINE: $params['TestResult'] = 'D'; break;
case self::TEST_MODE_FRAUD: $params['TestResult'] = 'F'; break;
case self::TEST_MODE_RANDOM: $params['TestResult'] = 'R'; break;
default: throw new Exception("Invalid test mode");
}
}
return $params;
}
/**
* Mask a credit card number.
*
* Makes the card safe for logging and storing, by replacing all but the
* first 2 and last 4 digits with x's.
*
* @param string $cardnum Card number to mask
* @return string Masked card number
*/
protected function mask_cardnum($cardnum) {
return substr($cardnum,0,2) . preg_replace('/./','x',substr($cardnum,2,-4)) . substr($cardnum,-4,4);
}
/**
* Mask a card verification value;
*
* Makes a card verification value safe for logging and storing, by replacing all
* characters with x's.
*
* @param string $cardverifier Card verification value to mask
* @return string Masked card verification value
*/
protected function mask_cvv($cvv) {
return preg_replace('/./','x',$cvv);
}
}