🍲dfcv🏰dd⋉(● ∸ ●)⋊@% PNG %k25u25%fgd5n! PNG %k25u25%fgd5n!library/tests/API/Payment/MyFatoorahPaymentStatusTest.php 0000644 00000002561 15242753723 0017602 0 ustar 00 keys = 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.php 0000644 00000002455 15242753723 0020012 0 ustar 00 keys = 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.php 0000644 00000003514 15242753723 0016375 0 ustar 00 keys = 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.php 0000644 00000004452 15242753723 0014570 0 ustar 00 keys = 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.php 0000644 00000007630 15242753723 0015127 0 ustar 00 keys = 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.php 0000644 00000005221 15242753723 0015143 0 ustar 00 keys = 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.php 0000644 00000002556 15242753723 0014263 0 ustar 00 keys = 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.php 0000644 00000007434 15242753723 0011512 0 ustar 00 [
'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.php 0000644 00000020122 15242753723 0014143 0 ustar 00 assertEquals('', $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.php 0000644 00000006237 15242753723 0016601 0 ustar 00 initiatePayment($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.php 0000644 00000011302 15242753723 0015154 0 ustar 00 $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.php 0000644 00000005423 15242753723 0016367 0 ustar 00 $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.php 0000644 00000001221 15242753723 0013034 0 ustar 00 Text==$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.php 0000644 00000001711 15242753723 0013706 0 ustar 00 apiURL/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.php 0000644 00000001142 15242753723 0013346 0 ustar 00 $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.php 0000644 00000000722 15242753723 0013731 0 ustar 00 apiURL.'/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.json 0000644 00000005753 15242753723 0011563 0 ustar 00 {
"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.php 0000644 00000010154 15242753723 0012734 0 ustar 00 14){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.php 0000644 00000011161 15242753723 0011573 0 ustar 00 setApiKey($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.md 0000644 00000007035 15242753723 0010040 0 ustar 00 # 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.php 0000644 00000010645 15242753723 0010551 0 ustar 00
* @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.json 0000644 00000003346 15242753723 0010752 0 ustar 00 {
"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.xml 0000644 00000001122 15242753723 0010427 0 ustar 00
tests
laravel-package/resources/views/includes/sectionForm.blade.php 0000644 00000005507 15242753723 0020630 0 ustar 00
laravel-package/resources/views/includes/sectionApplePay.blade.php 0000644 00000001156 15242753723 0021434 0 ustar 00