Test Setup Failed
Push — master ( f71949...6c6bd7 )
by Julito
55:21
created

paypalfunctions.php ➔ CallShortcutExpressCheckout()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 28
Code Lines 16

Duplication

Lines 4
Ratio 14.29 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 2
nop 6
dl 4
loc 28
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/********************************************
3
 * PayPal API Module
4
 *
5
 * Defines all the global variables and the wrapper functions
6
 ********************************************/
7
$PROXY_HOST = '127.0.0.1';
8
$PROXY_PORT = '808';
9
10
$SandboxFlag = $pruebas;
11
12
/**
13
 * PayPal API Credentials
14
 * Replace <API_USERNAME> with your API Username
15
 * Replace <API_PASSWORD> with your API Password
16
 * Replace <API_SIGNATURE> with your Signature
17
 */
18
$API_UserName = $paypalUsername;
19
$API_Password = $paypalPassword;
20
$API_Signature = $paypalSignature;
21
22
// BN Code is only applicable for partners
23
$sBNCode = "PP-ECWizard";
24
25
/**
26
 * Define the PayPal Redirect URLs.
27
 * This is the URL that the buyer is first sent to do authorize payment with their paypal account
28
 * change the URL depending if you are testing on the sandbox or the live PayPal site
29
 *
30
 * For the sandbox, the URL is https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
31
 * For the live site, the URL is https://www.paypal.com/webscr&cmd=_express-checkout&token=
32
 */
33
34
if ($SandboxFlag == true) {
35
    $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
36
    $PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
37
} else {
38
    $API_Endpoint = "https://api-3t.paypal.com/nvp";
39
    $PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
40
}
41
42
$USE_PROXY = false;
43
$version = "93";
44
45
if (session_id() == "") {
46
    session_start();
47
}
48
49
/**
50
 * An express checkout transaction starts with a token, that
51
 * identifies to PayPal your transaction
52
 * In this example, when the script sees a token, the script
53
 * knows that the buyer has already authorized payment through
54
 * paypal.  If no token was found, the action is to send the buyer
55
 * to PayPal to first authorize payment
56
 */
57
58
/**
59
 * Purpose: 	Prepares the parameters for the SetExpressCheckout API Call.
60
 * Inputs:
61
 *		paymentAmount:  	Total value of the shopping cart
62
 *		currencyCodeType: 	Currency code value the PayPal API
63
 *		paymentType: 		paymentType has to be one of the following values: Sale or Order or Authorization
64
 *		returnURL:			the page where buyers return to after they are done with the payment review on PayPal
65
 *		cancelURL:			the page where buyers return to when they cancel the payment review on PayPal
66
 */
67
function CallShortcutExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL, $extra)
68
{
69
    // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
70
    $nvpstr = "&PAYMENTREQUEST_0_AMT=".$paymentAmount;
71
    $nvpstr .= "&PAYMENTREQUEST_0_ITEMAMT=".$paymentAmount;
72
    $nvpstr .= "&PAYMENTREQUEST_0_PAYMENTACTION=".$paymentType;
73
    $nvpstr .= "&RETURNURL=".$returnURL;
74
    $nvpstr .= "&CANCELURL=".$cancelURL;
75
    $nvpstr .= "&PAYMENTREQUEST_0_CURRENCYCODE=".$currencyCodeType;
76
    $nvpstr .= $extra;
77
78
    $_SESSION["currencyCodeType"] = $currencyCodeType;
79
    $_SESSION["PaymentType"] = $paymentType;
80
81
    /**
82
     * Make the API call to PayPal
83
     * If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
84
     * If an error occured, show the resulting errors
85
     */
86
    $resArray = hash_call("SetExpressCheckout", $nvpstr);
87
    $ack = strtoupper($resArray["ACK"]);
88
    if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
89
        $token = urldecode($resArray["TOKEN"]);
90
        $_SESSION['TOKEN'] = $token;
91
    }
92
93
    return $resArray;
