-
Notifications
You must be signed in to change notification settings - Fork 1
/
sagepay.php
502 lines (444 loc) · 16.4 KB
/
sagepay.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
<?php
/**
* SagePay class
* Handles the formatting of requests to SagePay,
* the actual request and response of the request
*
* @package Payment
* @author Pete Robinson
* @version 1.0
**/
class SagePay
{
public
$status = '', // status returned from the cURL request
$error = '', // stores any errors
$vendorTxCode = '', // vendor transaction code. must be unqiue
$acsurl = '', // used to store data for 3D Secure
$pareq = '', // used to store data for 3D Secure
$md = ''; // used to store data for 3D Secure
private
$env = '', // environment, set according to 'ENV' site constant
$url = '', // the URL to post the cURL request to (set further down)
$data = array(), // the data to post
$price = 0, // transaction amount
$standardFields = array(), // holds standard SagePay info (currency etc)
$response = array(), // response from SagePay cURL request
$description = 'New order from your online store', // Description of the order sent to SagePay
$curl_str = ''; // the url encoded string derrived from the $this->data array
const
TYPE = 'PAYMENT', // Transaction type
PROTOCOL_VERSION = '2.22', // SagePay protocol vers no
VENDOR = 'my_vendor_name', // Your SagePay vendor name
CURRENCY = 'gbp'; // Currency transaction is to be in. For multi-currency sites, you need to change this from a constant to a property
/**
* Constructor method
* Sets the $this->env property, assigns the necessary urls,
* sets the price, sets and formats the data to pass to SagePay
* @return void
* @param arr $data - the data provided by the user (billing, price and card)
* @author Pete Robinson
**/
public function __construct($data)
{
$this->env = ENV;
// sets the url to post to based on ENV
$this->setUrls();
$this->setPrice($data['Amount']);
// adds all of the config fields to the data array
$this->setData($data);
// converts $this->data from an array into a query string
$this->formatData();
}
/**
* setData method
* Assigns the user data and SagePay config data to $this->data
* @return void
* @param arr $data - billing and card info from user
* @author Pete Robinson
**/
private function setData($data)
{
// Set the billing, card and purchase details as provided by the user
$this->data = $data;
// Format the StartDate field
if($data['StartDateMonth']){
// If so, add start date to data array to be appended to POST
$this->data['StartDate'] = $data['StartDateMonth'] . $data['StartDateYear'];
}
// Format the ExpiryDate field
$this->data['ExpiryDate'] = $data['ExpiryDateMonth'] . $data['ExpiryDateYear'];
// set the vendorTxCode
$this->vendorTxCode = $data['VendorTxCode'];
// set the required fields to pass to SagePay
$this->standardFields = array(
'VPSProtocol' => self::PROTOCOL_VERSION,
'TxType' => self::TYPE,
'Vendor' => self::VENDOR,
'VendorTxCode' => $this->vendorTxCode,
'Amount' => $this->price,
'Currency' => self::CURRENCY,
'Description' => $this->description
);
// Add Payment Type
$this->data['PaymentType'] = self::TYPE;
// Add currency details
$this->data['Currency'] = self::CURRENCY;
// Add vendor and transaction details
$this->data['VendorTxCode'] = $this->vendorTxCode;
$this->data['Description'] = $this->description;
$this->data['Vendor'] = self::VENDOR;
}
/**
* setUrls method
* Selects which SagePay url to use (live or test)
* based on the $this->env property
* @return void
* @author Pete Robinson
**/
private function setUrls()
{
$this->url = ($this->env == 'DEVELOPMENT') ? 'https://test.sagepay.com/gateway/service/vspdirect-register.vsp' : 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp';
}
/**
* setPrice method
*
* @return void
* @author Pete Robinson
**/
private function setPrice($price)
{
$this->price = $price;
}
/**
* setVendorTxCode method
*
* @return void
* @author Pete Robinson
**/
private function setVendorTxCode($code)
{
$this->vendorTxCode = $code;
}
/**
* formatData method
* Takes $this->data and converts it to
* a url encoded query string
* @return void
* @author Pete Robinson
**/
private function formatData()
{
$arr = array();
// loop through $this->data
foreach($this->data as $key => $value){
// assign as an item of $arr (field=value)
$arr[] = $key . '='. urlencode($value);
}
// Implode the array using & as the glue and store the data
$this->curl_str = implode('&', $arr);
}
/**
* execute method
* Executes the cURL request to SagePay and formats the result
*
* @return void
* @author Pete Robinson
**/
public function execute()
{
// Max exec time of 1 minute.
set_time_limit(60);
// Open cURL request
$curl_session = curl_init();
// Set the url to post request to
curl_setopt ($curl_session, CURLOPT_URL, $this->url);
// cURL params
curl_setopt ($curl_session, CURLOPT_HEADER, 0);
curl_setopt ($curl_session, CURLOPT_POST, 1);
// Pass it the query string we created from $this->data earlier
curl_setopt ($curl_session, CURLOPT_POSTFIELDS, $this->curl_str);
// Return the result instead of print
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
// Set a cURL timeout of 30 seconds
curl_setopt($curl_session, CURLOPT_TIMEOUT,30);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, FALSE);
// Send the request and convert the return value to an array
$response = preg_split('/$\R?^/m',curl_exec($curl_session));
// Check that it actually reached the SagePay server
// If it didn't, set the status as FAIL and the error as the cURL error
if (curl_error($curl_session)){
$this->status = 'FAIL';
$this->error = curl_error($curl_session);
}
// Close the cURL session
curl_close ($curl_session);
// Turn the reponse into an associative array
for ($i=0; $i < count($response); $i++){
// Find position of first "=" character
$splitAt = strpos($response[$i], "=");
// Create an associative array
$this->response[trim(substr($response[$i], 0, $splitAt))] = trim(substr($response[$i], ($splitAt+1)));
}
// Return values. Assign stuff based on the return 'Status' value from SagePay
switch($this->response['Status']) {
case 'OK':
// Transactino made succssfully
$this->status = 'success';
$_SESSION['transaction']['VPSTxId'] = $this->response['VPSTxId']; // assign the VPSTxId to a session variable for storing if need be
$_SESSION['transaction']['TxAuthNo'] = $this->response['TxAuthNo']; // assign the TxAuthNo to a session variable for storing if need be
break;
case '3DAUTH':
// Transaction required 3D Secure authentication
// The request will return two parameters that need to be passed with the 3D Secure
$this->acsurl = $this->response['ACSURL']; // the url to request for 3D Secure
$this->pareq = $this->response['PAReq']; // param to pass to 3D Secure
$this->md = $this->response['MD']; // param to pass to 3D Secure
$this->status = '3dAuth'; // set $this->status to '3dAuth' so your controller knows how to handle it
break;
case 'REJECTED':
// errors for if the card is declined
$this->status = 'declined';
$this->error = 'Your payment was not authorised by your bank or your card details where incorrect.';
break;
case 'NOTAUTHED':
// errors for if their card doesn't authenticate
$this->status = 'notauthed';
$this->error = 'Your payment was not authorised by your bank or your card details where incorrect.';
break;
case 'INVALID':
// errors for if the user provides incorrect card data
$this->status = 'invalid';
$this->error = 'One or more of your card details where invalid. Please try again.';
break;
case 'FAIL':
// errors for if the transaction fails for any reason
$this->status = 'fail';
$this->error = 'An unexpected error has occurred. Please try again.';
break;
default:
// default error if none of the above conditions are met
$this->status = 'error';
$this->error = 'An error has occurred. Please try again.';
break;
}
}
/**
* formatRawData static method
* Takes the array from the form the user fills out
* and returns an array with the correct array keys assigned to each item
*
* @param array $arr - the array of user data to process
* @return array
* @author Pete Robinson
**/
public static function formatRawData($arr)
{
$data = array();
// this is test card details for SagePay, if we are testing, we don't want to use live card details
if(ENV == 'DEVELOPMENT') {
// this is where the VendorTxCode is set. Once it's set here, don't set it anywhere else, use this one
$data['VendorTxCode'] = 'prefix_' . time() . rand(0, 9999);
$data['CardHolder'] = 'DELTA';
$data['CardNumber'] = '4462000000000003';
$data['StartDateMonth'] = '01';
$data['StartDateYear'] = '05';
$data['ExpiryDateMonth'] = '01';
$data['ExpiryDateYear'] = '12';
$data['CardType'] = 'VISA';
$data['IssueNumber'] = '';
$data['CV2'] = '123';
$data['BillingFirstnames'] = 'Tester';
$data['BillingSurname'] = 'Testing';
$data['BillingAddress1'] = '88';
$data['BillingAddress2'] = '432 Testing Road';
$data['BillingCity'] = 'Test Town';
$data['BillingCountry'] = 'GB';
$data['BillingPostCode'] = '412';
$data['Amount'] = $arr['total'];
} else {
// this is where the VendorTxCode is set. Once it's set here, don't set it anywhere else, use this one
$data['VendorTxCode'] = 'prefix_' . time() . rand(0, 9999);
// If you're using different names for your input fields for this data (card and billing address), use this section
// to map the data to the array keys that SagePay expects. I've used the same keys so this piece of code is pretty much redundant
$data['CardHolder'] = $arr['CardHolder'];
$data['CardNumber'] = $arr['CardNumber'];
$data['StartDateMonth'] = $arr['StartDateMonth'];
$data['StartDateYear'] = $arr['StartDateYear'];
$data['ExpiryDateMonth'] = $arr['ExpiryDateMonth'];
$data['ExpiryDateYear'] = $arr['ExpiryDateYear'];
$data['CardType'] = $arr['CardType'];
$data['IssueNumber'] = $arr['IssueNumber'];
$data['CV2'] = $arr['CV2'];
$data['BillingFirstnames'] = $arr['BillingFirstnames'];
$data['BillingSurname'] = $arr['BillingSurname'];
$data['BillingAddress1'] = $arr['BillingAddress1'];
$data['BillingAddress2'] = $arr['BillingAddress2'];
$data['BillingCity'] = $arr['BillingCity'];
$data['BillingCountry'] = $arr['BillingCountry'];
$data['BillingPostCode'] = $arr['BillingPostCode'];
$data['Amount'] = $arr['Amount'];
}
return $data;
}
}
/**
* SecureAuth class
* Handles the integration with 3dSecure
*
* @package Payment
* @author Pete Robinson
* @version 1.0
**/
class SecureAuth
{
public
$vendorTxCode = '', // vendor transaction code. must be unqiue
$status = '', // status returned from the cURL request
$error = ''; // stores any errors
private
$md = '', // param received from SagePay to pass with the 3D Secure request
$pareq = '', // param received from SagePay to pass with the 3D Secure request
$data = array(), // the data to post to the 3D Secure server
$response = '', // the response from the server
$url = '', // the url to pos the cURL request to
$env = '', // the environment, set according to 'ENV' site constant
$curl_str = ''; // the url encoded string derrived from the $this->data array
/**
* Constructor method
* Sets the $this->env property, assigns the necessary urls,
* sets and formats the data to pass to 3D Secure
* @return void
* @param arr $data - the data provided by the user (billing, price and card)
* @author Pete Robinson
**/
public function __construct($data)
{
$this->data = $data;
$this->env = ENV;
$this->setUrls();
$this->formatData();
$this->execute();
}
/**
* setUrls method
* Selects which SagePay url to use (live or test)
* based on the $this->env property
* @return void
* @author Pete Robinson
**/
private function setUrls()
{
$this->url = ($this->env == 'DEVELOPMENT') ? 'https://test.sagepay.com/gateway/service/direct3dcallback.vsp' : 'https://live.sagepay.com/gateway/service/direct3dcallback.vsp';
}
/**
* formatData method
* Takes $this->data and converts it to
* a url encoded query string
* @return void
* @author Pete Robinson
**/
private function formatData()
{
// Initialise arr variable
$str = array();
// Step through the fields
foreach($this->data as $key => $value){
// Stick them together as key=value pairs (url encoded)
$str[] = $key . '=' . urlencode($value);
}
// Implode the arry using & as the glue and store the data
$this->curl_str = implode('&', $str);
}
/**
* execute method
* Executes the cURL request to SagePay and formats the result
*
* @return void
* @author Pete Robinson
**/
private function execute()
{
// Max exec time of 1 minute.
set_time_limit(60);
// Open cURL request
$curl_session = curl_init();
// Set the url to post request to
curl_setopt ($curl_session, CURLOPT_URL, $this->url);
// cURL params
curl_setopt ($curl_session, CURLOPT_HEADER, 0);
curl_setopt ($curl_session, CURLOPT_POST, 1);
// Pass it the query string we created from $this->data earlier
curl_setopt ($curl_session, CURLOPT_POSTFIELDS, $this->curl_str);
// Return the result instead of print
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER,1);
// Set a cURL timeout of 30 seconds
curl_setopt($curl_session, CURLOPT_TIMEOUT,30);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, FALSE);
// Send the request and convert the return value to an array
$response = preg_split('/$\R?^/m',curl_exec($curl_session));
// Check that it actually reached the SagePay server
// If it didn't, set the status as FAIL and the error as the cURL error
if (curl_error($curl_session)){
$this->status = 'FAIL';
$this->error = curl_error($curl_session);
}
// Close the cURL session
curl_close ($curl_session);
// Turn the response into an associative array
for ($i=0; $i < count($response); $i++) {
// Find position of first "=" character
$splitAt = strpos($response[$i], '=');
// Create an associative array
$this->response[trim(substr($response[$i], 0, $splitAt))] = trim(substr($response[$i], ($splitAt+1)));
}
// Return values. Assign stuff based on the return 'Status' value from SagePay
switch($this->response['Status']) {
case 'OK':
// Transactino made succssfully
$this->status = 'success';
$_SESSION['transaction']['VPSTxId'] = $this->response['VPSTxId']; // assign the VPSTxId to a session variable for storing if need be
$_SESSION['transaction']['TxAuthNo'] = $this->response['TxAuthNo']; // assign the TxAuthNo to a session variable for storing if need be
break;
case '3DAUTH':
// Transaction required 3D Secure authentication
// The request will return two parameters that need to be passed with the 3D Secure
$this->acsurl = $this->response['ACSURL']; // the url to request for 3D Secure
$this->pareq = $this->response['PAReq']; // param to pass to 3D Secure
$this->md = $this->response['MD']; // param to pass to 3D Secure
$this->status = '3dAuth'; // set $this->status to '3dAuth' so your controller knows how to handle it
break;
case 'REJECTED':
// errors for if the card is declined
$this->status = 'declined';
$this->error = 'Your payment was not authorised by your bank or your card details where incorrect.';
break;
case 'NOTAUTHED':
// errors for if their card doesn't authenticate
$this->status = 'notauthed';
$this->error = 'Your payment was not authorised by your bank or your card details where incorrect.';
break;
case 'INVALID':
// errors for if the user provides incorrect card data
$this->status = 'invalid';
$this->error = 'One or more of your card details where invalid. Please try again.';
break;
case 'FAIL':
// errors for if the transaction fails for any reason
$this->status = 'fail';
$this->error = 'An unexpected error has occurred. Please try again.';
break;
default:
// default error if none of the above conditions are met
$this->status = 'error';
$this->error = 'An error has occurred. Please try again.';
break;
}
// set error sessions if the request failed or was declined to be handled by controller
if($this->status != 'success') {
$_SESSION['error']['status'] = $this->status;
$_SESSION['error']['description'] = $this->error;
}
}
}
?>