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