🍲dfcv🏰dd⋉(● ∸ ●)⋊@% PNG %k25u25%fgd5n! PNG %k25u25%fgd5n!library/tests/API/Payment/MyFatoorahPaymentStatusTest.php000064400000002561152427537230017602 0ustar00keys = include __DIR__ . '/../../apiKeys.php'; } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetPaymentStatus() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahPaymentStatus($config); $data = $mfObj->getPaymentStatus('100202312116138082', 'PaymentId'); $this->assertEquals('Paid', $data->InvoiceStatus); } catch (\Exception $ex) { $exception = $config['getPaymentStatusException'] ?? $config['exception']; $this->assertEquals($exception, $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- } library/tests/API/Payment/MyFatoorahPaymentEmbeddedTest.php000064400000002455152427537230020012 0ustar00keys = include __DIR__ . '/../../apiKeys.php'; } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetCheckoutGateways() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahPaymentEmbedded($config); $data = $mfObj->getCheckoutGateways(10, 'KWD', false); $this->assertArrayHasKey('PaymentMethodId', (array) $data['all'][0]); } catch (\Exception $ex) { $this->assertEquals($config['exception'], $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- } library/tests/API/Payment/MyFatoorahPaymentTest.php000064400000003514152427537230016375 0ustar00keys = include __DIR__ . '/../../apiKeys.php'; } //----------------------------------------------------------------------------------------------------------------------------------------- public function testInitiatePayment() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahPayment($config); $json = $mfObj->initiatePayment(); $this->assertArrayHasKey('PaymentMethodId', (array) $json[0]); } catch (\Exception $ex) { $this->assertEquals($config['exception'], $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- /** * change the accessibility of a function * usage $method->invokeArgs($mfObj, [$ua]); * * @param type $name * @return type */ // protected static function getMethod($name) { // $class = new \ReflectionClass('\MyFatoorah\Library\MyfatoorahPayment'); // $method = $class->getMethod($name); // $method->setAccessible(true); // return $method; // } //----------------------------------------------------------------------------------------------------------------------------------------- } library/tests/API/MyFatoorahRefundTest.php000064400000004452152427537230014570 0ustar00keys = include __DIR__ . '/../apiKeys.php'; } //----------------------------------------------------------------------------------------------------------------------------------------- public function testRefund() { try { $mfObj = new MyFatoorahRefund($this->keys['valid']); $json = $mfObj->refund('100202312116138082', 10, 'KWD', 'test'); $this->assertEquals('100202312116138082', $json->Key); $this->assertNotNull($json->RefundReference); } catch (\Exception $ex) { $this->assertEquals($this->keys['valid']['refundException'], $ex->getMessage(), $this->keys['valid']['message']); } } //----------------------------------------------------------------------------------------------------------------------------------------- public function testMakeRefund() { $postFields = [ 'Key' => 100202312116138082, 'KeyType' => 'PaymentId', 'RefundChargeOnCustomer' => false, 'ServiceChargeOnCustomer' => false, 'Amount' => 2, 'CurrencyIso' => 'KWD', 'Comment' => 'test' ]; foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahRefund($config); $json = $mfObj->makeRefund($postFields); $this->assertEquals('100202312116138082', $json->Key); $this->assertNotNull($json->RefundReference); } catch (\Exception $ex) { $exception = $config['refundException'] ?? $config['exception']; $this->assertEquals($exception, $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- } library/tests/API/MyFatoorahShippingTest.php000064400000007630152427537230015127 0ustar00keys = include __DIR__ . '/../apiKeys.php'; } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetShippingCountries() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahShipping($config); $data = $mfObj->getShippingCountries(); $this->assertEquals('AD', $data[0]->CountryCode); $this->assertEquals('ANDORRA', $data[0]->CountryName); } catch (\Exception $ex) { $this->assertEquals($config['exception'], $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetShippingCities() { foreach ($this->keys as $config) { try { $mfObj = new MyfatoorahShipping($config); $cities = $mfObj->getShippingCities(1, 'KW', 'ada'); $this->assertEquals('ADAN', $cities[0]); $this->assertEquals('SHUHADA', $cities[1]); } catch (\Exception $ex) { $this->assertEquals($config['exception'], $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- public function testCalculateShippingCharge() { $mfObj = new MyfatoorahShipping($this->keys['valid']); $shippingData = [ 'ShippingMethod' => 1, 'Items' => [ [ 'ProductName' => 'product', 'Description' => 'product', 'Weight' => 10, 'Width' => 10, 'Height' => 10, 'Depth' => 10, 'Quantity' => 1, 'UnitPrice' => '17.234', ] ], 'CountryCode' => 'KW', 'CityName' => 'adan', 'PostalCode' => '12345', ]; $data = $mfObj->calculateShippingCharge($shippingData); $this->assertEquals('KD', $data->Currency); } public function testCalculateShippingChargeExceptionProductName() { $mfObj = new MyfatoorahShipping($this->keys['valid']); //test empty ProductName $shippingData1 = [ 'ShippingMethod' => 1, 'Items' => [[ 'ProductName' => '', 'Description' => 'product', 'Weight' => 10, 'Width' => 10, 'Height' => 10, 'Depth' => 10, 'Quantity' => 1, 'UnitPrice' => '17.234', ]], 'CountryCode' => 'KW', 'CityName' => 'adan', 'PostalCode' => '12345', ]; $this->expectException(\Exception::class); $this->expectExceptionMessage('model.Items[0].ProductName: The field Product Name (En) is mandatory.'); $mfObj->calculateShippingCharge($shippingData1); } //----------------------------------------------------------------------------------------------------------------------------------------- } library/tests/API/MyFatoorahSupplierTest.php000064400000005221152427537230015143 0ustar00keys = include __DIR__ . '/../apiKeys.php'; } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetSupplierDashboard() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahSupplier($config); $data = $mfObj->getSupplierDashboard(1); $this->assertArrayHasKey('TotalAwaitingBalance', (array) $data); } catch (\Exception $ex) { $exception = $config['supplierException'] ?? $config['exception']; $this->assertEquals($exception, $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- public function testIsSupplierApproved() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahSupplier($config); $data = $mfObj->isSupplierApproved(1); $this->assertTrue($data); } catch (\Exception $ex) { $exception = $config['supplierException'] ?? $config['exception']; $this->assertEquals($exception, $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- public function testIsSupplierApprovedNotCreated() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahSupplier($config); $data = $mfObj->isSupplierApproved(3232323); $this->assertTrue($data); } catch (\Exception $ex) { $exception = $config['supplierException'] ?? $config['exception']; $this->assertEquals($exception, $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- } library/tests/API/MyFatoorahListTest.php000064400000002556152427537230014263 0ustar00keys = include __DIR__ . '/../apiKeys.php'; } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetCurrencyRates() { foreach ($this->keys as $config) { try { $mfObj = new MyFatoorahList($config); $json = $mfObj->getCurrencyRates(); $this->assertEquals('1.00000000', $json[0]->Value); $this->assertEquals('KWD', $json[0]->Text, $config['message']); } catch (\Exception $ex) { $exception = $config['getCurrencyRatesException'] ?? $config['exception']; $this->assertEquals($exception, $ex->getMessage(), $config['message']); } } } //----------------------------------------------------------------------------------------------------------------------------------------- } library/tests/apiKeys.php000064400000007434152427537230011512 0ustar00 [ 'apiKey' => 'rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL', 'countryCode' => 'KWT', 'isTest' => true, 'message' => 'Valid', 'exception' => '', 'refundException' => 'Key: The transaction is already under processing!', 'supplierException' => 'Not Found', ], 'noContent' => [ 'apiKey' => 'qrLtt6JWvbUHD', 'countryCode' => 'KWT', 'isTest' => true, 'message' => 'No Content', 'exception' => 'Kindly review your MyFatoorah admin configuration due to a wrong entry.', 'getCurrencyRatesException' => 'Authorization has been denied for this request.' ], 'expired' => [ 'apiKey' => '2ZR_G9WiA5NKptj6E7uEUXITVfpNzczNbCZben0WFD3zZnyRJ3pqc579oBT1Mm6BkoVLOUnHVxf_B729jI6nHdIGlEt4lMJtx4nrC6X7bV4zz8TtQHBsTTBEfc7BZa3nEgYjasZ-iuTYERdZriZy14Bzby7DVhoT8lGxKO0OdgAuW5rqtNQihsrWXZXa69N3JRrESAfcvekhhjU1_g5JtNKdPYblrwhlGJnVvTovbdJa0vEWClLUyKUvziJZE-FmdF9RMlIPnylL4cdHVf1pUK9uPsYJ7Q-B8i-NV1kU07Q9wVk5vsnSdKgUXOtMCC19rDWlro4MYY2kQvuPDKwyMB7DjLbq_psbkmuXi7oEq-f5H1oEaVl_LLCIusQu2_tE4E7hslr31TlAguKkSNMlQ3IES7VgMu7F4Yi-ploiBoTR1eV8Qcy2fKXXlPQv_YKjXj8uYsIe-5Dl34tPfMIDUVKXAH44KmnLhlw68J56WC5n1t-rDGQT299wXsXfKCuhn53yzIH9tAxX0Tm3Jnq1GNLvGtGOwqOzOncbhfuwEXlbpi83SKhyTo9B8JDFsGDmQfzgRZlnlwmvqc2CmrBdxCOG0zll1XKJ9YYKhdSplHsFcshaAYWl9pypEb7272GiuJXKhvES1tQ1mzegMEou019GvMUxmcLnBlMUF9MrorOdvvDD', 'countryCode' => 'KWT', 'isTest' => true, 'message' => 'Expired', 'exception' => 'The token is not valid or it is expired!' ], 'notAuthorized' => [ 'apiKey' => '0LLrGl7Il9eO-sbFpneJbjGzjqHVqddt1MTAbi8uJS9Zhg0kuUwvv23kTKR-ZgTzAZxsNotlHX3knyDtsxpJsSa5YoywApfAG0eUvnMUY2mA211f_gRh0JhD9m_lVbhsTbavYkrfhh7Zb5P-KKfxhszEbNyUZM1mPfZ5UhrfjodKuUP_Q-Wu5iYxXP6jLOFDQTCSj3IjU0EZSvetcblo6g6wZ6IKjPGbESFn_1K1PswvrGKYjhWAACc6w_RcWt13k5NwNSZgPXlmVeEDTa7azgqArmSHk0f3Fz_3o4JytdaqdbJ3AfaVbz6S9oCtD8Vv_uwJMEn2xQvXagbTJ3g6TRxL1vs8zjY-KIKLlupmnq94pUijzSjj4hnY60YaxcYXn4rIWQtqoqbMExzHEsbhXdCefiqVu7-IXpYQpyVnXndH9dqXYAhXuOFBgv7E5pmarwq7EbozX5S0zQov38R4AsFvQUNHa2fj2R0yrX7iEzo96HHzaWvAnMFX6qVGbnJbNLpKgkjt5SHHYLzd8pPcDCwu2RNTGkHvw720qM6ifuNc2qN5KQgLwVgJ59fOpMWFA66dkCCjqKIQQgwbHLSxvLkSLlbh3DtcKtk3YCkPgXj5mwH7GCGcK_xyu8ZREgRSedM7ev7wL5tciZ6sTXWFQLXrNp3hdkk2x7Emm8WD2w5J89rA', 'countryCode' => 'KWT', 'isTest' => true, 'message' => 'Not Authorized', 'exception' => 'Exception: You are not Authorized to use API.', 'getCurrencyRatesException' => 'You are not Authorized to use API.', //'exception' => 'Invalid Account Information!, Please check the Dhl account information and try again.', //'refundException' => 'Key: No transaction exist matching this Key!', //'supplierException' => 'Not Found', //'getPaymentStatusException' => 'No data match the provided values' ] ]; library/tests/MyFatoorahHelperTest.php000064400000020122152427537230014143 0ustar00assertEquals('', $expected[0]); $this->assertEquals('', $expected[1]); $expected1 = MyFatoorah::getPhone('+2 01234567890'); $this->assertEquals('201', $expected1[0]); $this->assertEquals('234567890', $expected1[1]); $expected2 = MyFatoorah::getPhone('+201234567890'); $this->assertEquals('201', $expected2[0]); $this->assertEquals('234567890', $expected2[1]); $expected3 = MyFatoorah::getPhone('00201234567890'); $this->assertEquals('201', $expected3[0]); $this->assertEquals('234567890', $expected3[1]); $expected4 = MyFatoorah::getPhone('002031234567'); $this->assertEquals('203', $expected4[0]); $this->assertEquals('1234567', $expected4[1]); $expected5 = MyFatoorah::getPhone('٠٠٢٠١٢٣٤٥٦٧٨٩٠'); $this->assertEquals('201', $expected5[0]); $this->assertEquals('234567890', $expected5[1]); } public function testGetPhoneException1() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Phone Number lenght must be between 3 to 14 digits'); MyFatoorah::getPhone('12'); } public function testGetPhoneException2() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Phone Number lenght must be between 3 to 14 digits'); MyFatoorah::getPhone('12345678910123456'); } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetWeightRate() { $expected1 = MyFatoorah::getWeightRate('KG'); $this->assertEquals(1, $expected1); $expected2 = MyFatoorah::getWeightRate('kg'); $this->assertEquals(1, $expected2); $expected3 = MyFatoorah::getWeightRate('oZ'); $this->assertEquals(0.0283495, $expected3); } public function testGetWeightRateException1() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Weight units must be in kg, g, lbs, or oz. Default is kg'); MyFatoorah::getWeightRate(''); } public function testGetWeightRateException2() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Weight units must be in kg, g, lbs, or oz. Default is kg'); MyFatoorah::getWeightRate('sss'); } //----------------------------------------------------------------------------------------------------------------------------------------- public function testGetDimensionRate() { $expected = MyFatoorah::getDimensionRate('CM'); $this->assertEquals(1, $expected); $expected2 = MyFatoorah::getDimensionRate('cm'); $this->assertEquals(1, $expected2); $expected3 = MyFatoorah::getDimensionRate('mM'); $this->assertEquals(0.1, $expected3); } public function testGetDimensionRateException1() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Dimension units must be in cm, m, mm, in, or yd. Default is cm'); MyFatoorah::getDimensionRate(''); } public function testGetDimensionRateException2() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Dimension units must be in cm, m, mm, in, or yd. Default is cm'); MyFatoorah::getDimensionRate('sss'); } //----------------------------------------------------------------------------------------------------------------------------------------- public function testIsSignatureValid() { $MyFatoorah_Signature1 = 'uRBOogk9ek7Hgsxs/Rt7Nvbu7Vxf+4eI5gwvbtg0NCw='; $MyFatoorah_Signature2 = '0YPWuCj1yxScY1gWMUCtilqTL76AAPna8EqedMikhuI='; $MyFatoorah_Signature3 = 'XdNvAIV8ZN6CmB2zzapnSemO6lDUpwKk2g/a11GxI8U='; $MyFatoorah_Signature4 = '4jsjl0JdWsTLBxqfJ7VxLFLoNhi1EqJaz1c+Z+ri02w='; $secret1 = '7wNeL4LfSs/EHVOf0Xzeq1ja+HbPr//2XC2fZO24wA6479AT8o84BmELU2FiRwIpd+rM9W5/egjFuihNSXsHKw=='; $secret2 = 'Yfsa6MHREzuK+z9VLF3SmoDsdLFEguH970BISF44h5qTSy1jWeH/3FxSVGCEqMPadSmGthmyHP1oz2PFqhoVdg=='; $secret3 = 'kOYhtuna3DmVilmtlTFI6wNAUX2dH+LSHdMLrmSAjamZKC4B7uSVJmB0+nch4ITGt95ZxoUfQ6Mhbzte7UG7Mw=='; $secret4 = 'tEtrecTNgRTu+zmde7OZ8pyy62kQTo2sT/tYG0DO2JT626XRKTWeUqwyXsDfE4kMsMSGxjP7KbV0h8pdFG1Pgg=='; $body1 = '{"EventType":3,"Event":"BalanceTransferred","DateTime":"04072021100512","CountryIsoCode":"KWT","Data":{"DepositReference":"2021000008","DepositedAmount":"1520.664","NumberOfTransactions":"47","DepositFor":"VENDOR","SupplierCode":null}}'; $body2 = '{"EventType":1,"Event":"BalanceTransferred","DateTime":"04072021100512","CountryIsoCode":"KWT","Data":{"InvoiceId": 34959075,"InvoiceReference": "2021000088","CreatedDate": "24082021144854","CustomerReference": "6124dca568974cf05d7f1e0c","CustomerName": "THE COW","CustomerMobile": "+96590088538","CustomerEmail": null,"TransactionStatus": "SUCCESS","PaymentMethod": "KNET","UserDefinedField": null,"ReferenceId": "123655013425","TrackId": "24-08-2021_32916777","PaymentId": "109202123602930060","AuthorizationId": "659726","InvoiceValueInBaseCurrency": "2.5","BaseCurrency": "KWD","InvoiceValueInDisplayCurreny": "2.5","DisplayCurrency": "KWD","InvoiceValueInPayCurrency": "2.5","PayCurrency": "KWD"}}'; $body3 = '{"EventType":1,"Event":"TransactionsStatusChanged","DateTime":"13092021114623","CountryIsoCode":"KWT","Data":{"InvoiceId":994285,"InvoiceReference":"2021001240","CreatedDate":"13092021114006","CustomerReference":"139","CustomerName":"رشا سعيد","CustomerMobile":"123456789","CustomerEmail":"rsaeed@myfatoorah.com","TransactionStatus":"FAILED","PaymentMethod":"KNET","UserDefinedField":"139","ReferenceId":"060699428581329564","TrackId":"13-09-2021_813295","PaymentId":"100202125611400734","AuthorizationId":"060699428581329564","InvoiceValueInBaseCurrency":"10.942","BaseCurrency":"KWD","InvoiceValueInDisplayCurreny":"36","DisplayCurrency":"USD","InvoiceValueInPayCurrency":"10.95","PayCurrency":"KWD"}}'; $body4 = '{"EventType":1,"Event":"TransactionsStatusChanged","DateTime":"14092021012540","CountryIsoCode":"KWT","Data":{"InvoiceId":36301378,"InvoiceReference":"2021520754","CreatedDate":"14092021012424","CustomerReference":"HB8R-3270991","CustomerName":"امل","CustomerMobile":"96599848810","CustomerEmail":"athoob88@hotmail.com","TransactionStatus":"SUCCESS","PaymentMethod":"KNET","UserDefinedField":"ar-61-sale-KWD","ReferenceId":"125720001110","TrackId":"14-09-2021_34159285","PaymentId":"109202125764066719","AuthorizationId":"079903","InvoiceValueInBaseCurrency":"39.25","BaseCurrency":"KWD","InvoiceValueInDisplayCurreny":"39.25","DisplayCurrency":"KWD","InvoiceValueInPayCurrency":"39.25","PayCurrency":"KWD"}}'; $data1 = json_decode($body1, true); $data2 = json_decode($body2, true); $data3 = json_decode($body3, true); $data4 = json_decode($body4, true); $this->assertTrue(MyFatoorah::isSignatureValid($data1['Data'], $secret1, $MyFatoorah_Signature1)); $this->assertTrue(MyFatoorah::isSignatureValid($data2['Data'], $secret2, $MyFatoorah_Signature2)); $this->assertTrue(MyFatoorah::isSignatureValid($data3['Data'], $secret3, $MyFatoorah_Signature3)); $this->assertTrue(MyFatoorah::isSignatureValid($data4['Data'], $secret4, $MyFatoorah_Signature4)); $this->assertFalse(MyFatoorah::isSignatureValid($data3['Data'], $secret4, $MyFatoorah_Signature4)); } //----------------------------------------------------------------------------------------------------------------------------------------- } library/src/API/Payment/MyFatoorahPaymentEmbedded.php000064400000006237152427537230016601 0ustar00initiatePayment($invoiceAmount,$currencyIso);$mfListObj=new MyFatoorahList($this->config);$allRates=$mfListObj->getCurrencyRates();$currencyRate=MyFatoorahList::getOneCurrencyRate($currencyIso,$allRates);self::$checkoutGateways=['all'=>[],'cards'=>[],'form'=>[],'ap'=>[],'gp'=>[]];foreach($gateways as $gateway){$gateway->PaymentTotalAmount=$this->getPaymentTotalAmount($gateway,$allRates,$currencyRate);$gateway->GatewayData=['GatewayTotalAmount'=>number_format($gateway->PaymentTotalAmount,2),'GatewayCurrency'=>$gateway->PaymentCurrencyIso,'GatewayTransCurrency'=>self::getTranslatedCurrency($gateway->PaymentCurrencyIso),];self::$checkoutGateways=$this->addGatewayToCheckout($gateway,self::$checkoutGateways,$isApRegistered);}self::$checkoutGateways['gp']=$this->getOneEmbeddedGateway(self::$checkoutGateways['gp'],$currencyIso,$allRates);if($isApRegistered){self::$checkoutGateways['ap']=$this->getOneEmbeddedGateway(self::$checkoutGateways['ap'],$currencyIso,$allRates);}return self::$checkoutGateways;}private function getPaymentTotalAmount($paymentMethod,$allRates,$currencyRate){$dbTrucVal=((int)($paymentMethod->TotalAmount*1000))/1000;if($paymentMethod->PaymentCurrencyIso==$paymentMethod->CurrencyIso){return $this->roundUp($dbTrucVal,2);}$dueVal=($currencyRate==1)?$dbTrucVal:round($paymentMethod->TotalAmount/$currencyRate,3);$baseTotalAmount=$this->roundUp($dueVal,2);$paymentCurrencyRate=MyFatoorahList::getOneCurrencyRate($paymentMethod->PaymentCurrencyIso,$allRates);if($paymentCurrencyRate!=1){$paymentTotalAmount=$baseTotalAmount*$paymentCurrencyRate;return $this->roundUp($paymentTotalAmount,2);}return $baseTotalAmount;}private function roundUp($number,$decimalPlaces){$multi=pow(10,$decimalPlaces);$nrAsStr=(string)($number*$multi);return ceil((float) $nrAsStr)/$multi;}private function getOneEmbeddedGateway($gateways,$displayCurrency,$allRates){if(count($gateways)==1){return $gateways[0];}$displayCurrencyIndex=array_search($displayCurrency,array_column($gateways,'PaymentCurrencyIso'));if($displayCurrencyIndex){return $gateways[$displayCurrencyIndex];}$defCurKey=array_search('1',array_column($allRates,'Value'));$defaultCurrency=$allRates[$defCurKey]->Text;$defaultCurrencyIndex=array_search($defaultCurrency,array_column($gateways,'PaymentCurrencyIso'));if($defaultCurrencyIndex){return $gateways[$defaultCurrencyIndex];}if(isset($gateways[0])){return $gateways[0];}return[];}public static function getTranslatedCurrency($currency){$currencies=['KWD'=>['en'=>'KD','ar'=>'د.ك'],'SAR'=>['en'=>'SR','ar'=>'ريال'],'BHD'=>['en'=>'BD','ar'=>'د.ب'],'EGP'=>['en'=>'LE','ar'=>'ج.م'],'QAR'=>['en'=>'QR','ar'=>'ر.ق'],'OMR'=>['en'=>'OR','ar'=>'ر.ع'],'JOD'=>['en'=>'JD','ar'=>'د.أ'],'AED'=>['en'=>'AED','ar'=>'د'],'USD'=>['en'=>'USD','ar'=>'دولار'],'EUR'=>['en'=>'EUR','ar'=>'يورو']];return $currencies[$currency]??['en'=>'','ar'=>''];}}library/src/API/Payment/MyFatoorahPayment.php000064400000011302152427537230015154 0ustar00$invoiceAmount,'CurrencyIso'=>$currencyIso,];$json=$this->callAPI("$this->apiURL/v2/InitiatePayment",$postFields,null,'Initiate Payment');$paymentMethods=($json->Data->PaymentMethods)??[];if(!empty($paymentMethods)&&$isCached){file_put_contents(self::$pmCachedFile,json_encode($paymentMethods));}return $paymentMethods;}public function getCachedVendorGateways(){if(file_exists(self::$pmCachedFile)){$cache=file_get_contents(self::$pmCachedFile);return($cache)?json_decode($cache):[];}else{return $this->initiatePayment(0,'',true);}}public function getCachedCheckoutGateways($isApRegistered=false){$gateways=$this->getCachedVendorGateways();$cachedGateways=['all'=>[],'cards'=>[],'form'=>[],'ap'=>[],'gp'=>[]];foreach($gateways as $gateway){$cachedGateways=$this->addGatewayToCheckout($gateway,$cachedGateways,$isApRegistered);}$cachedGateways['gp']=$cachedGateways['gp'][0]??[];if($isApRegistered){$cachedGateways['ap']=$cachedGateways['ap'][0]??[];}return $cachedGateways;}protected function addGatewayToCheckout($gateway,$checkoutGateways,$isApRegistered){$code=$gateway->PaymentMethodCode;if($gateway->IsEmbeddedSupported){$map=['stc'=>'cards','gp'=>'gp','ap'=>($isApRegistered)?'ap':'cards'];$index=$map[$code]?? 'form';}elseif($gateway->IsDirectPayment){return $checkoutGateways;}else{$index='cards';}$checkoutGateways[$index][]=$gateway;$checkoutGateways['all'][]=$gateway;return $checkoutGateways;}public function getOnePaymentMethod($gateway,$searchKey='PaymentMethodId',$invoiceAmount=0,$currencyIso=''){$paymentMethods=$this->initiatePayment($invoiceAmount,$currencyIso);$paymentMethod=null;foreach($paymentMethods as $pm){if($pm->$searchKey==$gateway){$paymentMethod=$pm;break;}}if(!isset($paymentMethod)){throw new Exception('Please contact Account Manager to enable the used payment method in your account');}return $paymentMethod;}public function getInvoiceURL($curlData,$gatewayId=0,$orderId=null,$sessionId=null,$ntfOption='Lnk'){$this->log('------------------------------------------------------------');$curlData['CustomerReference']=$curlData['CustomerReference']?? $orderId;if(!empty($sessionId)){$curlData['SessionId']=$sessionId;$data=$this->executePayment($curlData);return['invoiceURL'=>$data->PaymentURL,'invoiceId'=>$data->InvoiceId];}elseif($gatewayId=='myfatoorah'||empty($gatewayId)){if(empty($curlData['NotificationOption'])){$curlData['NotificationOption']=$ntfOption;}$data=$this->sendPayment($curlData);return['invoiceURL'=>$data->InvoiceURL,'invoiceId'=>$data->InvoiceId];}else{$curlData['PaymentMethodId']=$gatewayId;$data=$this->executePayment($curlData);return['invoiceURL'=>$data->PaymentURL,'invoiceId'=>$data->InvoiceId];}}public function sendPayment($curlData){$this->preparePayment($curlData);$json=$this->callAPI("$this->apiURL/v2/SendPayment",$curlData,$curlData['CustomerReference'],'Send Payment');return $json->Data;}public function executePayment($curlData){$this->preparePayment($curlData);$json=$this->callAPI("$this->apiURL/v2/ExecutePayment",$curlData,$curlData['CustomerReference'],'Execute Payment');return $json->Data;}private function preparePayment(&$curlData){$curlData['CustomerReference']=$curlData['CustomerReference']?? null;$curlData['SourceInfo']=$curlData['SourceInfo']?? 'MyFatoorah PHP Library '.$this->version;$this->prepareInvoiceInfo($curlData);$this->prepareCustomerInfo($curlData);}private function prepareCustomerInfo(&$curlData){if(!empty($curlData['CustomerName'])){$curlData['CustomerName']=preg_replace('/[^\p{L}\p{N}\s]/u','',$curlData['CustomerName']);}if(empty($curlData['CustomerEmail'])){$curlData['CustomerEmail']=null;}}private function prepareInvoiceInfo(&$curlData){if(!empty($curlData['InvoiceItems'])){foreach($curlData['InvoiceItems']as &$item){$item['ItemName']=strip_tags($item['ItemName']);}}unset($item);if(empty($curlData['ExpiryDate'])&&!empty($curlData['ExpiryMinutes'])){$curlData['ExpiryDate']=$this->getExpiryDate($curlData['ExpiryMinutes']);}}public function getEmbeddedSession($userDefinedField='',$logId=null){$curlData=['CustomerIdentifier'=>$userDefinedField];return $this->initiateSession($curlData,$logId);}public function initiateSession($curlData,$logId=null){$json=$this->callAPI("$this->apiURL/v2/InitiateSession",$curlData,$logId,'Initiate Session');return $json->Data;}public function registerApplePayDomain($url){$domainName=['DomainName'=>parse_url($url,PHP_URL_HOST)];return $this->callAPI("$this->apiURL/v2/RegisterApplePayDomain",$domainName,'','Register Apple Pay Domain');}}library/src/API/Payment/MyFatoorahPaymentStatus.php000064400000005423152427537230016367 0ustar00$keyId,'KeyType'=>$KeyType];$json=$this->callAPI("$this->apiURL/v2/GetPaymentStatus",$curlData,$orderId,'Get Payment Status');$data=$json->Data;$msgLog='Order #'.$data->CustomerReference.' ----- Get Payment Status';if(!self::checkOrderInformation($data,$orderId,$price,$currency)){$err='Trying to call data of another order';$this->log("$msgLog - Exception is $err");throw new Exception($err);}if($data->InvoiceStatus=='Paid'||$data->InvoiceStatus=='DuplicatePayment'){$data=self::getSuccessData($data);$this->log("$msgLog - Status is Paid");}elseif($data->InvoiceStatus!='Paid'){$data=$this->getErrorData($data,$keyId,$KeyType);$this->log("$msgLog - Status is ".$data->InvoiceStatus.'. Error is '.$data->InvoiceError);}return $data;}private static function checkOrderInformation($data,$orderId=null,$price=null,$currency=null){if($orderId&&$orderId!=$data->CustomerReference){return false;}list($valStr,$mfCurrency)=explode(' ',$data->InvoiceDisplayValue);$mfPrice=(double)(preg_replace('/[^\d.]/','',$valStr));if($price&&$price!=$mfPrice){return false;}return!($currency&&$currency!=$mfCurrency);}private static function getSuccessData($data){foreach($data->InvoiceTransactions as $transaction){if($transaction->TransactionStatus=='Succss'){$data->InvoiceStatus='Paid';$data->InvoiceError='';$data->focusTransaction=$transaction;return $data;}}return $data;}private function getErrorData($data,$keyId,$KeyType){$focusTransaction=self::{"getLastTransactionOf$KeyType"}($data->InvoiceTransactions,$keyId);if($focusTransaction&&$focusTransaction->TransactionStatus=='Failed'){$data->InvoiceStatus='Failed';$data->InvoiceError=$focusTransaction->Error.'.';$data->focusTransaction=$focusTransaction;return $data;}$timeZone=$this->getVendorTimeZone();$ExpiryDateTime=$data->ExpiryDate.' '.$data->ExpiryTime;$ExpiryDate=new \DateTime($ExpiryDateTime,new \DateTimeZone($timeZone));$currentDate=new \DateTime('now',new \DateTimeZone($timeZone));if($ExpiryDate<$currentDate){$data->InvoiceStatus='Expired';$data->InvoiceError='Invoice is expired since '.$data->ExpiryDate.'.';return $data;}$data->InvoiceStatus='Pending';$data->InvoiceError='Pending Payment.';return $data;}private static function getLastTransactionOfPaymentId($transactions,$paymentId){foreach($transactions as $transaction){if($transaction->PaymentId==$paymentId&&$transaction->Error){return $transaction;}}return null;}private static function getLastTransactionOfInvoiceId($transactions){$usortFun=function($a,$b){return strtotime($a->TransactionDate)-strtotime($b->TransactionDate);};usort($transactions,$usortFun);return end($transactions);}}library/src/API/MyFatoorahList.php000064400000001221152427537230013034 0ustar00Text==$currency){return (double) $value->Value;}}throw new Exception('The selected currency is not supported by MyFatoorah');}public function getCurrencyRate($currency){$allRates=$this->getCurrencyRates();return self::getOneCurrencyRate($currency,$allRates);}public function getCurrencyRates(){$url="$this->apiURL/v2/GetCurrenciesExchangeList";return (array) $this->callAPI($url,null,null,'Get Currencies Exchange List');}}library/src/API/MyFatoorahShipping.php000064400000001711152427537230013706 0ustar00apiURL/v2/GetCountries";$json=$this->callAPI($url,null,null,'Get Countries');return $json->Data;}public function getShippingCities($method,$countryCode,$searchValue=''){$url=$this->apiURL.'/v2/GetCities'.'?shippingMethod='.$method.'&countryCode='.$countryCode.'&searchValue='.urlencode(substr($searchValue,0,30));$json=$this->callAPI($url,null,null,"Get Cities: $countryCode");return array_map('ucwords',$json->Data->CityNames);}public function calculateShippingCharge($curlData){if(!empty($curlData['Items'])){foreach($curlData['Items']as &$item){$item['ProductName']=strip_tags($item['ProductName']);$item['Description']=strip_tags($item['Description']);}}$url="$this->apiURL/v2/CalculateShippingCharge";$json=$this->callAPI($url,$curlData,null,'Calculate Shipping Charge');return $json->Data;}}library/src/API/MyFatoorahRefund.php000064400000001142152427537230013346 0ustar00$keyId,'KeyType'=>$keyType,'RefundChargeOnCustomer'=>false,'ServiceChargeOnCustomer'=>false,'Amount'=>$amount,'CurrencyIso'=>$currency,'Comment'=>$comment,];return $this->makeRefund($postFields,$orderId);}public function makeRefund($curlData,$logId=null){$url="$this->apiURL/v2/MakeRefund";$json=$this->callAPI($url,$curlData,$logId,'Make Refund');return $json->Data;}}library/src/API/MyFatoorahSupplier.php000064400000000722152427537230013731 0ustar00apiURL.'/v2/GetSupplierDashboard?SupplierCode='.$supplierCode;return $this->callAPI($url,null,null,"Get Supplier Documents");}public function isSupplierApproved($supplierCode){$supplier=$this->getSupplierDashboard($supplierCode);return($supplier->IsApproved&&$supplier->IsActive);}}library/src/mf-config.json000064400000005753152427537230011563 0ustar00{ "KWT":{ "portal":"https://portal.myfatoorah.com", "v1":"https://apikw.myfatoorah.com", "v2":"https://api.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"الكويت", "countryNameEn":"Kuwait" }, "SAU":{ "portal":"https://sa.myfatoorah.com", "v1":"https://apisa.myfatoorah.com", "v2":"https://api-sa.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"السعودية", "countryNameEn":"Saudi Arabia" }, "ARE":{ "portal":"https://portal.myfatoorah.com", "v1":"https://apiae.myfatoorah.com", "v2":"https://api.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"الإمارات العربية المتحدة", "countryNameEn":"United Arab Emirates" }, "QAT":{ "portal":"https://qa.myfatoorah.com", "v1":"https://apiqa.myfatoorah.com", "v2":"https://api-qa.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"قطر", "countryNameEn":"Qatar" }, "BHR":{ "portal":"https://portal.myfatoorah.com", "v1":"https://apibh.myfatoorah.com", "v2":"https://api.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"البحرين", "countryNameEn":"Bahrain" }, "OMN":{ "portal":"https://portal.myfatoorah.com", "v1":"https://apiom.myfatoorah.com", "v2":"https://api.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"عمان", "countryNameEn":"Oman" }, "JOD":{ "portal":"https://portal.myfatoorah.com", "v1":"https://apijo.myfatoorah.com", "v2":"https://api.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"اﻷردن", "countryNameEn":"Jordan" }, "EGY":{ "portal":"https://portal.myfatoorah.com", "v1":"https://apieg.myfatoorah.com", "v2":"https://api.myfatoorah.com", "testPortal":"https://demo.myfatoorah.com", "testv1":"https://apidemo.myfatoorah.com", "testv2":"https://apitest.myfatoorah.com", "countryNameAr":"مصر", "countryNameEn":"Egypt" } } library/src/MyFatoorahHelper.php000064400000010154152427537230012734 0ustar0014){throw new Exception('Phone Number length must be between 3 to 14 digits');}if(strlen(substr($string4,3))>3){return[substr($string4,0,3),substr($string4,3)];}return['',$string4];}protected static function convertArabicDigitstoEnglish($inputString){$newNumbers=range(0,9);$persianDecimal=['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];$arabicDecimal=['٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];$arabic=['٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];$persian=['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];$string0=str_replace($persianDecimal,$newNumbers,$inputString);$string1=str_replace($arabicDecimal,$newNumbers,$string0);$string2=str_replace($arabic,$newNumbers,$string1);return str_replace($persian,$newNumbers,$string2);}public static function getWeightRate($unit){$lUnit=strtolower($unit);$rateUnits=['1'=>['kg','kgs','كج','كلغ','كيلو جرام','كيلو غرام'],'0.001'=>['g','جرام','غرام','جم'],'0.453592'=>['lbs','lb','رطل','باوند'],'0.0283495'=>['oz','اوقية','أوقية'],];foreach($rateUnits as $rate=>$unitArr){if(array_search($lUnit,$unitArr)!==false){return (double) $rate;}}throw new Exception('Weight units must be in kg, g, lbs, or oz. Default is kg');}public static function getDimensionRate($unit){$lUnit=strtolower($unit);$rateUnits=['1'=>['cm','سم'],'100'=>['m','متر','م'],'0.1'=>['mm','مم'],'2.54'=>['in','انش','إنش','بوصه','بوصة'],'91.44'=>['yd','يارده','ياردة'],];foreach($rateUnits as $rate=>$unitArr){if(array_search($lUnit,$unitArr)!==false){return (double) $rate;}}throw new Exception('Dimension units must be in cm, m, mm, in, or yd. Default is cm');}public static function isSignatureValid($dataModel,$secretKey,$signature,$eventType=1){if($eventType==2){unset($dataModel['GatewayReference']);}uksort($dataModel,'strcasecmp');return self::checkSignatureValidation($dataModel,$secretKey,$signature);}protected static function checkSignatureValidation($dataModel,$secretKey,$signature){$mapFun=function($v,$k){return sprintf("%s=%s",$k,$v);};$outputArr=array_map($mapFun,$dataModel,array_keys($dataModel));$output=implode(',',$outputArr);$hash=base64_encode(hash_hmac('sha256',$output,$secretKey,true));return hash_equals($hash,$signature);}public static function getMFCountries(){$cachedFile=dirname(__FILE__).'/mf-config.json';if(file_exists($cachedFile)){if((time()-filemtime($cachedFile)>3600)){$countries=self::getMFConfigFileContent($cachedFile);}if(!empty($countries)){return $countries;}$cache=file_get_contents($cachedFile);return($cache)?json_decode($cache,true):[];}else{return self::getMFConfigFileContent($cachedFile);}}protected static function getMFConfigFileContent($cachedFile){$curl=curl_init('https://portal.myfatoorah.com/Files/API/mf-config.json');$option=[CURLOPT_HTTPHEADER=>['Content-Type: application/json'],CURLOPT_RETURNTRANSFER=>true];curl_setopt_array($curl,$option);$response=curl_exec($curl);$http_code=curl_getinfo($curl,CURLINFO_HTTP_CODE);curl_close($curl);if($http_code==200&&is_string($response)){$responseText=trim($response,'');file_put_contents($cachedFile,$responseText);return json_decode($responseText,true);}elseif($http_code==403){touch($cachedFile);$fileContent=file_get_contents($cachedFile);if(!empty($fileContent)){return json_decode($fileContent,true);}}return[];}public static function filterInputField($name,$type='GET'){if(isset($GLOBALS["_$type"][$name])){return htmlspecialchars($GLOBALS["_$type"][$name]);}return null;}public static function getPaymentStatusLink($url,$paymentId){$pattern='/MpgsAuthentication.*|ApplePayComplete.*|GooglePayComplete.*/i';return preg_replace($pattern,"Result?paymentId=$paymentId",$url);}}library/src/MyFatoorah.php000064400000011161152427537230011573 0ustar00setApiKey($config);$this->setIsTest($config);$this->setVcCode($config);$this->config['loggerObj']=empty($config['loggerObj'])?null:$config['loggerObj'];$this->config['loggerFunc']=empty($config['loggerFunc'])?null:$config['loggerFunc'];self::$loggerObj=$this->config['loggerObj'];self::$loggerFunc=$this->config['loggerFunc'];$code=$this->config['vcCode'];$this->apiURL=$this->config['isTest']?$mfCountries[$code]['testv2']:$mfCountries[$code]['v2'];}public function getApiURL(){return $this->apiURL;}protected function setApiKey($config){if(empty($config['apiKey'])){throw new Exception('Config array must have the "apiKey" key.');}$config['apiKey']=trim($config['apiKey']);if(empty($config['apiKey'])){throw new Exception('The "apiKey" key is required and must be a string.');}$this->config['apiKey']=$config['apiKey'];}protected function setIsTest($config){if(!isset($config['isTest'])){throw new Exception('Config array must have the "isTest" key.');}if(!is_bool($config['isTest'])){throw new Exception('The "isTest" key must be boolean.');}$this->config['isTest']=$config['isTest'];}protected function setVcCode($config){$config['vcCode']=$config['vcCode']?? $config['countryCode']?? '';if(empty($config['vcCode'])){throw new Exception('Config array must have the "vcCode" key.');}$mfCountries=self::getMFCountries();$countriesCodes=array_keys($mfCountries);$config['vcCode']=strtoupper($config['vcCode']);if(!in_array($config['vcCode'],$countriesCodes)){throw new Exception('The "vcCode" key must be one of ('.implode(', ',$countriesCodes).').');}$this->config['vcCode']=$config['vcCode'];}public function callAPI($url,$postFields=null,$orderId=null,$function=null){ini_set('precision','14');ini_set('serialize_precision','-1');$request=isset($postFields)?'POST':'GET';$fields=empty($postFields)?json_encode($postFields,JSON_FORCE_OBJECT):json_encode($postFields,JSON_UNESCAPED_UNICODE);$msgLog="Order #$orderId ----- $function";$this->log("$msgLog - Request: $fields");$curl=curl_init($url);$options=[CURLOPT_CUSTOMREQUEST=>$request,CURLOPT_POSTFIELDS=>$fields,CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$this->config['apiKey'],'Content-Type: application/json'],CURLOPT_RETURNTRANSFER=>true];curl_setopt_array($curl,$options);$res=curl_exec($curl);$err=curl_error($curl);curl_close($curl);if($err){$this->log("$msgLog - cURL Error: $err");throw new Exception('cURL Error: '.$err);}$this->log("$msgLog - Response: $res");$json=json_decode((string) $res);$error=self::getAPIError($json,(string) $res);if($error){$this->log("$msgLog - Error: $error");throw new Exception($error);}return $json;}protected static function getAPIError($json,$res){$isSuccess=$json->IsSuccess ?? false;if($isSuccess){return '';}$hErr=self::getHtmlErrors($res);if($hErr){return $hErr;}if(is_string($json)){return $json;}if(empty($json)){return(!empty($res)?$res:'Kindly review your MyFatoorah admin configuration due to a wrong entry.');}return self::getJsonErrors($json);}protected static function getHtmlErrors($res){$stripHtml=strip_tags($res);if($res!=$stripHtml&&stripos($stripHtml,'apple-developer-merchantid-domain-association')!==false){return trim(preg_replace('/\s+/',' ',$stripHtml));}return '';}protected static function getJsonErrors($json){$errorsVar=isset($json->ValidationErrors)?'ValidationErrors':'FieldsErrors';if(isset($json->$errorsVar)){$blogDatas=array_column($json->$errorsVar,'Error','Name');$mapFun=function($k,$v){return"$k: $v";};$errArr=array_map($mapFun,array_keys($blogDatas),array_values($blogDatas));return implode(', ',$errArr);}if(isset($json->Data->ErrorMessage)){return $json->Data->ErrorMessage;}return empty($json->Message)?'':$json->Message;}public static function log($msg){$loggerObj=self::$loggerObj;$loggerFunc=self::$loggerFunc;if(empty($loggerObj)){return;}if(is_string($loggerObj)){error_log(PHP_EOL.date('d.m.Y h:i:s').' - '.$msg,3,$loggerObj);}elseif(method_exists($loggerObj,$loggerFunc)){$loggerObj->{$loggerFunc}($msg);}}protected function getVendorTimeZone(){$countries=self::getMFCountries();$vcCode=$this->config['vcCode'];$isTest=$this->config['isTest'];return($isTest)?$countries['KWT']['timeZone']:$countries[$vcCode]['timeZone'];}public function getExpiryDate($expiryMinutes){if(!ctype_digit((string) $expiryMinutes)||(int) $expiryMinutes<=0){return '';}$timeZone=$this->getVendorTimeZone();$nowDate=new \DateTime('now',new \DateTimeZone($timeZone));$nowDate->modify("+$expiryMinutes minutes");return $nowDate->format('Y-m-d\TH:i:s');}}library/CHANGELOG.md000064400000007035152427537230010040 0ustar00# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ------------------------------ ## [2.2.8] - 2024-09-06 ### Changed - Fix the display of the checkout price. ------------------------------ ## [2.2.7] - 2024-03-31 ### Changed - Fix the display of the checkout price. - Trim the config JSON file to remove any hidden chars. ------------------------------ ## [2.2.6] - 2024-02-11 ### Added - Add the getPaymentStatusLink static function - Add the getOneCurrencyRate static function - Add the getTranslatedCurrency static function to translate the currency ### Changed - Change the config array to accept the vcCode and countryCode ------------------------------ ## [2.2.5] - 2023-12-05 ### Changed - Some changes to the library to be compatible with other API rather than plugins ------------------------------ ## [2.2.4] - 2023-06-26 ### Changed - Add google pay gateway ------------------------------ ## [2.2.3] - 2023-05-24 ### Changed - Fix display price value in calc Gateway Data ------------------------------ ## [2.2.2] - 2023-05-02 ### Changed - Add makeRefund API function - Add more test files - Fix autoload file ------------------------------ ## [2.1.3] - 2023-05-24 ### Changed - Fix display price value in calc Gateway Data - Modify refund ------------------------------ ## [2.1.2] - 2023-05-02 ### Changed - Add notification options as param in send payment function - Modify refund - Fix apple pay striptags ------------------------------ ## [2.2.1] - 2023-03-30 ### Changed - Add notification options as param in send payment function - Modify refund - Fix apple pay striptags ------------------------------ ## [2.2.0] - 2023-01-04 ### Changed - Restructure the library files ------------------------------ ## [2.1.0] - 2023-01-04 ### Changed Fix many requests in the MyFatoorah autoloader ------------------------------ ## [2.1.0] - 2022-09-18 ### Added - Added Apple Pay Embedded Button ### Changed - Optimization in some functions - Fix compatibility with PHP 8.1 ------------------------------ ## [2.0.0] - 2022-07-04 The first version of the library ------------------------------ [2.2.8]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.8 [2.2.7]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.7 [2.2.6]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.6 [2.2.5]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.5 [2.2.4]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.4 [2.2.3]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.3 [2.2.2]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.2 [2.2.1]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.1 [2.2.0]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.2.0 [2.1.3]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.1.3 [2.1.2]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.1.2 [2.1.1]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.1.1 [2.1.0]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.1.0 [2.0.0]: https://dev.azure.com/myfatoorahsc/Public-Repo/_git/Library?version=GT2.0.0 library/autoload.php000064400000010645152427537230010551 0ustar00 * @copyright MyFatoorah, All rights reserved * @license GNU General Public License v3.0 */ $mfVersion = '2.2'; if (!in_array('curl', get_loaded_extensions())) { trigger_error('Kindly install and enable PHP cURL extension in your server.', E_USER_WARNING); return; } $mfLibFolder = __DIR__ . '/src/'; $mfLibFile = $mfLibFolder . 'MyFatoorah.php'; if (!is_writable($mfLibFile) || ((time() - filemtime($mfLibFile)) < 86400)) { return; } touch($mfLibFile); try { $mfCurl = curl_init("https://portal.myfatoorah.com/Files/API/php/library/$mfVersion/MyfatoorahLibrary.txt"); curl_setopt_array( $mfCurl, array( CURLOPT_RETURNTRANSFER => true, ) ); $mfResponse = curl_exec($mfCurl); $mfHttpCode = curl_getinfo($mfCurl, CURLINFO_HTTP_CODE); $mfCurlErr = curl_error($mfCurl); curl_close($mfCurl); if ($mfCurlErr) { trigger_error('cURL Error: ' . $mfCurlErr, E_USER_WARNING); } if ($mfHttpCode == 200 && is_string($mfResponse)) { mfPutFileContent($mfLibFolder, $mfResponse); } } catch (\Exception $ex) { trigger_error('Exception: ' . $ex->getMessage(), E_USER_WARNING); } function mfPutFileContent($mfLibFolder, $mfResponse) { $mfSplitFile = explode('class', $mfResponse); $mfNamespace = ' '', countryCode => 'KWT', isTest => false, ]; $mfObj = new MyFatoorahPayment($config); $postFields = [ 'NotificationOption' => 'Lnk', 'InvoiceValue' => '50', 'CustomerName' => 'fname lname', ]; $data = $mfObj->getInvoiceURL($postFields); $invoiceId = $data->InvoiceId; $paymentLink = $data->InvoiceURL; echo "Click on $paymentLink to pay with invoiceID $invoiceId."; ``` ### Shipping Operations ``` php $config = [ apiKey => '', countryCode => 'KWT', isTest => false, ]; $mfObj = new MyFatoorahShipping($config); $data = $mfObj->getShippingCountries(); echo 'Country code: ' . $data[0]->CountryCode; echo 'Country name: ' . $data[0]->CountryName; ``` ### General Operations ``` php $phone = MyFatoorah::getPhone('+2 01234567890'); echo 'Phone code: ' . $phone[0]; echo 'Phone number: ' . $phone[1]; ``` ## Testing ``` bash phpunit ``` ## Credits - [MyFatoorah Plugin Team](https://github.com/my-fatoorah) - [Nermeen Shoman](https://github.com/nermeenshoman) - [Rasha Saeed](https://github.com/rasha-saeed) ## License The GPL-3.0-only License. library/composer.json000064400000003346152427537230010752 0ustar00{ "name": "myfatoorah/library", "description": "MyFatoorah PHP Library", "version": "2.2.8", "type": "library", "license": [ "GPL-3.0-only" ], "require": { "php": ">=7", "ext-curl": "*", "ext-json": "*" }, "require-dev": { "phpunit/phpunit": "^9.5", "phpcompatibility/php-compatibility": "*", "squizlabs/php_codesniffer": "*", "phpstan/phpstan": "^1.10", "phan/phan": "^5.4" }, "prefer-stable": true, "scripts": { "post-install-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility", "post-update-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility" }, "autoload": { "files": ["autoload.php"], "psr-4": { "MyFatoorah\\Library\\": "src/" } }, "autoload-dev": { "psr-4": { "MyFatoorah\\Test\\": "tests" } }, "keywords": [ "MyFatoorah", "My Fatoorah", "Fatoorah", "gateway", "payment", "Shipping", "api", "commerce", "Library" ], "homepage": "https://myfatoorah.com/", "authors": [ { "name": "MyFatoorah Plugin Team", "email": "plugins@myfatoorah.com" }, { "name": "Nermeen Shoman", "email": "nshoman@myfatoorah.com", "role": "Senior Software Engineer" }, { "name": "Rasha Saeed", "email": "rsaeed@myfatoorah.com", "role": "Senior Software Engineer" } ] } library/phpunit.xml000064400000001122152427537230010427 0ustar00 tests laravel-package/resources/views/includes/sectionForm.blade.php000064400000005507152427537230020630 0ustar00 laravel-package/resources/views/includes/sectionApplePay.blade.php000064400000001156152427537230021434 0ustar00 laravel-package/resources/views/includes/sectionCards.blade.php000064400000001430152427537230020750 0ustar00@foreach($paymentMethods['cards'] as $mfCard) @php($mfCardTitle = App::isLocale('ar') ? $mfCard->PaymentMethodAr : $mfCard->PaymentMethodEn)
{{$mfCardTitle}}
{{ $mfCard->GatewayData['GatewayTotalAmount'] }} {{ $mfCard->GatewayData['GatewayCurrency'] }}
@endforeach laravel-package/resources/views/includes/sectionGooglePay.blade.php000064400000001300152427537230021576 0ustar00 laravel-package/resources/views/checkout.blade.php000064400000007432152427537230016336 0ustar00 {{__('myfatoorah.pageCheckout')}}
{{__('myfatoorah.noPaymentGateways')}}
{{__('myfatoorah.howWouldYouLikeToPay')}}
@if(!empty($paymentMethods['ap']))
@endif @if(!empty($paymentMethods['gp']))
@endif
@if(!empty($paymentMethods['cards'] ))
{{!empty($paymentMethods['ap'] ) || !empty($paymentMethods['gp'] ) ? __('myfatoorah.or') : ''}} {{__('myfatoorah.payWith')}}
@include('myfatoorah.includes.sectionCards')
@endif @if(!empty($paymentMethods['form']))
{{!empty($paymentMethods['cards'] ) || !empty($paymentMethods['ap'] ) || !empty($paymentMethods['gp'] ) ? __('myfatoorah.or') :''}} {{__('myfatoorah.insertCardDetails')}}
@endif @if(!empty($paymentMethods['gp'])) @include('myfatoorah.includes.sectionGooglePay') @endif @if(!empty($paymentMethods['ap'])) @include('myfatoorah.includes.sectionApplePay') @endif @if(!empty($paymentMethods['form'])) @include('myfatoorah.includes.sectionForm') @endif
laravel-package/resources/views/error.blade.php000064400000000721152427537230015654 0ustar00 {{__('myfatoorah.pageError')}}
{{$exMessage}}
laravel-package/lang/ar/myfatoorah.php000064400000003151152427537230014002 0ustar00 'ماي فاتورة - الدفع', 'pageError' => 'خطأ ماي فاتورة', 'noPaymentGateways' => 'عذرا: لا توجد أي بوابات دفع في حسابك. تواصل مع مدير الحساب الخاص بك', 'howWouldYouLikeToPay' => 'كيف تريد أن تدفع؟', 'or' => 'أو', 'payWith' => 'ادفع بواسطة', 'insertCardDetails' => 'ادخل بيانات البطاقة', 'payNow' => 'ادفع الآن', 'holderName' => 'اسم حامل البطاقة', 'cardNumber' => 'رقم البطاقة', 'expiryDate' => 'شهر/سنة', 'securityCode' => 'الرمز السري', 'cardHolderNameLabel' => 'اسم حامل البطاقة', 'cardNumberLabel' => 'رقم البطاقة', 'expiryDateLabel' => 'تاريخ الإنتهاء', 'securityCodeLabel' => 'الرمز السري', 'saveCard' => 'حفظ بيانات البطاقة للاستخدام المستقبلي', 'addCard' => 'إضافة رقم بطاقة', 'deleteAlert.title' => 'حذف البطاقة', 'deleteAlert.message' => 'هل أنت متأكد من حذف البطاقة؟', 'deleteAlert.confirm' => 'موافق', 'deleteAlert.cancel' => 'غير موافق', 'Kindly review your MyFatoorah admin configuration due to a wrong entry.' => 'نرجو مراجعة إعدادت ماي فاتورة نتيجة لوجود خطأ بها.', ]; laravel-package/lang/en/myfatoorah.php000064400000002462152427537230014006 0ustar00 'MyFatoorah - Checkout', 'pageError' => 'MyFatoorah Error', 'noPaymentGateways' => 'There are no payment methods available on your account, please contact your account manager.', 'howWouldYouLikeToPay' => 'How would you like to pay?', 'or' => 'Or', 'payWith' => 'Pay With', 'insertCardDetails' => 'Insert Card Details', 'payNow' => 'Pay Now', 'holderName' => 'Name On Card', 'cardNumber' => 'Number', 'expiryDate' => 'MM/YY', 'securityCode' => 'CVV', 'cardHolderNameLabel' => 'Card Holder Name', 'cardNumberLabel' => 'Card Number', 'expiryDateLabel' => 'Expiry Date', 'securityCodeLabel' => 'Security Code', 'saveCard' => 'Save card number for future payments', 'addCard' => 'Use another card', 'deleteAlert.title' => 'Delete Card', 'deleteAlert.message' => 'Are you sure you want to remove this card?', 'deleteAlert.confirm' => 'Yes', 'deleteAlert.cancel' => 'No', 'Kindly review your MyFatoorah admin configuration due to a wrong entry.' => 'Kindly review your MyFatoorah admin configuration due to a wrong entry.', ]; laravel-package/src/controllers/MyFatoorahController.php000064400000023464152427537230017571 0ustar00mfConfig = [ 'apiKey' => config('myfatoorah.api_key'), 'isTest' => config('myfatoorah.test_mode'), 'countryCode' => config('myfatoorah.country_iso'), ]; } //----------------------------------------------------------------------------------------------------------------------------------------- /** * Redirect to MyFatoorah Invoice URL * Provide the index method with the order id and (payment method id or session id) * * @return Response */ public function index() { try { //For example: pmid=0 for MyFatoorah invoice or pmid=1 for Knet in test mode $paymentId = request('pmid') ?: 0; $sessionId = request('sid') ?: null; $orderId = request('oid') ?: 147; $curlData = $this->getPayLoadData($orderId); $mfObj = new MyFatoorahPayment($this->mfConfig); $payment = $mfObj->getInvoiceURL($curlData, $paymentId, $orderId, $sessionId); return redirect($payment['invoiceURL']); } catch (Exception $ex) { $exMessage = __('myfatoorah.' . $ex->getMessage()); return response()->json(['IsSuccess' => 'false', 'Message' => $exMessage]); } } //----------------------------------------------------------------------------------------------------------------------------------------- /** * Example on how to map order data to MyFatoorah * You can get the data using the order object in your system * * @param int|string $orderId * * @return array */ private function getPayLoadData($orderId = null) { $callbackURL = route('myfatoorah.callback'); //You can get the data using the order object in your system $order = $this->getTestOrderData($orderId); return [ 'CustomerName' => 'FName LName', 'InvoiceValue' => $order['total'], 'DisplayCurrencyIso' => $order['currency'], 'CustomerEmail' => 'test@test.com', 'CallBackUrl' => $callbackURL, 'ErrorUrl' => $callbackURL, 'MobileCountryCode' => '+965', 'CustomerMobile' => '12345678', 'Language' => 'en', 'CustomerReference' => $orderId, 'SourceInfo' => 'Laravel ' . app()::VERSION . ' - MyFatoorah Package ' . MYFATOORAH_LARAVEL_PACKAGE_VERSION ]; } //----------------------------------------------------------------------------------------------------------------------------------------- /** * Get MyFatoorah Payment Information * Provide the callback method with the paymentId * * @return Response */ public function callback() { try { $paymentId = request('paymentId'); $mfObj = new MyFatoorahPaymentStatus($this->mfConfig); $data = $mfObj->getPaymentStatus($paymentId, 'PaymentId'); $message = $this->getTestMessage($data->InvoiceStatus, $data->InvoiceError); $response = ['IsSuccess' => true, 'Message' => $message, 'Data' => $data]; } catch (Exception $ex) { $exMessage = __('myfatoorah.' . $ex->getMessage()); $response = ['IsSuccess' => 'false', 'Message' => $exMessage]; } return response()->json($response); } //----------------------------------------------------------------------------------------------------------------------------------------- /** * Example on how to Display the enabled gateways at your MyFatoorah account to be displayed on the checkout page * Provide the checkout method with the order id to display its total amount and currency * * @return View */ public function checkout() { try { //You can get the data using the order object in your system $orderId = request('oid') ?: 147; $order = $this->getTestOrderData($orderId); //You can replace this variable with customer Id in your system $customerId = request('customerId'); //You can use the user defined field if you want to save card $userDefinedField = config('myfatoorah.save_card') && $customerId ? "CK-$customerId" : ''; //Get the enabled gateways at your MyFatoorah acount to be displayed on checkout page $mfObj = new MyFatoorahPaymentEmbedded($this->mfConfig); $paymentMethods = $mfObj->getCheckoutGateways($order['total'], $order['currency'], config('myfatoorah.register_apple_pay')); if (empty($paymentMethods['all'])) { throw new Exception('noPaymentGateways'); } //Generate MyFatoorah session for embedded payment $mfSession = $mfObj->getEmbeddedSession($userDefinedField); //Get Environment url $isTest = $this->mfConfig['isTest']; $vcCode = $this->mfConfig['countryCode']; $countries = MyFatoorah::getMFCountries(); $jsDomain = ($isTest) ? $countries[$vcCode]['testPortal'] : $countries[$vcCode]['portal']; return view('myfatoorah.checkout', compact('mfSession', 'paymentMethods', 'jsDomain', 'userDefinedField')); } catch (Exception $ex) { $exMessage = __('myfatoorah.' . $ex->getMessage()); return view('myfatoorah.error', compact('exMessage')); } } //----------------------------------------------------------------------------------------------------------------------------------------- /** * Example on how the webhook is working when MyFatoorah try to notify your system about any transaction status update */ public function webhook(Request $request) { try { //Validate webhook_secret_key $secretKey = config('myfatoorah.webhook_secret_key'); if (empty($secretKey)) { return response(null, 404); } //Validate MyFatoorah-Signature $mfSignature = $request->header('MyFatoorah-Signature'); if (empty($mfSignature)) { return response(null, 404); } //Validate input $body = $request->getContent(); $input = json_decode($body, true); if (empty($input['Data']) || empty($input['EventType']) || $input['EventType'] != 1) { return response(null, 404); } //Validate Signature if (!MyFatoorah::isSignatureValid($input['Data'], $secretKey, $mfSignature, $input['EventType'])) { return response(null, 404); } //Update Transaction status on your system $result = $this->changeTransactionStatus($input['Data']); return response()->json($result); } catch (Exception $ex) { $exMessage = __('myfatoorah.' . $ex->getMessage()); return response()->json(['IsSuccess' => false, 'Message' => $exMessage]); } } //----------------------------------------------------------------------------------------------------------------------------------------- private function changeTransactionStatus($inputData) { //1. Check if orderId is valid on your system. $orderId = $inputData['CustomerReference']; //2. Get MyFatoorah invoice id $invoiceId = $inputData['InvoiceId']; //3. Check order status at MyFatoorah side if ($inputData['TransactionStatus'] == 'SUCCESS') { $status = 'Paid'; $error = ''; } else { $mfObj = new MyFatoorahPaymentStatus($this->mfConfig); $data = $mfObj->getPaymentStatus($invoiceId, 'InvoiceId'); $status = $data->InvoiceStatus; $error = $data->InvoiceError; } $message = $this->getTestMessage($status, $error); //4. Update order transaction status on your system return ['IsSuccess' => true, 'Message' => $message, 'Data' => $inputData]; } //----------------------------------------------------------------------------------------------------------------------------------------- private function getTestOrderData($orderId) { return [ 'total' => 15, 'currency' => 'KWD' ]; } //----------------------------------------------------------------------------------------------------------------------------------------- private function getTestMessage($status, $error) { if ($status == 'Paid') { return 'Invoice is paid.'; } else if ($status == 'Failed') { return 'Invoice is not paid due to ' . $error; } else if ($status == 'Expired') { return $error; } } //----------------------------------------------------------------------------------------------------------------------------------------- } laravel-package/src/MyFatoorahServiceProvider.php000064400000003523152427537230016205 0ustar00publishes([ __DIR__ . '/../config/myfatoorah.php' => config_path('myfatoorah.php'), __DIR__ . '/../resources/views' => resource_path('views/myfatoorah'), __DIR__ . '/../public' => public_path('vendor/myfatoorah'), __DIR__ . '/../lang' => lang_path(), __DIR__ . '/controllers/MyFatoorahController.php' => app_path() . '/Http/Controllers/MyFatoorahController.php', ], 'myfatoorah'); Route::get('myfatoorah', [ 'as' => 'myfatoorah', 'uses' => MyFatoorahController::class . '@index' ]); Route::get('myfatoorah/callback', [ 'as' => 'myfatoorah.callback', 'uses' => MyFatoorahController::class . '@callback' ]); Route::get('myfatoorah/checkout', [ 'as' => 'myfatoorah.cardView', 'uses' => MyFatoorahController::class . '@checkout' ]); Route::post('myfatoorah/webhook', [ 'as' => 'myfatoorah.webhook', 'uses' => MyFatoorahController::class . '@webhook' ]); defined('MYFATOORAH_LARAVEL_PACKAGE_VERSION') or define('MYFATOORAH_LARAVEL_PACKAGE_VERSION', '2.2.4'); } /** * Bootstrap services. * * @return void */ public function boot() { $this->mergeConfigFrom( __DIR__ . '/../config/myfatoorah.php', 'myfatoorah' ); } } laravel-package/public/css/style.css000064400000011075152427537230013521 0ustar00/* COMMON STYLES ========================================================================== */ .mf-grey-text { color: #888484 !important; font-size: 12px; } .mf-danger-text{ color: red; font-size: 14px; font-weight: 600; } #mf-noPaymentGateways{ display: none; } #mf-sectionButtons{ margin-top: 14px; } #mf-sectionGP{ height: 40px; } .mf-row-container { display: flex; flex-direction: row; align-items: center; margin-inline-end: .5rem; text-align: start; } #gp-card-element{ height: 35px !important; } /* CONTAINERS ========================================================================== */ .mf-payment-methods-container { /*max-width: 40rem;*/ width: fit-content; background-color: #fff; border: 0.063rem solid #e2e5e8; border-radius: 0.5rem; box-shadow: 0.063rem 0.063rem 0.625rem 0 rgba(144, 144, 144, 0.5); padding: 15px 10px; margin: 0.5rem auto; display: flex; flex-direction: column; } /* PAYMENT METHODS SECTION ========================================================================== */ .mf-card-container { /*font-size: initial;*/ border: 0.063rem solid #e3e3e8; border-radius: 0.5rem; box-shadow: 0 0.063rem 0.188rem 0 rgba(0, 0, 0, 0.1), 0 0.063rem 0.125rem 0 rgba(0, 0, 0, 0.06); display: flex; align-items: center; justify-content: space-between; margin: 0.25rem 0.5rem; padding: 0rem 0.5rem; cursor: pointer; background-color: #fff !important; height: 48px !important; } .mf-card-container:hover { box-shadow: rgba(45, 35, 66, 0.4) 0 0.063rem 0.125rem, rgba(45, 35, 66, 0.3) 0 0.188rem 0.25rem 0.063rem, #D6D6E7 0 0.063rem 0 inset !important; transform: translateY(-0.125rem); background-color: white; border: 0.063rem solid #e3e3e8; border-radius: 0.5rem; box-shadow: 0 0.063rem 0.188rem 0 rgba(0, 0, 0, 0.1), 0 0.063rem 0.125rem 0 rgba(0, 0, 0, 0.06); width: unset; } .mf-card-container:focus{ background-color: #fff; } .mf-payment-logo { /*margin: 0.5rem !important;*/ margin-inline-end: 1rem !important; width: 40px !important; } .mf-payment-text { color: #40a7cf !important; font-size: 12px !important; font-family: 'Roboto', sans-serif; font-weight: 600 !important; text-transform: initial; margin: 1rem 0.5rem !important; } /* DIVIDER ========================================================================== */ .mf-divider, .mf-form-divider{ text-align: center; border-bottom: 0.063rem solid; line-height: 0.1rem; margin: 16px 0 !important; color: #b6b5b5; } .mf-divider-span { color: #b6b5b5; background: #fff; padding:0 0.625rem; font-size: 12px; font-family: 'Roboto', sans-serif; font-weight: 500; float: none !important; display: inline !important; } /* Pay Now BTN ========================================================================== */ .mf-btn { width: auto; border: none; border-radius: 8px; display: flex; align-items: center; margin: 0.3rem 0rem; color: var(--white); padding: 0.3rem 2rem; } .mf-pay-now-btn { /*height: 32.2px;*/ background-color: var(--brand-color); justify-content: center; color: white !important; cursor: pointer; text-decoration: none; } .mf-pay-now-btn:hover { /*text-decoration: none;*/ } .mf-pay-now-span { margin: 0px !important; padding: 0px !important; font-weight: 500 !important; /*font-family: 'Roboto', sans-serif;*/ vertical-align: baseline; /*font-size: 14px !important;*/ color: white !important; text-transform: initial; line-height: 1.618; } /* MEDIA QUERIES ========================================================================== */ /*phone (480px - 400 - 320px)*/ @media (max-width: 440px) { .mf-card-container { margin: 0.25rem 0rem; height: 40px !important; } .mf-payment-methods-container { padding: 15px 7px; margin: 0.2rem auto; } .mf-payment-logo { margin-inline-end: 0.5rem !important; margin-inline-start: 0rem !important; margin-top: 0 !important; width: 30px !important; } .mf-payment-text { font-weight: 500 !important; /*font-size: 10px !important;*/ line-height: 15px; } } /* ========================================================================== */ laravel-package/public/js/checkout.js000064400000002252152427537230013633 0ustar00document.addEventListener('DOMContentLoaded', function () { if (window.ApplePaySession) { return; } //remove ap if registered document.getElementById('mf-ap-element')?.remove(); var mfGpElement = document.getElementById('mf-gp-element'); if (!mfGpElement) { document.getElementById('mf-or-cardsDivider')?.remove(); } //remove ap as a card let mfDivAps = document.querySelectorAll('.mf-div-ap'); mfDivAps.forEach(element => { element.remove(); }); //are there any cards left? var mfCardContainer = document.querySelectorAll('.mf-card-container'); if (mfCardContainer.length === 0) { document.getElementById('mf-sectionCard')?.remove(); if (!mfGpElement) { document.getElementById('mf-or-formDivider')?.remove(); } if (!document.getElementById('mf-ap-element') && !document.getElementById('mf-gp-element') && !document.getElementById('mf-form-element')) { document.getElementById('mf-paymentGateways')?.remove(); document.getElementById('mf-noPaymentGateways').style.display = 'block'; } } }); laravel-package/config/myfatoorah.php000064400000002657152427537230013736 0ustar00 '', /** * Test Mode (boolean) * Accepted value: true for the test mode or false for the live mode */ 'test_mode' => true, /** * Country ISO Code (string) * Accepted value: KWT, SAU, ARE, QAT, BHR, OMN, JOD, or EGY. */ 'country_iso' => 'KWT', /** * Save card (boolean) * Accepted value: true if you want to enable save card options. * You should contact your account manager to enable this feature in your MyFatoorah account as well. */ 'save_card' => true, /** * Webhook secret key (string) * Enable webhook on your MyFatoorah account setting then paste the secret key here. * The webhook link is: https://{example.com}/myfatoorah/webhook */ 'webhook_secret_key' => '', /** * Register Apple Pay (boolean) * Set it to true to show the Apple Pay on the checkout page. * First, verify your domain with Apple Pay before you set it to true. * You can either follow the steps here: https://docs.myfatoorah.com/docs/apple-pay#verify-your-domain-with-apple-pay or contact the MyFatoorah support team (tech@myfatoorah.com). */ 'register_apple_pay' => false ]; laravel-package/README.md000064400000004175152427537230011063 0ustar00# MyFatoorah Laravel ## Description This is the official MyFatoorah Payment Gateway Laravel package. MyFatoorah Laravel is based on [myfatoorah/library](https://packagist.org/packages/myfatoorah/library) composer package. Both MyFatoorah Laravel and PHP library composer packages are developed by [MyFatoorah Technical Team](mailto:tech@myfatoorah.com) to handle myfatoorah API endpoints. ## Main Features * Create MyFatoorah invoices. * Check the MyFatoorah payment status for invoice/payment. * Display the enabled gateways at your MyFatoorah account to be displayed on the checkout page. ## Installation 1. Install the package via [myfatoorah/laravel-package](https://packagist.org/packages/myfatoorah/laravel-package) composer. ```bash composer require myfatoorah/laravel-package ``` 2. Publish the **MyFatoorah** provider using the following CLI command. ```bash php artisan vendor:publish --provider="MyFatoorah\LaravelPackage\MyFatoorahServiceProvider" --tag="myfatoorah" ``` 3. To test the payment cycle, type the below URL onto your browser. Replace only the `{example.com}` with your site domain. ``` https://{example.com}/myfatoorah ``` 4. Customize the **app/Http/Controllers/MyFatoorahController.php** file as per your site needs. 5. Optional: call the the below URL onto your browser. Replace only the `{example.com}` with your site domain to see how to draw the available gateways on checkoutpages ``` https://{example.com}/myfatoorah/checkout?oid=22 ```
## Merchant Configurations Edit the **config/myfatoorah.php** file with your correct vendor data. **Demo configuration** 1. You can use the test API token key mentioned [here](https://myfatoorah.readme.io/docs/test-token). 2. Make sure the test mode is true. 3. You can use one of [the test cards](https://myfatoorah.readme.io/docs/test-cards). **Live Configuration** 1. You can use the live API token key mentioned [here](https://myfatoorah.readme.io/docs/live-token). 2. Make sure the test mode is false. 3. Make sure to set the country ISO code as mentioned in [this link](https://myfatoorah.readme.io/docs/iso-lookups). laravel-package/composer.json000064400000002401152427537230012314 0ustar00{ "name": "myfatoorah/laravel-package", "description": "The official MyFatoorah Payment Gateway for Laravel.", "version": "2.2.4", "type": "library", "license": [ "GPL-3.0-only" ], "require": { "myfatoorah/library": "~2.2.4" }, "autoload": { "psr-4": { "MyFatoorah\\LaravelPackage\\": "src" } }, "extra": { "laravel": { "providers": [ "MyFatoorah\\LaravelPackage\\MyFatoorahServiceProvider" ] } }, "keywords": [ "MyFatoorah", "My Fatoorah", "Fatoorah", "gateway", "payment", "Shipping", "api", "commerce", "Laravel" ], "homepage": "https://myfatoorah.com/", "authors": [ { "name": "MyFatoorah Plugin Team", "email": "plugins@myfatoorah.com" }, { "name": "Nermeen Shoman", "email": "nshoman@myfatoorah.com", "role": "Senior Software Engineer" }, { "name": "Rasha Saeed", "email": "rsaeed@myfatoorah.com", "role": "Senior Software Engineer" } ] }