Passed
Pull Request — master (#59)
by Raúl
05:19 queued 01:21
created

createOrder()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 126
Code Lines 101

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 101
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 126
rs 8

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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