MyFatoorahPaymentStatus   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 54
c 1
b 0
f 0
dl 0
loc 190
rs 10
wmc 23

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getPaymentStatus() 0 28 5
A checkOrderInformation() 0 17 6
A getLastTransactionOfInvoiceId() 0 9 1
A getSuccessData() 0 13 3
A getLastTransactionOfPaymentId() 0 9 4
A getErrorData() 0 36 4
1
<?php
2
3
namespace MyFatoorah\Library\API\Payment;
4
5
use Exception;
6
7
/**
8
 *  MyFatoorahPaymentStatus handles the payment status of MyFatoorah API endpoints
9
 *
10
 * @author    MyFatoorah <[email protected]>
11
 * @copyright MyFatoorah, All rights reserved
12
 * @license   GNU General Public License v3.0
13
 */
14
class MyFatoorahPaymentStatus extends MyFatoorahPayment
15
{
16
    //-----------------------------------------------------------------------------------------------------------------------------------------
17
18
    /**
19
     * Get the Payment Transaction Status (POST API)
20
     *
21
     * @param int|string $keyId    MyFatoorah InvoiceId, PaymentId, or CustomerReference value.
22
     * @param string     $KeyType  The supported key types are "InvoiceId", "PaymentId", or "CustomerReference".
23
     * @param int|string $orderId  The order id in the store used to match the invoice data with store order.
24
     * @param string     $price    The order price in the store used to match the invoice data with store order.
25
     * @param string     $currency The order currency in the store used to match the invoice data with store order.
26
     *
27
     * @return object
28
     *
29
     * @throws Exception
30
     */
31
    public function getPaymentStatus($keyId, $KeyType, $orderId = null, $price = null, $currency = null)
32
    {
33
34
        //payment inquiry
35
        $curlData = ['Key' => $keyId, 'KeyType' => $KeyType];
36
        $json     = $this->callAPI("$this->apiURL/v2/GetPaymentStatus", $curlData, $orderId, 'Get Payment Status');
37
38
        $data = $json->Data;
39
40
        $msgLog = 'Order #' . $data->CustomerReference . ' ----- Get Payment Status';
41
42
        //check for the order information
43
        if (!self::checkOrderInformation($data, $orderId, $price, $currency)) {
44
            $err = 'Trying to call data of another order';
45
            $this->log("$msgLog - Exception is $err");
46
            throw new Exception($err);
47
        }
48
49
        //check invoice status (Paid and Not Paid Cases)
50
        if ($data->InvoiceStatus == 'Paid' || $data->InvoiceStatus == 'DuplicatePayment') {
51
            $data = self::getSuccessData($data);
52
            $this->log("$msgLog - Status is Paid");
53
        } elseif ($data->InvoiceStatus != 'Paid') {
54
            $data = self::getErrorData($data, $keyId, $KeyType);
55
            $this->log("$msgLog - Status is " . $data->InvoiceStatus . '. Error is ' . $data->InvoiceError);
56
        }
57
58
        return $data;
59
    }
60
61
    //-----------------------------------------------------------------------------------------------------------------------------------------
62
63
    /**
64
     * Validate the invoice data with store order data
65
     *
66
     * @param object     $data     The MyFatoorah invoice data
67
     * @param int|string $orderId  The order id in the store used to match the invoice data with store order.
68
     * @param string     $price    The order price in the store used to match the invoice data with store order.
69
     * @param string     $currency The order currency in the store used to match the invoice data with store order.
70
     *
71
     * @return boolean
72
     */
73
    private static function checkOrderInformation($data, $orderId = null, $price = null, $currency = null)
74
    {
75
76
        //check for the order ID
77
        if ($orderId && $orderId != $data->CustomerReference) {
78
            return false;
79
        }
80
81
        //check for the order price and currency
82
        list($valStr, $mfCurrency) = explode(' ', $data->InvoiceDisplayValue);
83
        $mfPrice = (double) (preg_replace('/[^\d.]/', '', $valStr));
84
85
        if ($price && $price != $mfPrice) {
86
            return false;
87
        }
88
89
        return !($currency && $currency != $mfCurrency);
90
    }
91
92
    //-----------------------------------------------------------------------------------------------------------------------------------------
93
94
    /**
95
     * Search for the success transaction and return it in the focusTransaction object
96
     *
97
     * @param object $data The payment data object
98
     *
99
     * @return object
100
     */
101
    private static function getSuccessData($data)
102
    {
103
104
        foreach ($data->InvoiceTransactions as $transaction) {
105
            if ($transaction->TransactionStatus == 'Succss') {
106
                $data->InvoiceStatus = 'Paid';
107
                $data->InvoiceError  = '';
108
109
                $data->focusTransaction = $transaction;
110
                return $data;
111
            }
112
        }
113
        return $data;
114
    }
115
116
    //-----------------------------------------------------------------------------------------------------------------------------------------
117
118
    /**
119
     * Search for the failed transaction and return it in the focusTransaction object
120
     *
121
     * @param object     $data    The payment data object
122
     * @param int|string $keyId   MyFatoorah InvoiceId, PaymentId, or CustomerReference value.
123
     * @param string     $KeyType The supported key types are "InvoiceId", "PaymentId", or "CustomerReference".
124
     *
125
     * @return object
126
     */
127
    private static function getErrorData($data, $keyId, $KeyType)
128
    {
129
130
        //------------------
131
        //case 1: payment is Failed
132
        $focusTransaction = self::{"getLastTransactionOf$KeyType"}($data->InvoiceTransactions, $keyId);
133
        if ($focusTransaction && $focusTransaction->TransactionStatus == 'Failed') {
134
            $data->InvoiceStatus = 'Failed';
135
            $data->InvoiceError  = $focusTransaction->Error . '.';
136
137
            $data->focusTransaction = $focusTransaction;
138
139
            return $data;
140
        }
141
142
        //------------------
143
        //case 2: payment is Expired
144
        //all myfatoorah gateway is set to Asia/Kuwait
145
        $ExpiryDateTime = $data->ExpiryDate . ' ' . $data->ExpiryTime;
146
        $ExpiryDate     = new \DateTime($ExpiryDateTime, new \DateTimeZone('Asia/Kuwait'));
147
        $currentDate    = new \DateTime('now', new \DateTimeZone('Asia/Kuwait'));
148
149
        if ($ExpiryDate < $currentDate) {
150
            $data->InvoiceStatus = 'Expired';
151
            $data->InvoiceError  = 'Invoice is expired since ' . $data->ExpiryDate . '.';
152
153
            return $data;
154
        }
155
156
        //------------------
157
        //case 3: payment is Pending
158
        //payment is pending .. user has not paid yet and the invoice is not expired
159
        $data->InvoiceStatus = 'Pending';
160
        $data->InvoiceError  = 'Pending Payment.';
161
162
        return $data;
163
    }
164
165
    //-----------------------------------------------------------------------------------------------------------------------------------------
166
167
    /**
168
     * Search for the failed transaction by the payment Id
169
     *
170
     * @param array      $transactions The transactions array
171
     * @param int|string $paymentId    the failed payment Id
172
     *
173
     * @return object|null
174
     */
175
    private static function getLastTransactionOfPaymentId($transactions, $paymentId)
176
    {
177
178
        foreach ($transactions as $transaction) {
179
            if ($transaction->PaymentId == $paymentId && $transaction->Error) {
180
                return $transaction;
181
            }
182
        }
183
        return null;
184
    }
185
186
    //-----------------------------------------------------------------------------------------------------------------------------------------
187
188
    /**
189
     * Search for the last transaction of an invoice
190
     *
191
     * @param array $transactions The transactions array
192
     *
193
     * @return object
194
     */
195
    private static function getLastTransactionOfInvoiceId($transactions)
196
    {
197
198
        $usortFun = function ($a, $b) {
199
            return strtotime($a->TransactionDate) - strtotime($b->TransactionDate);
200
        };
201
        usort($transactions, $usortFun);
202
203
        return end($transactions);
204
    }
205
206
    //-----------------------------------------------------------------------------------------------------------------------------------------
207
}
208