-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaypal_lib.php
365 lines (318 loc) · 14.4 KB
/
paypal_lib.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
<?php
// Version final
require __DIR__ . '/bootstrap.php';
require __DIR__ . '/common.php';
use PayPal\Api\ChargeModel;
use PayPal\Api\Currency;
use PayPal\Api\MerchantPreferences;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\Plan;
use PayPal\Api\Patch;
use PayPal\Api\PatchRequest;
use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\ShippingAddress;
use PayPal\Api\AgreementStateDescriptor;
use PayPal\Common\PayPalModel;
use PayPal\Api\PayerInfo;
use PayPal\Api\CreditCard;
use PayPal\Api\FundingInstrument;
/**
* @api {Definicion} createPlan($returnUrl,$arg_plan) Crear plan
* @apiDescription Crea un plan de pagos para una subscripcion en Paypal
* @apiName createPlan
* @apiGroup Paypal_Lib
*
* @apiParam {String} returnUrl URL a la cual retornara cuando el usuario termina de autorizar el pago.
* @apiParam {Array} arg_plan Arreglo de parametros<br>planType - INFINITO por defecto, puede ser REGULAR<br>currency - USD por defecto, permite cualquier codigo de moneda admitido por Paypal<br>freqCycles - 0 por defecto, cantidad de veces que se va a realizar el cobro<br>planName - Requerido, no nombre del plan<br>planDescription - Requerido, descripcion del plan<br>paymentsName - Requerido, nombre del pago cuando se cobra<br>freqInterval - Requerido, cada cuantos [freq] cobrar<br>cost - Requerido, cuanto se cobra por cada pago<br>freq - Month por defecto, tipo de frecuencia del cobro
*
* @apiSuccessExample Success:
* array(
* 'msg' => 'Plan de pagos creado y activo.',
* 'id' => [id del plan recien creado]
* );
*
* @apiErrorExample Error:
* 'Error activando el plan de pagos.'
* 'Error creando el plan de pagos.'
*/
function createPlan($returnUrl, $arg_plan) {
global $apiContext;
$plan = new Plan();
$planType = isset($arg_plan['planType'])?$arg_plan['planType']:"INFINITE";
$currency = isset($arg_plan['currency'])?$arg_plan['currency']:"USD";
$freqCycles = isset($arg_plan['freqCycles'])?$arg_plan['freqCycles']:"0";
$planName = $arg_plan['planName'];
$planDescription = $arg_plan['planDescription'];
$paymentsName = $arg_plan['paymentsName'];
$freqInterval = $arg_plan['freqInterval'];
$cost = $arg_plan['cost'];
$freq = isset($arg_plan['freq'])?$arg_plan['freq']:"Month";
$plan->setName($planName)
->setDescription($planDescription)
->setType($planType);
$paymentDefinition = new PaymentDefinition();
$paymentDefinition->setName($paymentsName)
->setType("REGULAR")
->setFrequency($freq)
->setFrequencyInterval($freqInterval)
->setCycles($freqCycles)
->setAmount(new Currency(array(
'value' => $cost,
'currency' => $currency
)
)
);
$trialDefinition = new PaymentDefinition();
$trialDefinition->setName("Trial")
->setType("TRIAL")
->setFrequency($freq)
->setFrequencyInterval("1")
->setCycles("1")
->setAmount(new Currency(array(
'value' => 0,
'currency' => $currency
)
)
);
$merchantPreferences = new MerchantPreferences();
$merchantPreferences->setReturnUrl("$returnUrl/true")
->setCancelUrl("$returnUrl/false")
->setAutoBillAmount("yes")
->setInitialFailAmountAction("CONTINUE")
->setMaxFailAttempts("0");
$plan->setPaymentDefinitions(array(
$trialDefinition,
$paymentDefinition
));
$plan->setMerchantPreferences($merchantPreferences);
try {
$createdPlan = $plan->create($apiContext);
}
catch (Exception $ex) {
return returnArray('Error creando el plan de pagos.', -4, $ex);
}
// # Update a plan ###
// ### Making Plan Active
try {
$patch = new Patch();
$value = new PayPalModel('{
"state":"ACTIVE"
}');
$patch->setOp('replace')->setPath('/')->setValue($value);
$patchRequest = new PatchRequest();
$patchRequest->addPatch($patch);
$createdPlan->update($patchRequest, $apiContext);
$plan = Plan::get($createdPlan->getId(), $apiContext);
}
catch (Exception $ex) {
return returnArray('Error activando el plan de pagos.', -5, $ex);
}
$data = array( 'msg' => 'Plan de pagos creado y activo.',
'id' => $plan->getId() );
return returnArray($data, 0);
}
function subscribe($agreement_args) {
return subscribePaypal($agreement_args);
}
/**
* @api {Definicion} subscribe($agreement_args) Suscribir
* @apiDescription Genera un acuerdo de subscripcion a un plan de pago en Paypal<br>Tipo de pago: Paypal<br>No permite pago usando tarjeta de credito.
* @apiName suscribe
* @apiGroup Paypal_Lib
*
* @apiParam {Array} agreement_args Arreglo de parametros<br>plan_id - INFINITO por defecto, puede ser REGULAR<br>agreementName - USD por defecto, permite cualquier codigo de moneda admitido por Paypal<br>agreementDesc - 0 por defecto, cantidad de veces que se va a realizar el cobro<br>agreementDate - Requerido, no nombre del plan<br>shippingLine1 - Requerido, descripcion del plan<br>shippingCity - Requerido, nombre del pago cuando se cobra<br>shippingState - Requerido, cada cuantos [freq] cobrar<br>shippingPostal - Requerido, cuanto se cobra por cada pago<br>shippingCountryCode - Month por defecto, tipo de frecuencia del cobro
*
* @apiSuccessExample Success:
* array(
* 'msg' => 'Acuerdo de pago creado y listo para aprobar.',
* 'plan' => [id del plan usado para esta subscripcion]
* 'approvalUrl' => [URL en la que el usuario ingresa su info de pago y autoriza o rechaza el cobro] );
* );
*
* @apiErrorExample Error:
* 'Error creando el acuerdo de subscripcion.'
*/
function subscribePaypal($agreement_args) {
global $apiContext;
$baseUrl = getBaseUrl();
$plan_id = $agreement_args['plan_id'];
$agreementDate = $agreement_args['agreementDate'];
if ( isset($agreement_args['prueba']) && $agreement_args['prueba'] == 'true') {
$agreementName = "nombre del acuerdo";
$agreementDesc = "descripcion del acuerdo";
$shippingLine1 = "1030 Crown Pointe Parkway";
$shippingCity = "Atlanta";
$shippingState = "GA";
$shippingPostal = "30338";
$shippingCountryCode = "US";
} else {
$agreementName = $agreement_args['agreementName'];
$agreementDesc = $agreement_args['agreementDesc'];
$shippingLine1 = getDie($agreement_args['shippingLine1']);
$shippingCity = getDie($agreement_args['shippingCity']);
$shippingState = getDie($agreement_args['shippingState']);
$shippingPostal = getDie($agreement_args['shippingPostal']);
$shippingCountryCode = getDie($agreement_args['shippingCountryCode']);
}
$agreement = new Agreement();
$agreement->setName($agreementName)
->setDescription($agreementDesc)
->setStartDate($agreementDate);
// Add Plan ID
$plan = new Plan();
$plan->setId($plan_id);
$agreement->setPlan($plan);
// Add Payer
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$agreement->setPayer($payer);
// Add Shipping Address
$shippingAddress = new ShippingAddress();
$shippingAddress->setLine1($shippingLine1)
->setCity($shippingCity)
->setState($shippingState)
->setPostalCode($shippingPostal)
->setCountryCode($shippingCountryCode);
$agreement->setShippingAddress($shippingAddress);
try {
$agreement = $agreement->create($apiContext);
$approvalUrl = $agreement->getApprovalLink();
}
catch (Exception $ex) {
return returnArray('Error creando el acuerdo de subscripcion.', -10,$ex);
}
$data = array( 'msg' => 'Acuerdo de pago creado y listo para aprobar.',
'plan' => $plan->getId(),
'approvalUrl' => $approvalUrl );
return returnArray($data, 0);
}
/**
* @api {Definicion} status($id) Estado
* @apiDescription Consulta el estado de un contrato de pago en Paypal
* @apiName status
* @apiGroup Paypal_Lib
*
* @apiParam {String} id ID del acuerdo de pago a consultar.
*
* @apiSuccessExample Success:
* array( 'msg' => 'Informacion del acuerdo de pago.',
* 'state' => [estado - Active|Cancelled],
* 'next_billing_date' => [proxima fecha de pago (si existe)],
* 'last_payment_amount' => ultimo pago (si existe),
* 'last_payment_date' => ultima fecha de pago (si existe),
* 'agreement_data' => acuerdo de pago completo en JSON );
*
* @apiErrorExample Error:
* 'Error obteniendo la informacion de este arreglo de pago.'
*/
function status($id) {
global $apiContext;
// Make a get call to retrieve the executed agreement details
try {
$agreement = Agreement::get($id, $apiContext);
}
catch (Exception $ex) {
return returnArray('Error obteniendo la informacion de este arreglo de pago.',-9,$ex);
}
$now = DateTime::createFromFormat('Y-m-d',date('Y-m-d'));
$start_date = DateTime::createFromFormat('Y-m-d', substr($agreement->start_date,0,10));
$data = array( 'msg' => 'Informacion del acuerdo de pago.',
'state' => $agreement->state,
'start_date' => $start_date->format('Y-m-d'),
//'now' => $now->format('Y-m-d'),
'next_billing_date' => isset($agreement->agreement_details->next_billing_date)?$agreement->agreement_details->next_billing_date:'not defined',
/*
'last_payment_amount' => isset($agreement->agreement_details->last_payment_amount)?$agreement->agreement_details->last_payment_amount->value:'not defined',
'last_payment_date' => isset($agreement->agreement_details->last_payment_date)?$agreement->agreement_details->last_payment_date:'not defined',
*/
'agreement_data' => json_decode($agreement->toJSON()));
return returnArray($data, 0);
}
/**
* @api {Definicion} cancel($id,$note) Cancelar
* @apiDescription Cancela una subscripcion de pago activa en Paypal
* @apiName cancel
* @apiGroup Paypal_Lib
*
* @apiParam {String} id ID del acuerdo de pago a cancelar
* @apiParam {String} note Opcional, nota a incluir en el historial del acuerdo de pago en Paypal, por defecto tiene un valor ('Cancelando el contrato')
*
* @apiSuccessExample Success:
* array('msg' => 'Acuerdo de pago cancelado.',
* 'agreement_data' => Acuerdo de pago en JSON)
*
*
* @apiErrorExample Error:
* 'Error obteniendo el arreglo de pago para cancelar.'
* 'Error, el acuerdo de pago ya se encuentra cancelado.'
* 'Error cancelando el acuerdo de pago'.
*/
function cancel($id, $note="Cancelando el contrato") {
global $apiContext;
try {
$createdAgreement = Agreement::get($id, $apiContext);
}
catch (Exception $ex) {
return returnArray('Error obteniendo el arreglo de pago para cancelar.', -6,$ex);
}
if ( $createdAgreement->state == "Cancelled" ) {
return returnArray(array('msg' => 'Error, el acuerdo de pago ya se encuentra cancelado.',
'agreement_data' => json_decode($createdAgreement->toJSON())) ,
-11);
}
$agreementStateDescriptor = new AgreementStateDescriptor();
$agreementStateDescriptor->setNote($note);
try {
$createdAgreement->cancel($agreementStateDescriptor, $apiContext);
// Lets get the updated Agreement Object
$agreement = Agreement::get($id, $apiContext);
} catch (Exception $ex) {
return returnArray('Error cancelando el acuerdo de pago.', -7,$ex);
}
return returnArray( array('msg' => 'Acuerdo de pago cancelado.',
'agreement_data' => json_decode($agreement->toJSON())) ,
0);
}
/**
* @api {Definicion} complete($result) Completar el pago
* @apiDescription Activa una subscripcion de pago cuando el usuario lo autoriza.
* @apiName complete
* @apiGroup Paypal_Lib
*
* @apiParam {Boolean} result 'true'/'false' dependiendo si el cliente autoriza el pago o no.
* @apiParam {String} token Incluido por defecto, lo incluye el SDK de Paypal cuando llama de vuelta con la autorizacion del pago.
*
* @apiSuccessExample Success:
* array('msg' => 'Acuerdo de pago aceptado por el cliente.')
*
* @apiErrorExample Error:
* 'Error intentando ejecutar el arreglo de pago.'
* 'Acuerdo de pago no aprobado por el cliente.' - Si el cliente cancelo el proceso de pago desde Paypal, retorna este valor.
*/
function complete($result) {
global $apiContext;
// ## Approval Status
// Determine if the user accepted or denied the request
if ( $result == 'true') {
// #Execute Agreement ##########################################################################################
// This is the second part of CreateAgreement Sample.
// Use this call to execute an agreement after the buyer approves it
$token = getGetDie('token');
$agreement = new Agreement();
try {
// ## Execute Agreement
// Execute the agreement by passing in the token
$agreement->execute($token, $apiContext);
}
catch (Exception $ex) {
return returnArray('Error intentando ejecutar el arreglo de pago.', -2,$ex);
}
return returnArray(
array('msg' => 'Acuerdo de pago aceptado por el cliente.',
'agreement_data' => json_decode($agreement->toJSON())
) , 0);
}
return returnArray('Acuerdo de pago no aprobado por el cliente.',-8);
}
?>