Completed
Push — master ( 953551...9f57e7 )
by Cesar
15:09 queued 11s
created

writeLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
//Require the Client library using composer: composer require pagamastarde/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 Paga+Tarde
24
 *
25
 * @throws \Httpful\Exception\ConnectionErrorException
26
 * @throws \PagaMasTarde\OrdersApiClient\Exception\ClientException
27
 * @throws \PagaMasTarde\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 \PagaMasTarde\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
        ->setDni('59661738Z')
44
        ->setFixPhone('911231234')
45
        ->setMobilePhone('600123123');
46
47
    $orderBillingAddress = $userAddress;
48
49
    $orderShippingAddress =  new \PagaMasTarde\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
        ->setDni('77695544A')
57
        ->setFixPhone('931232345')
58
        ->setMobilePhone('600123124');
59
60
    writeLog('Adding the information of the user');
61
    $orderUser = new \PagaMasTarde\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
        ->setDni('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 \PagaMasTarde\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 \PagaMasTarde\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
85
    $product
86
        ->setAmount('59999')
87
        ->setQuantity('1')
88
        ->setDescription('TV LG UltraPlana');
89
90
    $details = new \PagaMasTarde\OrdersApiClient\Model\Order\ShoppingCart\Details();
91
    $details->setShippingCost('0');
92
    $details->addProduct($product);
93
94
    $orderShoppingCart = new \PagaMasTarde\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 \PagaMasTarde\OrdersApiClient\Model\Order\Configuration\Urls();
108
    $orderConfigurationUrls
109
        ->setCancel($errorUrl)
110
        ->setKo($errorUrl)
111
        ->setNotificationCallback($confirmUrl)
112
        ->setOk($confirmUrl);
113
114
    writeLog('Adding channel info');
115
    $orderChannel = new \PagaMasTarde\OrdersApiClient\Model\Order\Configuration\Channel();
116
    $orderChannel
117
        ->setAssistedSale(false)
118
        ->setType(\PagaMasTarde\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE);
119
120
    $orderConfiguration = new \PagaMasTarde\OrdersApiClient\Model\Order\Configuration();
121
    $orderConfiguration
122
        ->setChannel($orderChannel)
123
        ->setUrls($orderConfigurationUrls);
124
    writeLog('Created Configuration object');
125
126
    $order = new \PagaMasTarde\OrdersApiClient\Model\Order();
127
    $order
128
        ->setConfiguration($orderConfiguration)
129
        ->setShoppingCart($orderShoppingCart)
130
        ->setUser($orderUser);
131
132
    writeLog('Creating OrdersApiClient');
133
    if (PUBLIC_KEY=='' || PRIVATE_KEY == '') {
0 ignored issues
show
introduced by
The condition PUBLIC_KEY == '' is always true.
Loading history...
134
        throw new \Exception('You need set the public and private key');
135
    }
136
    $orderClient = new \PagaMasTarde\OrdersApiClient\Client(PUBLIC_KEY, PRIVATE_KEY);
137
138
    writeLog('Creating Paga+Tarde order');
139
    $order = $orderClient->createOrder($order);
140
    if ($order instanceof \PagaMasTarde\OrdersApiClient\Model\Order) {
141
        //If the order is correct and created then we have the redirection URL here:
142
        $url = $order->getActionUrls()->getForm();
143
        $_SESSION['order_id'] = $order->getId();
144
        writeLog(json_encode(
145
            $order->export(),
146
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
147
        ));
148
    } else {
149
        throw new \Exception('Order not created');
150
    }
151
152
    // You can use our test credit cards to fill the Paga+Tarde form
153
    writeLog("Redirecting to Paga+Tarde form => $url");
154
    header('Location:'. $url);
155
}
156
157
/**
158
 * Confirm order in Paga+Tarde
159
 *
160
 * @throws \Httpful\Exception\ConnectionErrorException
161
 * @throws \PagaMasTarde\OrdersApiClient\Exception\ClientException
162
 * @throws \PagaMasTarde\OrdersApiClient\Exception\HttpException
163
 */
164
function confirmOrder()
165
{
166
    /* Once the user comes back to the OK url or there is a notification upon callback url you will have to confirm
167
     * the reception of the order. If not it will expire and will never be paid.
168
     *
169
     * Add this parameters in your database when you create a order and map it to your own order. Or search orders by
170
     * your own order id. Both options are possible.
171
     */
172
173
    writeLog('Creating OrdersApiClient');
174
    $orderClient = new \PagaMasTarde\OrdersApiClient\Client(PUBLIC_KEY, PRIVATE_KEY);
175
176
    $order = $orderClient->getOrder($_SESSION['order_id']);
177
178
    if ($order instanceof \PagaMasTarde\OrdersApiClient\Model\Order &&
179
        $order->getStatus() == \PagaMasTarde\OrdersApiClient\Model\Order::STATUS_AUTHORIZED) {
180
        //If the order exists, and the status is authorized, means you can mark the order as paid.
181
182
        //DO WHATEVER YOU NEED TO DO TO MARK THE ORDER AS PAID IN YOUR OWN SYSTEM.
183
        writeLog('Confirming order');
184
        $order = $orderClient->confirmOrder($order->getId());
185
186
        writeLog('Order confirmed');
187
        writeLog(json_encode(
188
            $order->export(),
189
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
190
        ));
191
        $message = "The order {$_SESSION['order_id']} has been confirmed successfully";
192
    } else {
193
        $message = "The order {$_SESSION['order_id']} can't be confirmed";
194
    }
195
196
    /* The order has been marked as paid and confirmed in Paga+Tarde so you will send the product to your customer and
197
     * Paga+Tarde will pay you in the next 24h.
198
     */
199
200
    echo $message;
201
    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...
202
}
203
204
/**
205
 * Action after redirect to cancelUrl
206
 */
207
function cancelOrder()
208
{
209
    $message = "The order {$_SESSION['order_id']} can't be created";
210
211
    echo $message;
212
    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...
213
}
214
215
/**
216
 * UTILS
217
 */
218
219
/**
220
 * Write log file
221
 *
222
 * @param $message
223
 */
224
function writeLog($message)
225
{
226
    file_put_contents('pmt.log', "$message.\n", FILE_APPEND);
227
}
228