94
}
95
96
/**
97
 * Purpose: 	Prepares the parameters for the SetExpressCheckout API Call.
98
 * Inputs:
99
 *		paymentAmount:  	Total value of the shopping cart
100
 *		currencyCodeType: 	Currency code value the PayPal API
101
 *		paymentType: 		paymentType has to be one of the following values: Sale or Order or Authorization
102
 *		returnURL:			the page where buyers return to after they are done with the payment review on PayPal
103
 *		cancelURL:			the page where buyers return to when they cancel the payment review on PayPal
104
 *		shipToName:		the Ship to name entered on the merchant's site
105
 *		shipToStreet:		the Ship to Street entered on the merchant's site
106
 *		shipToCity:			the Ship to City entered on the merchant's site
107
 *		shipToState:		the Ship to State entered on the merchant's site
108
 *		shipToCountryCode:	the Code for Ship to Country entered on the merchant's site
109
 *		shipToZip:			the Ship to ZipCode entered on the merchant's site
110
 *		shipToStreet2:		the Ship to Street2 entered on the merchant's site
111
 *		phoneNum:			the phoneNum  entered on the merchant's site
112
 */
113
function CallMarkExpressCheckout($paymentAmount, $currencyCodeType, $paymentType, $returnURL,
114
                                 $cancelURL, $shipToName, $shipToStreet, $shipToCity, $shipToState,
115
                                 $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
116
)
117
{
118
    // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation
119
    $nvpstr = "&PAYMENTREQUEST_0_AMT=".$paymentAmount;
120
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_PAYMENTACTION=".$paymentType;
121
    $nvpstr = $nvpstr."&RETURNURL=".$returnURL;
122
    $nvpstr = $nvpstr."&CANCELURL=".$cancelURL;
123
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_CURRENCYCODE=".$currencyCodeType;
124
    $nvpstr = $nvpstr."&ADDROVERRIDE=1";
125
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTONAME=".$shipToName;
126
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOSTREET=".$shipToStreet;
127
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOSTREET2=".$shipToStreet2;
128
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOCITY=".$shipToCity;
129
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOSTATE=".$shipToState;
130
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=".$shipToCountryCode;
131
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOZIP=".$shipToZip;
132
    $nvpstr = $nvpstr."&PAYMENTREQUEST_0_SHIPTOPHONENUM=".$phoneNum;
133
134
    $_SESSION["currencyCodeType"] = $currencyCodeType;
135
    $_SESSION["PaymentType"] = $paymentType;
136
137
    /**
138
     * Make the API call to PayPal
139
     * If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.
140
     * If an error occured, show the resulting errors
141
     */
142
    $resArray = hash_call("SetExpressCheckout", $nvpstr);
143
    $ack = strtoupper($resArray["ACK"]);
144
    if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
145
        $token = urldecode($resArray["TOKEN"]);
146
        $_SESSION['TOKEN'] = $token;
147
    }
148
149
    return $resArray;
150
}
151
152
/**
153
 *
154
 * Purpose: Prepares the parameters for the GetExpressCheckoutDetails API Call.
155
 *
156
 * Inputs:
157
 *		None
158
 * Returns:
159
 *		The NVP Collection object of the GetExpressCheckoutDetails Call Response.
160
 */
161
162
function GetShippingDetails($token)
163
{
164
    /**
165
     * At this point, the buyer has completed authorizing the payment
166
     * at PayPal.  The function will call PayPal to obtain the details
167
     * of the authorization, including any shipping information of the
168
     * buyer.  Remember, the authorization is not a completed transaction
169
     * at this state - the buyer still needs an additional step to finalize
170
     * the transaction
171
     *
172
     * Build a second API request to PayPal, using the token as the
173
     * ID to get the details on the payment authorization
174
     */
175
    $nvpstr = "&TOKEN=".$token;
176
177
    /**
178
     * Make the API call and store the results in an array.
179
     * If the call was a success, show the authorization details, and provide
180
     * an action to complete the payment.
181
     * If failed, show the error
182
     */
183
    $resArray = hash_call("GetExpressCheckoutDetails", $nvpstr);
184
    $ack = strtoupper($resArray["ACK"]);
185
    if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
186
        $_SESSION['payer_id'] = $resArray['PAYERID'];
187
    }
188
189
    return $resArray;
190
}
191
192
/**
193
 * Purpose: 	Prepares the parameters for the GetExpressCheckoutDetails API Call.
194
 * Inputs:
195
 * sBNCode:	The BN code used by PayPal to track the transactions from a given shopping cart.
196
 * Returns:
197
 *		The NVP Collection object of the GetExpressCheckoutDetails Call Response.
198
 */
