Passed
Pull Request — master (#26)
by
unknown
01:41
created

isGetActionValid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
//Require the Client library using composer: composer require pagantis/orders-api-client
4
require_once('../../vendor/autoload.php');
5
/**
6
 * Require the helper functions
7
 * ⚠⚠⚠
8
 * PLEASE SET YOUR PUBLIC KEY AND PRIVATE KEY
9
 * IN examples/utils/Helpers.php
10
 * ⚠⚠⚠
11
 */
12
require_once('../utils/Helpers.php');
13
14
15
16
const ORDER_ID      = 'order_4159972708';
17
18
19
try {
20
    session_start();
21
    $method = getGetAction();
22
    call_user_func($method);
23
} catch (\Exception $e) {
24
    echo $e->getMessage();
25
    exit;
26
}
27
28
29
/**
30
 * Create order in Pagantis
31
 *
32
 * @throws \Httpful\Exception\ConnectionErrorException
33
 * @throws \Pagantis\OrdersApiClient\Exception\ClientException
34
 * @throws \Pagantis\OrdersApiClient\Exception\HttpException
35
 * @throws \Exception
36
 */
37
function createOrder()
38
{
39
    // There are  3 mandatory objects: User object, ShoppingCart object and Configuration object.
40
41
    //1. User Object
42
    $logsWithDate = true;
43
    $logsFileName = basename(__FILE__);
44
    
45
    writeLog('Creating User object', $logsFileName, $logsWithDate);
46
    
47
    $userAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
48
    $userAddress->setZipCode('28031')
49
                ->setFullName('María Sanchez Escudero')
50
                ->setCountryCode('ES')
51
                ->setCity('Madrid')
52
                ->setAddress('Paseo de la Castellana, 95')
53
                ->setDni('59661738Z')
54
                ->setNationalId('59661738Z')
55
                ->setFixPhone('911231234')
56
                ->setMobilePhone('600123123');
57
    
58
    $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
59
    $orderBillingAddress->setZipCode('28031')
60
                        ->setFullName('María Sanchez Escudero')
61
                        ->setCountryCode('ES')
62
                        ->setCity('Madrid')
63
                        ->setAddress('Paseo de la Castellana, 95')
64
                        ->setDni('59661738Z')
65
                        ->setNationalId('59661738Z')
66
                        ->setFixPhone('911231234')
67
                        ->setMobilePhone('600123123');
68
    writeLog('Adding the address of the user', $logsFileName, $logsWithDate);
69
    $orderShippingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
70
71
    $orderShippingAddress->setZipCode('08029')
72
                         ->setFullName('Alberto Escudero Sanchez')
73
                         ->setCountryCode('ES')
74
                         ->setCity('Barcelona')
75
                         ->setAddress('Avenida de la diagonal 525')
76
                         ->setDni('77695544A')
77
                         ->setNationalId('59661738Z')
78
                         ->setFixPhone('931232345')
79
                         ->setMobilePhone('600123124');
80
    writeLog('Adding the information of the user', $logsFileName, $logsWithDate);
81
    $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
82
    $orderUser->setFullName('María Sanchez Escudero')
83
              ->setAddress($userAddress)
84
              ->setBillingAddress($orderBillingAddress)
85
              ->setShippingAddress($orderShippingAddress)
86
              ->setDateOfBirth('1985-12-30')
87
              ->setEmail('[email protected]')
88
              ->setFixPhone('911231234')
89
              ->setMobilePhone('600123123')
90
              ->setDni('59661738Z')
91
              ->setNationalId('59661738Z');
92
    writeLog('User object created', $logsFileName, $logsWithDate);
93
94
    //2. ShoppingCart Object
95
    writeLog('Creating ShoppingCart object', $logsFileName, $logsWithDate);
96
    writeLog('Adding the purchases of the customer, if there are any.', $logsFileName, $logsWithDate);
97
    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
98
    $orderHistory->setAmount('2499')
99
                 ->setDate('2010-01-31');
100
    
101
    $orderUser->addOrderHistory($orderHistory);
102
103
    writeLog('Adding cart products. Minimum 1 required', $logsFileName, $logsWithDate);
104
    $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
105
    $product->setAmount('59999')
106
            ->setQuantity('1')
107
            ->setDescription('TV LG UltraPlasma');
108
109
    $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
110
    $details->setShippingCost('0');
111
    $details->addProduct($product);
112
113
    $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
114
    $orderShoppingCart->setDetails($details)
115
                      ->setOrderReference(ORDER_ID)
116
                      ->setPromotedAmount(0) // This amount means that the merchant will assume the interests.
117
                      ->setTotalAmount('59999');
118
    writeLog('Created OrderShoppingCart object', $logsFileName, $logsWithDate);
119
120
    //3. Configuration Object
121
    writeLog('Creating Configuration object', $logsFileName, $logsWithDate);
122
    writeLog('Adding urls to redirect the user according each case', $logsFileName, $logsWithDate);
123
124
    $confirmUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?action=confirmOrder";
125
    $errorUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?action=cancelOrder";
126
127
    $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
128
    $orderConfigurationUrls->setCancel($errorUrl)
129
                           ->setKo($errorUrl)
130
                           ->setAuthorizedNotificationCallback($confirmUrl)
131
                           ->setRejectedNotificationCallback($confirmUrl)
132
133
                           ->setOk($confirmUrl);
134
    writeLog('Adding channel info', $logsFileName, $logsWithDate);
135
136
    $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
137
    $orderChannel->setAssistedSale(false)
138
                 ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE);
139
140
    $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
141
    $orderConfiguration->setChannel($orderChannel)
142
                       ->setUrls($orderConfigurationUrls);
143
144
    writeLog('Created Configuration object', $logsFileName, $logsWithDate);
145
146
    $order = new \Pagantis\OrdersApiClient\Model\Order();
147
    $order->setConfiguration($orderConfiguration)
148
          ->setShoppingCart($orderShoppingCart)
149
          ->setUser($orderUser);
150
151
    writeLog('Creating OrdersApiClient', $logsFileName, $logsWithDate);
152
    $orderClient = getOrderApiClient();
153
154
    writeLog('Creating Pagantis order', $logsFileName, $logsWithDate);
155
    $order = $orderClient->createOrder($order);
156
157
    writeLog(
158
        "Pagantis Order Created ID: " . jsonEncoded($_SESSION['order_id']),
159
        $logsFileName,
160
        $logsWithDate
161
    );
162
163
    writeLog('Processing order' . jsonEncoded($order->getId()), $logsFileName, $logsWithDate);
164
165
    if (!isOrderIdValid($order)) {
166
        throw new \Exception('Order not valid');
167
    }
168
    //If the order is created and valid then we have the redirection URL here:
169
    // $formUrl = $order->getActionUrls()->getForm();
170
171
    $_SESSION['order_id'] = $order->getId();
172
173
    writeLog(jsonEncoded($order->export()), basename(__FILE__), $logsWithDate);
174
    $formUrl = $order->getActionUrls()
175
                     ->getForm();
176
    // You can use our test credit cards to fill the Pagantis form
177
    writeLog("Redirecting to Pagantis form => $formUrl", $logsFileName, $logsWithDate);
178
    header('Location:' . $formUrl);
179
}
180
181
/**
182
 * Confirm order in Pagantis
183
 *
184
 * @throws \Httpful\Exception\ConnectionErrorException
185
 * @throws \Pagantis\OrdersApiClient\Exception\ClientException
186
 * @throws \Pagantis\OrdersApiClient\Exception\HttpException
187
 * @throws \Exception
188
 */