199
200
function ConfirmPayment($FinalPaymentAmt)
201
{
202
    /**
203
     * Gather the information to make the final call to
204
     * finalize the PayPal payment.  The variable nvpstr
205
     * holds the name value pairs
206
     */
207
208
    //Format the other parameters that were stored in the session from the previous calls
209
210
    $token = urlencode($_SESSION['TOKEN']);
211
    $paymentType = urlencode($_SESSION['PaymentType']);
212
    $currencyCodeType = urlencode($_SESSION['currencyCodeType']);
213
    $payerID = urlencode($_SESSION['payer_id']);
214
    $serverName = urlencode($_SERVER['SERVER_NAME']);
215
216
    $nvpstr = '&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTREQUEST_0_PAYMENTACTION='.$paymentType.'&PAYMENTREQUEST_0_AMT='.$FinalPaymentAmt;
217
    $nvpstr .= '&PAYMENTREQUEST_0_CURRENCYCODE='.$currencyCodeType.'&IPADDRESS='.$serverName;
218
    $nvpstr = '&'.http_build_query([
219
        'TOKEN' => $token,
220
        'PAYERID' => $payerID,
221
        'PAYMENTACTION' => $paymentType,
222
        'PAYMENTREQUEST_0_AMT' => $FinalPaymentAmt,
223
        'PAYMENTREQUEST_0_CURRENCYCODE' => $currencyCodeType,
224
        'IPADDRESS' => $serverName,
225
        'paymentactionspecified' => 'true'
226
    ]);
227
228
    /**
229
     * Make the call to PayPal to finalize payment
230
     * If an error occured, show the resulting errors
231
     */
232
233
    $resArray = hash_call("DoExpressCheckoutPayment", $nvpstr);
234
235
    /**
236
     * Display the API response back to the browser.
237
     * If the response from PayPal was a success, display the response parameters
238
     * If the response was an error, display the errors received using APIError.php.
239
     */
240
241
    $ack = strtoupper($resArray["ACK"]);
242
    return $resArray;
243
}
244
245
246
/**
247
 * Purpose: 	This function makes a DoDirectPayment API call
248
 * Inputs:
249
 *		paymentType:		paymentType has to be one of the following values: Sale or Order or Authorization
250
 *		paymentAmount:  	total value of the shopping cart
251
 *		currencyCode:	 	currency code value the PayPal API
252
 *		firstName:			first name as it appears on credit card
253
 *		lastName:			last name as it appears on credit card
254
 *		street:				buyer's street address line as it appears on credit card
255
 *		city:				buyer's city
256
 *		state:				buyer's state
257
 *		countryCode:		buyer's country code
258
 *		zip:				buyer's zip
259
 *		creditCardType:		buyer's credit card type (i.e. Visa, MasterCard ... )
260
 *		creditCardNumber:	buyers credit card number without any spaces, dashes or any other characters
261
 *		expDate:			credit card expiration date
262
 *		cvv2:				Card Verification Value
263
 * Returns:
264
 *		The NVP Collection object of the DoDirectPayment Call Response.
265
 */
266
267
function DirectPayment($paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
268
                       $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
269
                       $countryCode, $currencyCode)
270
{
271
    //Construct the parameter string that describes DoDirectPayment
272
    $nvpstr = "&AMT=".$paymentAmount;
273
    $nvpstr = $nvpstr."&CURRENCYCODE=".$currencyCode;
274
    $nvpstr = $nvpstr."&PAYMENTACTION=".$paymentType;
275
    $nvpstr = $nvpstr."&CREDITCARDTYPE=".$creditCardType;
276
    $nvpstr = $nvpstr."&ACCT=".$creditCardNumber;
277
    $nvpstr = $nvpstr."&EXPDATE=".$expDate;
278
    $nvpstr = $nvpstr."&CVV2=".$cvv2;
279
    $nvpstr = $nvpstr."&FIRSTNAME=".$firstName;
280
    $nvpstr = $nvpstr."&LASTNAME=".$lastName;
281
    $nvpstr = $nvpstr."&STREET=".$street;
282
    $nvpstr = $nvpstr."&CITY=".$city;
283
    $nvpstr = $nvpstr."&STATE=".$state;
284
    $nvpstr = $nvpstr."&COUNTRYCODE=".$countryCode;
285
    $nvpstr = $nvpstr."&IPADDRESS=".$_SERVER['REMOTE_ADDR'];
286
287
    $resArray = hash_call("DoDirectPayment", $nvpstr);
288
289
    return $resArray;
290
291
}
292
293
/**
294
 * Purpose: 	This function makes a MassPay API call
295
 * Inputs:
296
 *		Beneficiarie:		Array that contains the Beneficiearie paypal account and the payout amount
297
 *		Currency Code:  	The currency Iso code
298
 * Returns:
299
 *		The NVP Collection object of the MassPay Call Response.
300
 */
301
302
function MassPayment(array $beneficiaries, $currencyCode) {
303
304
    $nvpstr = "&RECEIVERTYPE=EmailAddress";
305
    $nvpstr .= "&CURRENCYCODE=".$currencyCode;
306
307
    $index = 0;
308
309
    foreach ($beneficiaries as $beneficiary) {
310
        $nvpstr .= "&L_EMAIL".$index."=".$beneficiary['paypal_account'];
311
        $nvpstr .= "&L_AMT".$index."=".$beneficiary['commission'];
312
        $index++;
313
    }
314
315
    $resArray = hash_call("MassPay", $nvpstr);
316
317
    return $resArray;
318
}
319
320
/**
321
 *
322
 * hash_call: Function to perform the API call to PayPal using API signature
323
 * @methodName is name of API  method.
324
 * @nvpStr is nvp string.
325
 * returns an associtive array containing the response from the server.
326
 *
327
 */
328
function hash_call($methodName, $nvpStr)
329
{
330
    //declaring of global variables
331
    global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
332
    global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
333
    global $sBNCode;
334
335
    //setting the curl parameters.
336
    $ch = curl_init();
337
    curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
338
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
339
    //turning off the server and peer verification(TrustManager Concept).
340
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
341
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
342
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
343
    curl_setopt($ch, CURLOPT_POST, 1);
344
345
    //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
346
    //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
347
    if ($USE_PROXY) {
348
        curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT);
349
    }
350
351
    //NVPRequest for submitting to server
352
    $nvpreq = "METHOD=".urlencode($methodName)."&VERSION=".urlencode($version).
353
        "&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName).
354
        "&SIGNATURE=".urlencode($API_Signature).$nvpStr."&BUTTONSOURCE=".urlencode($sBNCode);
355
356
    //setting the nvpreq as POST FIELD to curl
357
    curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
358
    //getting response from server
359
    $response = curl_exec($ch);
360
    //converting NVPResponse to an Associative Array
361
    $nvpResArray = deformatNVP($response);
362
    $nvpReqArray = deformatNVP($nvpreq);
363
364
    $_SESSION['nvpReqArray'] = $nvpReqArray;
365
366
    if (curl_errno($ch)) {
367
        // moving to display page to display curl errors
368
        $_SESSION['curl_error_no'] = curl_errno($ch);
369
        $_SESSION['curl_error_msg'] = curl_error($ch);
370
        //Execute the Error handling module to display errors.
371
    } else {
372
        //closing the curl
373
        curl_close($ch);
374
    }
375
376
    return $nvpResArray;
377
}
378
379
/**
380
 * Purpose: Redirects to PayPal.com site.
381
 * Inputs:  NVP string.
382
 */
383
384
function RedirectToPayPal($token)
385
{
386
    global $PAYPAL_URL;
387
    // Redirect to paypal.com here
388
    $payPalURL = $PAYPAL_URL.$token;
389
    header("Location: ".$payPalURL);
390
    exit;
391
}
392
393
/**
394
 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
395
 * It is usefull to search for a particular key and displaying arrays.
396
 * @nvpstr is NVPString.
397
 * @nvpArray is Associative Array.
398
 */
399
400
function deformatNVP($nvpstr)
401
{
402
    $intial = 0;
403
    $nvpArray = array();
404
405
    while (strlen($nvpstr)) {
406
        //postion of Key
407
        $keypos = strpos($nvpstr, '=');
408
        //position of value
409
        $valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr);
410
        /*getting the Key and Value values and storing in a Associative Array*/
411
        $keyval = substr($nvpstr, $intial, $keypos);
412
        $valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1);
413
        //decoding the respose
414
        $nvpArray[urldecode($keyval)] = urldecode($valval);
415
        $nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
416
    }
417
418
    return $nvpArray;
419
}