189
function confirmOrder()
190
{
191
    /* Once the user comes back to the OK url or there is a notification upon callback url, you will have to confirm
192
     * the reception of the order. If not it will expire  and will never be paid out.
193
     *
194
     * Add these parameters to your database when you create a order and map it to your own order. Alternatively search orders by internal
195
     * order id. Both options are possible.
196
     */
197
198
    $logsFileName = basename(__FILE__);
199
    $logsWithDate = true;
200
    writeLog('Creating OrdersApiClient', $logsFileName, $logsWithDate);
201
    $orderClient = getOrderApiClient();
202
203
    $order = $orderClient->getOrder($_SESSION['order_id']);
204
205
    if ($order instanceof \Pagantis\OrdersApiClient\Model\Order
206
        && $order->getStatus() == \Pagantis\OrdersApiClient\Model\Order::STATUS_AUTHORIZED
207
    ) {
208
        //If the order exists, and the status is authorized, means you can mark the order as paid.
209
210
        //DO WHATEVER YOU NEED TO DO TO MARK THE ORDER AS PAID IN YOUR OWN SYSTEM.
211
        writeLog('Confirming order', $logsFileName, $logsWithDate);
212
        $order = $orderClient->confirmOrder($order->getId());
213
214
        writeLog('Order confirmed', $logsFileName, $logsWithDate);
215
        writeLog(jsonEncoded($order->export()), $logsFileName, $logsWithDate);
216
217
        $message = "The order {$_SESSION['order_id']} has been confirmed successfully";
218
        writeLog($message, $logsFileName, $logsWithDate);
219
    }
220
    $message = "The order {$_SESSION['order_id']} can't be confirmed";
221
    writeLog($message, $logsFileName, $logsWithDate);
222
223
    /* The order has been marked as paid and confirmed in Pagantis so you will send the product to your customer and
224
     * Pagantis will pay you in the next 24h.
225
     */
226
227
    echo $message;
228
    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
229
}
230
231
/**
232
 * Action after redirect to cancelUrl
233
 */
234
function cancelOrder()
235
{
236
    $message = "The order {$_SESSION['order_id']} can't be created";
237
    writeLog($message, $logsFileName = basename(__FILE__), $logsWithDate =true);
238
    echo $message;
239
    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
240
}
241
242
243
/**
244
 * @return mixed|string
245
 */
246
function getGetAction()
247
{
248
    if (!isGetActionValid()) {
249
        return 'createOrder';
250
    };
251
    $method = json_decode(json_encode($_GET));
252
    writeLog("Method->action " . $method->action, basename(__FILE__), $logsWithDate = true);
253
    return $method->action;
254
}
255
256
/**
257
 * @param $order
258
 *
259
 * @return bool
260
 */
261
function isOrderIdValid($order)
262
{
263
    if (!$order instanceof \Pagantis\OrdersApiClient\Model\Order) {
264
        return false;
265
    }
266
    return true;
267
}
268
269
/**
270
 * @return bool
271
 */
272
function isGetActionValid()
273
{
274
    if (!array_key_exists('action', $_GET)) {
275
        return false;
276
    }
277
    return true;
278
}
279
280