├── .github └── workflows │ └── tests.yml ├── .phpunit.result.cache ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── art └── socialcard.png ├── composer.json ├── config └── hyperpay.php ├── database └── migrations │ ├── 2021_05_16_000001_create_transactions_table.php │ └── create_transactions_table.php.stub ├── resources └── lang │ ├── ar.json │ └── en.json ├── routes └── web.php └── src ├── Console ├── BillingCommand.php └── stubs │ ├── billing.stub │ └── hyperpay-billing-example.stub ├── Contracts ├── BillingInterface.php └── Hyperpay.php ├── Events ├── FailTransaction.php └── SuccessTransaction.php ├── Facades └── LaravelHyperpay.php ├── Http └── Controllers │ └── WebhookController.php ├── LaravelHyperpay.php ├── LaravelHyperpayServiceProvider.php ├── Models └── Transaction.php ├── Support ├── HttpClient.php ├── HttpParameters.php ├── HttpResponse.php └── TransactionBuilder.php └── Traits ├── HasUniqID.php └── ManageUserTransactions.php /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "0 0 * * *" 8 | 9 | jobs: 10 | tests: 11 | runs-on: ubuntu-20.04 12 | 13 | strategy: 14 | fail-fast: true 15 | matrix: 16 | php: [7.3, 7.4] 17 | laravel: [^7.0] 18 | 19 | name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} 20 | 21 | steps: 22 | - name: Checkout code 23 | uses: actions/checkout@v2 24 | 25 | - name: Setup PHP 26 | uses: shivammathur/setup-php@v2 27 | with: 28 | php-version: ${{ matrix.php }} 29 | extensions: dom, curl, libxml, mbstring, zip 30 | tools: composer:v1 31 | coverage: none 32 | 33 | - name: Install dependencies 34 | run: | 35 | composer update --prefer-dist --no-interaction --no-progress 36 | 37 | - name: Execute tests 38 | run: vendor/bin/phpunit --verbose 39 | env: 40 | STRIPE_SECRET: ${{ secrets.STRIPE_SECRET }} 41 | -------------------------------------------------------------------------------- /.phpunit.result.cache: -------------------------------------------------------------------------------- 1 | {"version":1,"defects":{"Devinweb\\LaravelHyperpay\\Tests\\UserTest::true_is_true":3,"Devinweb\\LaravelHyperpay\\Tests\\UserTest::test_user_can_get_pending_transactions":4,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::test_user_can_prepare_checkout":4,"Warning":6,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::user_can_prepare_checkout":3,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::user_can_prepare_checkout_for_mada_brand":4,"Devinweb\\LaravelHyperpay\\Tests\\PaymentStatusTest::payment_status_with_fail_response":4,"Devinweb\\LaravelHyperpay\\Tests\\PaymentStatusTest::payment_status_for_fail_transaction":4,"Devinweb\\LaravelHyperpay\\Tests\\PaymentStatusTest::payment_status_for_success_transaction":4,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::user_can_prepare_checkout_for_default_brands_visa_master":4},"times":{"Devinweb\\LaravelHyperpay\\Tests\\ExampleTest::true_is_true":0.089,"Devinweb\\LaravelHyperpay\\Tests\\UserTest::true_is_true":0.007,"Devinweb\\LaravelHyperpay\\Tests\\UserTest::test_user_can_get_pending_transactions":0.018,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::test_user_can_prepare_checkout":0.096,"Warning":0,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::user_can_prepare_checkout":0.277,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::user_can_prepare_checkout_for_default_brands_visa_master":0.027,"Devinweb\\LaravelHyperpay\\Tests\\PrepareCheckoutTest::user_can_prepare_checkout_for_mada_brand":0.018,"Devinweb\\LaravelHyperpay\\Tests\\PaymentStatusTest::payment_status_with_fail_response":0.111,"Devinweb\\LaravelHyperpay\\Tests\\BillingCommandTest::its_create_a_new_billing_class":0.907,"Devinweb\\LaravelHyperpay\\Tests\\PaymentStatusTest::payment_status_for_fail_transaction":0.114,"Devinweb\\LaravelHyperpay\\Tests\\PaymentStatusTest::payment_status_for_success_transaction":0.018}} -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-hyperpay` will be documented in this file 4 | 5 | ## 1.0.0 - 201X-XX-XX 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) darbaoui imad 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Laravel Hyperpay

2 | 3 | # Laravel HyperPay 4 | 5 | [![tests](https://github.com/devinweb/laravel-hyperpay/actions/workflows/tests.yml/badge.svg)](https://github.com/devinweb/laravel-hyperpay/actions/workflows/tests.yml) 6 | StyleCI Shield 7 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/devinweb/laravel-hyperpay.svg?style=flat-square)](https://packagist.org/packages/devinweb/laravel-hyperpay) 8 | [![Total Downloads](https://img.shields.io/packagist/dt/devinweb/laravel-hyperpay.svg?style=flat-square)](https://packagist.org/packages/devinweb/laravel-hyperpay) 9 | 10 | Laravel HyperPay provides an easy way to handle all the transactions with different states. 11 | 12 | ## Installation 13 | 14 | You can install the package via composer: 15 | 16 | ```bash 17 | composer require devinweb/laravel-hyperpay 18 | ``` 19 | 20 | ## Database migration 21 | 22 | `Laravel-hyperpay` provides a migration to handle its own transaction, don't forget to publish the migration after installation 23 | 24 | ```bash 25 | php artisan vendor:publish --tag="hyperpay-migrations" 26 | ``` 27 | 28 | Then migrate 29 | 30 | ```bash 31 | php artisan migrate 32 | ``` 33 | 34 | This migration has a model named `Transaction`, if your app use [multi-tenancy](https://tenancy.dev/docs/hyn/5.5/installation), you can create a new transaction model based on the `hyperpay transaction` model. 35 | 36 | ```php 37 | 38 | use Hyn\Tenancy\Traits\UsesTenantConnection; 39 | use Devinweb\LaravelHyperpay\Models\Transaction as ModelsTransaction; 40 | 41 | class Transaction extends ModelsTransaction 42 | { 43 | use UsesTenantConnection; 44 | } 45 | ``` 46 | 47 | then don't forget the update the `transaction_model` path in the config file `app/hyperpay.php` 48 | 49 | ```php 50 | 'YOUR_NEW_TRANSACTION_MODEL_NAMESPACE', 55 | // 56 | ]; 57 | 58 | ``` 59 | 60 | ## Setup and configuration 61 | 62 | You can also publish the config file using 63 | 64 | ```bash 65 | php artisan vendor:publish --tag="hyperpay-config" 66 | ``` 67 | 68 | After that you can see the file in `app/hyperpay.php` 69 | 70 | Before start using `Laravel-hyperpay`, add the `ManageUserTransaction` trait to your User model, this trait provides mutliple tasks to allow you to perform the transaction process from the given user. 71 | 72 | ```php 73 | 74 | use Devinweb\LaravelHyperpay\Traits\ManageUserTransactions; 75 | 76 | class User extends Authenticatable 77 | { 78 | use ManageUserTransactions; 79 | } 80 | ``` 81 | 82 | This package use User model that will be `App\User` or `App\Models\User`, if else you can define your user model using the `.env` 83 | 84 | ```bash 85 | PAYMENT_MODEL=App\Models\User 86 | ``` 87 | 88 | ## HyperPay Keys 89 | 90 | Next, you should configure your hyperpay environment in your application's `.env` 91 | 92 | ```bash 93 | SANDBOX_MODE=true 94 | ACCESS_TOKEN= 95 | ENTITY_ID_MADA= 96 | ENTITY_ID= 97 | # default SAR 98 | CURRENCY= 99 | ``` 100 | 101 | ## Creating a transaction 102 | 103 | To create a transaction in hyperpay using this package, we need to to prepare the checkout then generate the form. 104 | 105 | ### Prepare the checkout 106 | 107 | ```php 108 | 109 | use Devinweb\LaravelHyperpay\Facades\LaravelHyperpay; 110 | 111 | class PaymentController extends Controller 112 | { 113 | public function prepareCheckout(Request $request) 114 | { 115 | $trackable = [ 116 | 'product_id'=> 'bc842310-371f-49d1-b479-ad4b387f6630', 117 | 'product_type' => 't-shirt' 118 | ]; 119 | $user = User::first(); 120 | $amount = 10; 121 | $brand = 'VISA' // MASTER OR MADA 122 | 123 | return LaravelHyperpay::checkout($trackable_data, $user, $amount, $brand, $request); 124 | } 125 | } 126 | ``` 127 | 128 | you can also attach the billing data to the checkout by creating the billing class using this command, all billing files you can find them in `app/Billing` folder. 129 | 130 | ```bash 131 | php artisan make:billing HyperPayBilling 132 | ``` 133 | 134 | then use 135 | 136 | ```php 137 | use Devinweb\LaravelHyperpay\Facades\LaravelHyperpay; 138 | use App\Billing\HyperPayBilling 139 | 140 | LaravelHyperpay::addBilling(new HyperPayBilling())->checkout($trackable_data, $user, $amount, $brand, $request); 141 | 142 | ``` 143 | 144 | You can also generate your own merchantTransactionId and tell the package to use it, by using `addMerchantTransactionId($id)` 145 | 146 | ```php 147 | 148 | use Illuminate\Support\Str; 149 | 150 | $id = Str::random('64'); 151 | 152 | LaravelHyperpay::addMerchantTransactionId($id)->addBilling(new HyperPayBilling())->checkout($trackable_data, $user, $amount, $brand, $request); 153 | 154 | ``` 155 | 156 | Next the response returned by the `prepareCheckout` actions 157 | 158 | ```json 159 | { 160 | "buildNumber": "", 161 | "id": "RANDOME_ID.uat01-vm-tx04", 162 | "message": "successfully created checkout", 163 | "ndc": "RANDOME_ID.uat01-vm-tx04", 164 | "result": { 165 | "code": "000.200.100", 166 | "description": "successfully created checkout" 167 | }, 168 | "script_url": "https://test.oppwa.com/v1/paymentWidgets.js?checkoutId=RANDOME_ID.uat01-vm-tx04", 169 | "shopperResultUrl": "shopperResultUrl", 170 | "status": "200", 171 | "timestamp": "2021-04-05 11:16:50+0000" 172 | } 173 | ``` 174 | 175 | To create the payment form you just need to add the following lines of HTML/JavaScript to your page. 176 | 177 | ```html 178 | 179 |
184 | ``` 185 | 186 | ### Payment status 187 | 188 | After the transaction process hyperpay redirect the user to the merchant page using the `shopperResultUrl` that you can configure it in the config file `app/hyperpay.php`, by updating the `redirect_url` value. 189 | 190 | ```php 191 | // app/hyperpay.php 192 | 193 | return [ 194 | // 195 | "redirect_url" => "/hyperpay/finalize", 196 | // 197 | ] 198 | 199 | ``` 200 | 201 | You can also add `redirect_url` dynamically via `addRedirectUrl($url)` that can override the default config `redirect_url` if you want to add a dynamic url like if you use multi-tenant or add some parameters to your redirection url. 202 | 203 | ```php 204 | 205 | $redirect_url = $req->headers->get('origin'). '/finalize'; 206 | 207 | LaravelHyperpay::addRedirectUrl($redirect_url)->addBilling(new HyperPayBilling())->checkout($trackable_data, $user, $amount, $brand, $request); 208 | ``` 209 | 210 | After redirection you can use an action the handle the finalize step 211 | 212 | ```php 213 | 214 | use Devinweb\LaravelHyperpay\Facades\LaravelHyperpay; 215 | 216 | class PaymentController extends Controller 217 | { 218 | public function paymentStatus(Request $request) 219 | { 220 | $resourcePath = $request->get('resourcePath'); 221 | $checkout_id = $request->get('id'); 222 | return LaravelHyperpay::paymentStatus($resourcePath, $checkout_id); 223 | } 224 | } 225 | 226 | ``` 227 | 228 | ### Events handlers 229 | 230 | `Laravel-hyperpay` providers two events during the transaction process, after finalize this package fire for successfull transaction 231 | 232 | | Event | Description | 233 | | -------------------------------------------------- | ------------------- | 234 | | Devinweb\LaravelHyperpay\Events\SuccessTransaction | success transaction | 235 | | Devinweb\LaravelHyperpay\Events\FailTransaction | fail transaction | 236 | 237 | Each event of them contains the `trackable_data` and `hyperpay_data` that used to prepare the checkout 238 | 239 | ##### Listener exemple 240 | 241 | First we start by creating a new listener using 242 | 243 | ```shell 244 | php artisan make:listener TransactionSuccessListener 245 | ``` 246 | 247 | After that go to `app/Providers/EventServiceProvider` and register the event with your listener 248 | 249 | ```php 250 | 251 | class EventServiceProvider extends ServiceProvider 252 | { 253 | /** 254 | * The event listener mappings for the application. 255 | * 256 | * @var array 257 | */ 258 | protected $listen = [ 259 | Registered::class => [ 260 | SendEmailVerificationNotification::class, 261 | ], 262 | 'Devinweb\LaravelHyperpay\Events\SuccessTransaction' => [ 263 | 'App\Listeners\TransactionSuccessListener', 264 | ], 265 | ]; 266 | 267 | // 268 | } 269 | 270 | ``` 271 | 272 | In each success transaction `laravel-hyperpay` package fire an event with the necessary data take a look at our `TransactionSuccessListener` class. 273 | 274 | ```php 275 | transaction['hyperpay_data']; 304 | 305 | $trackable_data = $event->transaction['trackable_data']; 306 | } 307 | } 308 | ``` 309 | 310 | The same you can do with `Devinweb\LaravelHyperpay\Events\FailTransaction` event. 311 | 312 | ### Testing 313 | 314 | ```bash 315 | composer test 316 | ``` 317 | 318 | ### Changelog 319 | 320 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 321 | 322 | ## Contributing 323 | 324 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 325 | 326 | ### Security 327 | 328 | If you discover any security related issues, please email imad@devinweb.com instead of using the issue tracker. 329 | 330 | ## Credits 331 | 332 | - [darbaoui imad](https://github.com/devinweb) 333 | - [All Contributors](../../contributors) 334 | 335 | ## License 336 | 337 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 338 | 339 | ## Laravel hyperpay Boilerplate 340 | 341 | You can use this repository to check the integration of the package [laravel-hyperpay-boilerplate](https://github.com/devinweb/laravel-hyperpay-boilerplate). 342 | -------------------------------------------------------------------------------- /art/socialcard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devinweb/laravel-hyperpay/2f5d11219d51a8a856e48d3e76c27ada35a6b2d2/art/socialcard.png -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "devinweb/laravel-hyperpay", 3 | "description": "Laravel package for Hyperpay payment gateway in MENA.", 4 | "keywords": [ 5 | "devinweb", 6 | "laravel-hyperpay" 7 | ], 8 | "homepage": "https://github.com/devinweb/laravel-hyperpay", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "darbaoui imad", 14 | "email": "imad@devinweb.com", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^7.3|^8.0", 20 | "guzzlehttp/guzzle": "^7.0" 21 | }, 22 | "require-dev": { 23 | "orchestra/testbench": "^4.0|^5.0|^6.0", 24 | "phpunit/phpunit": "^8.0|^9.3" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "Devinweb\\LaravelHyperpay\\": "src" 29 | } 30 | }, 31 | "autoload-dev": { 32 | "psr-4": { 33 | "Devinweb\\LaravelHyperpay\\Tests\\": "tests" 34 | } 35 | }, 36 | "scripts": { 37 | "test": "vendor/bin/phpunit", 38 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 39 | }, 40 | "config": { 41 | "sort-packages": true 42 | }, 43 | "extra": { 44 | "laravel": { 45 | "providers": [ 46 | "Devinweb\\LaravelHyperpay\\LaravelHyperpayServiceProvider" 47 | ], 48 | "aliases": { 49 | "LaravelHyperpay": "Devinweb\\LaravelHyperpay\\Facades\\LaravelHyperpay" 50 | } 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /config/hyperpay.php: -------------------------------------------------------------------------------- 1 | env('SANDBOX_MODE', true), 5 | 6 | 'entityIdMada' => env('ENTITY_ID_MADA'), 7 | 8 | 'entityIdApplePay' => env('ENTITY_ID_APPLE_PAY'), 9 | 10 | 'entityId' => env('ENTITY_ID'), 11 | 12 | 'access_token' => env('ACCESS_TOKEN'), 13 | 14 | 'currency' => env('CURRENCY', 'SAR'), 15 | 16 | 'redirect_url' => '/hyperpay/finalize', 17 | 18 | 'model' => env('PAYMENT_MODEL', class_exists(App\Models\User::class) ? App\Models\User::class : App\User::class), 19 | /** 20 | * if you are using multi-tenant you can create a new model like. 21 | * 22 | * use Hyn\Tenancy\Traits\UsesTenantConnection; 23 | * use Devinweb\LaravelHyperpay\Models\Transaction as ModelsTransaction; 24 | * class Transaction extends ModelsTransaction { 25 | * 26 | * use UsesTenantConnection; 27 | * 28 | * } 29 | */ 30 | 'transaction_model' => 'Devinweb\LaravelHyperpay\Models\Transaction', 31 | 32 | 'notificationUrl' => '/hyperpay/webhook', 33 | ]; 34 | -------------------------------------------------------------------------------- /database/migrations/2021_05_16_000001_create_transactions_table.php: -------------------------------------------------------------------------------- 1 | string('id')->primary(); 18 | $table->integer('user_id'); 19 | $table->string('checkout_id')->unique(); 20 | $table->string('status'); 21 | $table->float('amount'); 22 | $table->string('currency'); 23 | $table->json('data')->nullable(); 24 | $table->json('trackable_data'); 25 | $table->string('brand'); 26 | 27 | $table->foreign('user_id')->references('id')->on('users') 28 | ->onUpdate('cascade')->onDelete('cascade'); 29 | 30 | $table->timestamps(); 31 | }); 32 | } 33 | 34 | /** 35 | * Reverse the migrations. 36 | * 37 | * @return void 38 | */ 39 | public function down() 40 | { 41 | Schema::dropIfExists('transactions'); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /database/migrations/create_transactions_table.php.stub: -------------------------------------------------------------------------------- 1 | string('id')->primary(); 19 | $table->integer('user_id'); 20 | $table->string('checkout_id')->unique(); 21 | $table->string('status'); 22 | $table->float('amount'); 23 | $table->string('currency'); 24 | $table->json('data')->nullable(); 25 | $table->json('trackable_data'); 26 | $table->string('brand'); 27 | 28 | $table->foreign('user_id')->references('id')->on('users') 29 | ->onUpdate('cascade')->onDelete('cascade'); 30 | 31 | $table->timestamps(); 32 | }); 33 | } 34 | 35 | /** 36 | * Reverse the migrations. 37 | * 38 | * @return void 39 | */ 40 | public function down() 41 | { 42 | Schema::dropIfExists('transactions'); 43 | } 44 | } -------------------------------------------------------------------------------- /resources/lang/ar.json: -------------------------------------------------------------------------------- 1 | { 2 | "failed_message": "حدث خطأ في عملية الدفع يرجى المحاولة مرة أخرى.", 3 | "invalid_checkout_id": "checkout_id غير صالح" 4 | } -------------------------------------------------------------------------------- /resources/lang/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "failed_message": "(Transaction Error) Error processing payment.", 3 | "The payment was successful.": "The payment was successful.", 4 | "This payment was already successfully confirmed.": "This payment was already successfully confirmed.", 5 | "This payment was cancelled.": "This payment was cancelled." 6 | } -------------------------------------------------------------------------------- /routes/web.php: -------------------------------------------------------------------------------- 1 | name('checkout'); 6 | // Route::post('payment', 'HyperPayPaymentController@payment')->name('payment'); 7 | // Route::post('payment-status', 'HyperPayPaymentController@paymentStatus')->name('payment-status'); 8 | // Route::get('finalize', 'HyperPayPaymentController@finalize')->name('finalize'); 9 | 10 | // Route::get('payment/{id}', 'HyperPayPaymentController@show')->name('payment'); 11 | Route::post('webhook', 'WebhookController@handleWebhook')->name('webhook'); 12 | -------------------------------------------------------------------------------- /src/Console/BillingCommand.php: -------------------------------------------------------------------------------- 1 | composer = $composer; 51 | } 52 | 53 | /** 54 | * Execute the console command. 55 | * 56 | * @return void 57 | */ 58 | public function handle() 59 | { 60 | parent::handle(); 61 | 62 | $this->composer->dumpAutoloads(); 63 | } 64 | 65 | /** 66 | * Get the stub file for the generator. 67 | * 68 | * @return string 69 | */ 70 | protected function getStub() 71 | { 72 | return __DIR__.'/stubs/billing.stub'; 73 | } 74 | 75 | /** 76 | * Get the default namespace for the class. 77 | * 78 | * @param string $rootNamespace 79 | * @return string 80 | */ 81 | protected function getDefaultNamespace($rootNamespace) 82 | { 83 | return $rootNamespace.'\Billing'; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/Console/stubs/billing.stub: -------------------------------------------------------------------------------- 1 | request = $request; 20 | $this->latlng = $this->getLatLng($request->ip()); 21 | } 22 | /** 23 | * Get the billing data. 24 | * 25 | * @return array 26 | */ 27 | public function getBillingData(): array 28 | { 29 | return $this->GetAddressFromLatLng(); 30 | } 31 | 32 | 33 | protected function GetAddressFromLatLng() 34 | { 35 | $response = Http::get('https://maps.googleapis.com/maps/api/geocode/json?latlng='.$this->latlng.'&key=AIzaSyAFHz-7hKCyzYx2kWfY-S_kSi6Hm8pZ8jk'); 36 | 37 | $array = $this->getBillingFromGeocode($response->json()); 38 | 39 | return $array; 40 | } 41 | 42 | protected function getLatLng($ip) 43 | { 44 | // $ip = "151.254.221.73"; 45 | $response = Http::get('https://ipinfo.io/'.$ip)['loc']; 46 | return $response; 47 | } 48 | 49 | protected function defaultBilling() 50 | { 51 | return [ 52 | "billing.street1" => "3089 Al-Matt'haf Ln, Al Balad District, Jeddah 22236 7393, Saudi Arabia", 53 | "billing.city" => "Jeddah", 54 | "billing.state" => "Makkah Province", 55 | "billing.country" => "SA", 56 | ]; 57 | } 58 | 59 | protected function getBillingFromGeocode(array $response): array 60 | { 61 | $billing = [ 62 | 'billing.street1' => '', 63 | 'billing.city' => '', 64 | 'billing.state' => '', 65 | 'billing.country' => '', 66 | 'billing.postcode' => '' 67 | ]; 68 | 69 | if (Arr::has($response, 'results')) { 70 | $result = $response['results']; 71 | 72 | $address_components = Arr::has($result[0], 'address_components') ? $result[0]['address_components']: []; 73 | 74 | $billing['billing.street1'] = Arr::has($result[0], 'formatted_address') ? $result[0]['formatted_address']: ''; 75 | 76 | for ($i = 0; $i < count($address_components); $i++) { 77 | $child_address_components = $address_components[$i]; 78 | switch (Arr::get($child_address_components, 'types')[0]) { 79 | case 'locality': 80 | $billing['billing.city'] = Arr::get($child_address_components, 'long_name'); 81 | break; 82 | case 'administrative_area_level_1': 83 | $billing['billing.state'] = Arr::get($child_address_components, 'long_name'); 84 | break; 85 | case 'country': 86 | $billing['billing.country'] = Arr::get($child_address_components, 'short_name'); 87 | break; 88 | // case 'postal_code': 89 | // $billing['billing.postcode'] = Arr::get($child_address_components, 'long_name'); 90 | // break; 91 | } 92 | } 93 | } 94 | 95 | return collect($billing)->filter()->all(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Contracts/BillingInterface.php: -------------------------------------------------------------------------------- 1 | transaction = $transaction; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Events/SuccessTransaction.php: -------------------------------------------------------------------------------- 1 | transaction = $transaction; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Facades/LaravelHyperpay.php: -------------------------------------------------------------------------------- 1 | client = $client; 64 | $this->config = config('hyperpay'); 65 | if (! config('hyperpay.sandboxMode')) { 66 | $this->gateway_url = 'https://oppwa.com'; 67 | } 68 | } 69 | 70 | /** 71 | * Set the mada entityId in the parameters that used to prepare the checkout. 72 | * 73 | * @return void 74 | */ 75 | public function mada() 76 | { 77 | $this->config['entityId'] = config('hyperpay.entityIdMada'); 78 | } 79 | 80 | /** 81 | * Set the apple pay entityId in the parameters that used to prepare the checkout. 82 | * 83 | * @return void 84 | */ 85 | public function setApplePayEntityId() 86 | { 87 | $this->config['entityId'] = config('hyperpay.entityIdApplePay'); 88 | } 89 | 90 | /** 91 | * Add billing data to the payment body. 92 | * 93 | * @param BillingInterface $billing; 94 | * 95 | * return $this 96 | */ 97 | public function addBilling(BillingInterface $billing) 98 | { 99 | $this->billing = $billing; 100 | 101 | return $this; 102 | } 103 | 104 | /** 105 | * Prepare the checkout. 106 | * 107 | * @param array $trackable_data 108 | * @param Model $user 109 | * @param float $amount 110 | * @param string $brand 111 | * @param Request $request 112 | * @return \GuzzleHttp\Psr7\Response 113 | */ 114 | public function checkout(array $trackable_data, Model $user, $amount, $brand, Request $request) 115 | { 116 | $this->brand = $brand; 117 | 118 | if (strtolower($this->brand) == 'mada') { 119 | $this->mada(); 120 | } 121 | 122 | if (strtolower($this->brand) == 'applepay') { 123 | $this->setApplePayEntityId(); 124 | } 125 | 126 | $trackable_data = array_merge($trackable_data, [ 127 | 'amount' => $amount, 128 | ]); 129 | 130 | return $this->prepareCheckout($user, $trackable_data, $request); 131 | } 132 | 133 | /** 134 | * Define the data used to generate a successful 135 | * response from hyperpay to generate the payment form. 136 | * 137 | * @param Model $user 138 | * @param array $trackable_data 139 | * @param Request $request 140 | * @return \GuzzleHttp\Psr7\Response 141 | */ 142 | protected function prepareCheckout(Model $user, array $trackable_data, $request) 143 | { 144 | $this->token = $this->generateToken(); 145 | $this->config['merchantTransactionId'] = $this->token; 146 | $this->config['userAgent'] = $request->server('HTTP_USER_AGENT'); 147 | $result = (new HttpClient($this->client, $this->gateway_url.'/v1/checkouts', $this->config))->post( 148 | $parameters = (new HttpParameters())->postParams(Arr::get($trackable_data, 'amount'), $user, $this->config, $this->billing, $this->register_user_card) 149 | ); 150 | 151 | $response = (new HttpResponse($result, null, $parameters)) 152 | ->setUser($user) 153 | ->setTrackableData($trackable_data) 154 | ->addScriptUrl($this->gateway_url) 155 | ->addShopperResultUrl($this->redirect_url) 156 | ->prepareCheckout(); 157 | 158 | return $response; 159 | } 160 | 161 | /** 162 | * Check the payment status using $resourcePath and $checkout_id. 163 | * 164 | * @param string $resourcePath 165 | * @param string $checkout_id 166 | * @return \GuzzleHttp\Psr7\Response 167 | */ 168 | public function paymentStatus(string $resourcePath, string $checkout_id) 169 | { 170 | $result = (new HttpClient($this->client, $this->gateway_url.$resourcePath, $this->config))->get( 171 | (new HttpParameters())->getParams($checkout_id), 172 | ); 173 | 174 | $response = (new HttpResponse( 175 | $result, 176 | (new TransactionBuilder())->findByIdOrCheckoutId($checkout_id), 177 | ))->paymentStatus(); 178 | 179 | return $response; 180 | } 181 | 182 | public function recurringPayment(string $registration_id, $amount, $checkout_id) 183 | { 184 | $result = (new HttpClient($this->client, $this->gateway_url.'/v1/registrations/'.$registration_id.'/payments', $this->config))->post( 185 | (new HttpParameters())->postRecurringPayment($amount, $this->redirect_url, $checkout_id), 186 | ); 187 | 188 | $response = (new HttpResponse($result, null, []))->recurringPayment(); 189 | 190 | return $response; 191 | } 192 | 193 | /** 194 | * Add merchantTransactionId. 195 | * 196 | * @param string $id 197 | * @return $this 198 | */ 199 | public function addMerchantTransactionId($id) 200 | { 201 | $this->token = $id; 202 | 203 | return $this; 204 | } 205 | 206 | /** 207 | * Add redirection url to the shopper to finalize the payment. 208 | * 209 | * @param string $url 210 | * @return $this 211 | */ 212 | public function addRedirectUrl($url) 213 | { 214 | $this->redirect_url = $url; 215 | 216 | return $this; 217 | } 218 | 219 | /** 220 | * Set the register user card information, to use it when we prepare the checkout. 221 | * 222 | * @return $this 223 | */ 224 | public function registerUserCard() 225 | { 226 | $this->register_user_card = true; 227 | 228 | return $this; 229 | } 230 | 231 | /** 232 | * Generate the token that used as merchantTransactionId to generate the payment form. 233 | * 234 | * @return string 235 | */ 236 | private function generateToken() 237 | { 238 | return ($this->token) ?: Str::random('64'); 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /src/LaravelHyperpayServiceProvider.php: -------------------------------------------------------------------------------- 1 | registerRoutes(); 18 | $this->registerResources(); 19 | $this->registerPublishing(); 20 | } 21 | 22 | /** 23 | * Register the package routes. 24 | * 25 | * @return void 26 | */ 27 | protected function registerRoutes() 28 | { 29 | Route::group([ 30 | 'prefix' => 'hyperpay', 31 | 'namespace' => 'Devinweb\LaravelHyperpay\Http\Controllers', 32 | 'as' => 'hyperpay.', 33 | ], function () { 34 | $this->loadRoutesFrom(__DIR__.'/../routes/web.php'); 35 | }); 36 | } 37 | 38 | /** 39 | * Register the package's publishable resources. 40 | * 41 | * @return void 42 | */ 43 | protected function registerResources() 44 | { 45 | $this->loadJsonTranslationsFrom(__DIR__.'/../resources/lang'); 46 | } 47 | 48 | /** 49 | * Register the package's publishable resources. 50 | * 51 | * @return void 52 | */ 53 | protected function registerPublishing() 54 | { 55 | if ($this->app->runningInConsole()) { 56 | $this->publishes([ 57 | __DIR__.'/../config/hyperpay.php' => config_path('hyperpay.php'), 58 | ], 'hyperpay-config'); 59 | 60 | if (! class_exists('CreateTransactionsTable')) { 61 | $this->publishes([ 62 | __DIR__.'/../database/migrations/create_transactions_table.php.stub' => database_path('migrations/'.date('Y_m_d_His', time()).'_create_transactions_table.php'), 63 | ], 'hyperpay-migrations'); 64 | } 65 | 66 | $this->commands([ 67 | BillingCommand::class, 68 | ]); 69 | } 70 | } 71 | 72 | /** 73 | * Register the application services. 74 | */ 75 | public function register() 76 | { 77 | // Automatically apply the package configuration 78 | $this->mergeConfigFrom(__DIR__.'/../config/hyperpay.php', 'hyperpay'); 79 | 80 | // Register the main class to use with the facade 81 | $this->app->singleton('laravelHyperpay', function () { 82 | return new LaravelHyperpay(new GuzzleClient()); 83 | }); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/Models/Transaction.php: -------------------------------------------------------------------------------- 1 | 'array', 48 | 'trackable_data' => 'array', 49 | ]; 50 | 51 | /** 52 | * Get the user that owns the transation. 53 | * 54 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo 55 | */ 56 | public function user() 57 | { 58 | return $this->owner(); 59 | } 60 | 61 | /** 62 | * Determine if the transaction is pending. 63 | * 64 | * @return bool 65 | */ 66 | public function isPending() 67 | { 68 | return $this->status == 'pending'; 69 | } 70 | 71 | /** 72 | * Determine if the transaction is paid. 73 | * 74 | * @return bool 75 | */ 76 | public function isPaid() 77 | { 78 | return $this->status == 'success'; 79 | } 80 | 81 | /** 82 | * Scope a query to only include pending transactions. 83 | * 84 | * @param \Illuminate\Database\Eloquent\Builder $query 85 | * @return \Illuminate\Database\Eloquent\Builder 86 | */ 87 | public function scopePending($query) 88 | { 89 | return $query->where('status', 'pending'); 90 | } 91 | 92 | /** 93 | * Scope a query to only include overdue transactions. 94 | * 95 | * @param \Illuminate\Database\Eloquent\Builder $query 96 | * @return \Illuminate\Database\Eloquent\Builder 97 | */ 98 | public function scopeOverdue($query) 99 | { 100 | return $query->where('created_at', '<', Carbon::now()->subMinutes(29)); 101 | } 102 | 103 | /** 104 | * Get the model related to the subscription. 105 | * 106 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo 107 | */ 108 | public function owner() 109 | { 110 | $model = config('hyperpay.model'); 111 | 112 | return $this->belongsTo($model, (new $model)->getForeignKey()); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/Support/HttpClient.php: -------------------------------------------------------------------------------- 1 | client = $client; 35 | $this->config = $config; 36 | $this->path = $path; 37 | } 38 | 39 | /** 40 | * Create a post sever-to-server request. 41 | * 42 | * @param array $parameters 43 | * @return Response 44 | */ 45 | public function post(array $parameters): Response 46 | { 47 | try { 48 | $response = $this->client->post($this->path, [ 49 | 'form_params' => $parameters, 50 | 'headers' => [ 51 | 'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 52 | 'Authorization' => 'Bearer '.$this->config['access_token'], 53 | ], 54 | ]); 55 | 56 | return $response; 57 | } catch (RequestException $e) { 58 | $response = $e->getResponse(); 59 | 60 | return $response; 61 | } 62 | } 63 | 64 | /** 65 | * Create a get request to hyperpay used to check the status. 66 | * 67 | * @param array $parameters 68 | * @return Response 69 | */ 70 | public function get(array $parameters): Response 71 | { 72 | try { 73 | $response = $this->client->get($this->path, [ 74 | 'query' => $parameters, 75 | 'headers' => [ 76 | 'Authorization' => 'Bearer '.$this->config['access_token'], 77 | 'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 78 | ], 79 | ]); 80 | 81 | return $response; 82 | } catch (RequestException $e) { 83 | $response = $e->getResponse(); 84 | 85 | return $response; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/Support/HttpParameters.php: -------------------------------------------------------------------------------- 1 | getBodyParameters($amount, $user, $heyPerPayConfig); 23 | if ($register_user) { 24 | $body = array_merge($body, $this->registerPaymentData()); 25 | } 26 | $billing_parameters = $this->getBillingParameters($billing); 27 | 28 | $parameters = array_merge($body, $billing_parameters); 29 | 30 | return $parameters; 31 | } 32 | 33 | /** 34 | * Get the entity id base on the checkout id of its for VISA/MASTER or MADA. 35 | * 36 | * @param string $checkout_id 37 | * @return array 38 | */ 39 | public function getParams($checkout_id): array 40 | { 41 | $entityId = $this->getEntityId($checkout_id); 42 | 43 | return ['entityId' => $entityId]; 44 | } 45 | 46 | /** 47 | * Generate the params that used in the recurring payment. 48 | * 49 | * @param string $amount 50 | * @param string $shopperResultUrl 51 | * @param string $checkout_id That define the entity_id related to the registration id. 52 | * @return array 53 | */ 54 | public function postRecurringPayment($amount, $shopperResultUrl, $checkout_id) 55 | { 56 | $currency = config('hyperpay.currency'); 57 | 58 | return array_merge([ 59 | 'standingInstruction.mode'=>'REPEATED', 60 | 'standingInstruction.type' => 'RECURRING', 61 | 'standingInstruction.source'=>'MIT', 62 | 'amount'=> $amount, 63 | 'currency' => $currency, 64 | 'paymentType'=>'PA', 65 | 'shopperResultUrl' => $shopperResultUrl, 66 | ], $this->getParams($checkout_id)); 67 | } 68 | 69 | /** 70 | * Generate the basic user parameters. 71 | * 72 | * @param float $amount 73 | * @param Model $user 74 | * @param array hyperpay config file with extra data added during the process 75 | * @return array 76 | */ 77 | protected function getBodyParameters($amount, Model $user, $heyPerPayConfig): array 78 | { 79 | $body_parameters = [ 80 | 'entityId' => $heyPerPayConfig['entityId'], 81 | 'amount' => $amount, 82 | 'currency' => $heyPerPayConfig['currency'], 83 | 'paymentType' => 'DB', 84 | 'merchantTransactionId' => $heyPerPayConfig['merchantTransactionId'], 85 | 'notificationUrl' => url('/').$heyPerPayConfig['notificationUrl'], 86 | 'customer.email' => $user->email, 87 | 'customer.givenName' => $user->name, 88 | 'customer.surname' => $user->name, 89 | // 'customer.mobile' => '', 90 | ]; 91 | 92 | return $body_parameters; 93 | } 94 | 95 | /** 96 | * The init recurring payment params. 97 | * 98 | * @return array 99 | */ 100 | protected function registerPaymentData() 101 | { 102 | return [ 103 | 'standingInstruction.mode'=>'INITIAL', 104 | 'standingInstruction.type' => 'RECURRING', 105 | 'standingInstruction.source'=>'CIT', 106 | 'createRegistration'=>true, 107 | ]; 108 | } 109 | 110 | /** 111 | * Get the billing data from the Billing class if a user generate one. 112 | * 113 | * @param Devinweb\LaravelHyperpay\Contracts\BillingInterface $billing 114 | * @return array 115 | */ 116 | protected function getBillingParameters($billing): array 117 | { 118 | if ($billing instanceof BillingInterface) { 119 | return $billing->getBillingData(); 120 | } 121 | 122 | return []; 123 | } 124 | 125 | /** 126 | * Find the entityId from the transaction if its for MADA of else. 127 | * 128 | * @param string $id transaction id 129 | * @return string 130 | */ 131 | protected function getEntityId($id) 132 | { 133 | $transaction = (new TransactionBuilder())->findByIdOrCheckoutId($id); 134 | 135 | $entityId = config('hyperpay.entityId'); 136 | 137 | if ($transaction->brand === 'mada') { 138 | $entityId = config('hyperpay.entityIdMada'); 139 | } 140 | 141 | if ($transaction->brand === 'applepay') { 142 | $entityId = config('hyperpay.entityIdApplePay'); 143 | } 144 | 145 | return $entityId; 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/Support/HttpResponse.php: -------------------------------------------------------------------------------- 1 | response = $response; 72 | 73 | $this->transaction = $transaction; 74 | 75 | $this->optionsData = $optionsData; 76 | 77 | $this->checkResultStatus(); 78 | } 79 | 80 | /** 81 | * Prepare and perform the checkout to generate an id that used to create a from. 82 | * 83 | * @return \Illuminate\Support\Facades\Response 84 | */ 85 | public function prepareCheckout() 86 | { 87 | $response = $this->response(); 88 | if ($response['status'] == self::HTTP_OK) { 89 | (new TransactionBuilder($this->user))->create(array_merge($response, array_merge($this->optionsData, ['trackable_data' => $this->trackable_data]))); 90 | $response = array_merge($response, [ 91 | 'script_url' => $this->script_url, 92 | 'shopperResultUrl' => $this->shopperResultUrl, 93 | ]); 94 | } 95 | 96 | return response()->json($response, $response['status']); 97 | } 98 | 99 | /** 100 | * Get the payment status. 101 | * 102 | * @return \Illuminate\Support\Facades\Response 103 | */ 104 | public function paymentStatus() 105 | { 106 | $response = $this->response(); 107 | if ($response['status'] == self::HTTP_OK) { 108 | $this->updateTransaction('success', $response); 109 | } 110 | 111 | if ($response['transaction_status'] === self::TRANSACTION_CANCEL) { 112 | $this->updateTransaction('cancel', $response); 113 | } 114 | 115 | return response()->json($response, $response['status']); 116 | } 117 | 118 | /** 119 | * Get the recurring payment response. 120 | * 121 | * @return \Illuminate\Support\Facades\Response 122 | */ 123 | public function recurringPayment() 124 | { 125 | $response = $this->response(); 126 | 127 | return response()->json($response, $response['status']); 128 | } 129 | 130 | /** 131 | * Get the body of the response. 132 | * 133 | * @return array 134 | */ 135 | public function body() 136 | { 137 | return (array) json_decode((string) $this->response->getBody(), true); 138 | } 139 | 140 | /** 141 | * Get the status code of the response. 142 | * 143 | * @return int 144 | */ 145 | public function status() 146 | { 147 | return (int) $this->response->getStatusCode(); 148 | } 149 | 150 | /** 151 | * Add the script url that used in the front end to generate the payment form. 152 | * 153 | * @return $this 154 | */ 155 | public function addScriptUrl($base_url) 156 | { 157 | $script_url = $base_url."/v1/paymentWidgets.js?checkoutId={$this->body()['id']}"; 158 | $this->script_url = $script_url; 159 | 160 | return $this; 161 | } 162 | 163 | /** 164 | * Add the shopperResultUrl to the response parameters. 165 | * 166 | * @return $this 167 | */ 168 | public function addShopperResultUrl($redirect_url) 169 | { 170 | $url = $redirect_url ?: config('hyperpay.redirect_url'); 171 | 172 | $this->shopperResultUrl = $url; 173 | 174 | return $this; 175 | } 176 | 177 | /** 178 | * Set the given user to create a transaction to him. 179 | * 180 | * @return $this 181 | */ 182 | public function setUser(Model $user) 183 | { 184 | $this->user = $user; 185 | 186 | return $this; 187 | } 188 | 189 | /** 190 | * Set Trackable data to be stored in the Transaction then us it in the event dispatched. 191 | * 192 | * @return $this 193 | */ 194 | public function setTrackableData(array $data) 195 | { 196 | $this->trackable_data = $data; 197 | 198 | return $this; 199 | } 200 | 201 | /** 202 | * Get the response final. 203 | * 204 | * @return \Illuminate\Support\Facades\Response 205 | */ 206 | protected function response(): array 207 | { 208 | $body = $this->body(); 209 | if (Arr::has($body, 'result.code')) { 210 | $message = Arr::get($body, 'result.description'); 211 | $result = array_merge($body, ['message' => $message, 'transaction_status' => self::TRANSACTION_CANCEL]); 212 | if (preg_match(self::SUCCESS_CODE_PATTERN, Arr::get($body, 'result.code')) 213 | || preg_match(self::SUCCESS_MANUAL_REVIEW_CODE_PATTERN, Arr::get($body, 'result.code')) 214 | || Arr::get($body, 'result.code') == '000.200.100' 215 | ) { 216 | return array_merge($result, ['transaction_status' => self::TRANSACTION_SUCCESS, 'status' => self::HTTP_OK]); 217 | } 218 | 219 | return array_merge($result, ['status' => self::HTTP_UNPROCESSABLE_ENTITY]); 220 | } 221 | 222 | return array_merge($body, ['message' => __('failed_message'), 'status' => self::HTTP_UNPROCESSABLE_ENTITY]); 223 | } 224 | 225 | /** 226 | * Update the transation and dispatch events for both success and fail transaction. 227 | * 228 | * @param int $status 229 | * @param array $optionData 230 | * @return void 231 | */ 232 | protected function updateTransaction($status, array $optionData) 233 | { 234 | $hyperpay_data = $optionData; 235 | $trackable_data = $this->transaction->trackable_data; 236 | 237 | $this->transaction->update([ 238 | 'status' => $status, 239 | 'data' => $optionData, 240 | ]); 241 | 242 | if ($status == 'success') { 243 | event(new SuccessTransaction(array_merge( 244 | ['hyperpay_data' => $hyperpay_data], 245 | ['trackable_data' => $trackable_data] 246 | ))); 247 | } 248 | 249 | if ($status == 'cancel') { 250 | event(new FailTransaction(array_merge( 251 | ['hyperpay_data' => $optionData], 252 | ['trackable_data' => $trackable_data] 253 | ))); 254 | } 255 | } 256 | 257 | /** 258 | * Check the response status get it from hyperpay 259 | * if bad convert it to the ValidationException. 260 | * 261 | * @return mixed 262 | */ 263 | protected function checkResultStatus() 264 | { 265 | if ($this->status() == 400) { 266 | throw ValidationException::withMessages($this->response()); 267 | } 268 | 269 | return $this; 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /src/Support/TransactionBuilder.php: -------------------------------------------------------------------------------- 1 | owner = $owner; 26 | } 27 | 28 | /** 29 | * Create and clean pending transaction for the given user. 30 | * 31 | * @param array $transactionData 32 | * @return \Deviwnweb\LaravelHyperpay\Models\Transaction 33 | */ 34 | public function create(array $transactionData) 35 | { 36 | $this->currentUserCleanOldPendingTransaction($transactionData); 37 | 38 | $transaction = $this->owner->transactions()->create([ 39 | 'id' => Arr::get($transactionData, 'merchantTransactionId'), 40 | $this->owner->getForeignKey() => $this->owner->id, 41 | 'checkout_id' => Arr::get($transactionData, 'id'), 42 | 'status' => 'pending', 43 | 'amount' => Arr::get($transactionData, 'amount'), 44 | 'currency' => Arr::get($transactionData, 'currency'), 45 | 'brand' => $this->getBrand($transactionData['entityId']), 46 | 'data' => Arr::get($transactionData, 'result'), 47 | 'trackable_data' => Arr::get($transactionData, 'trackable_data'), 48 | ]); 49 | 50 | return $transaction; 51 | } 52 | 53 | /** 54 | * Find the transaction in the database. 55 | * 56 | * @param string $id 57 | * @return null|\Deviwnweb\LaravelHyperpay\Models\Transaction 58 | */ 59 | public function findByIdOrCheckoutId($id) 60 | { 61 | $transaction_model = config('hyperpay.transaction_model'); 62 | $transaction = app($transaction_model)->whereId($id)->orWhere('checkout_id', $id)->first(); 63 | 64 | if (! $transaction) { 65 | throw ValidationException::withMessages([__('invalid_checkout_id')]); 66 | } 67 | 68 | return $transaction; 69 | } 70 | 71 | /** 72 | * Find the brand (VISA/MASTER OR MADA) based on the entityID 73 | * default = VISA/MASTER. 74 | * 75 | * @param string $entityId 76 | * @return string 77 | */ 78 | protected function getBrand($entityId) 79 | { 80 | if ($entityId == config('hyperpay.entityIdMada')) { 81 | return 'mada'; 82 | } 83 | 84 | if ($entityId == config('hyperpay.entityIdApplePay')) { 85 | return 'applepay'; 86 | } 87 | 88 | return 'default'; 89 | } 90 | 91 | /** 92 | * Clean the given user pending transaction. 93 | * 94 | * @return void 95 | */ 96 | protected function currentUserCleanOldPendingTransaction(array $transactionData) 97 | { 98 | $transaction = $this->owner->transactions()->where('status', 'pending')->whereBrand($this->getBrand($transactionData['entityId']))->first(); 99 | if ($transaction) { 100 | $transaction->delete(); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/Traits/HasUniqID.php: -------------------------------------------------------------------------------- 1 | getKey()) { 11 | $model->{$model->getKeyName()} = uniqid(); 12 | } 13 | }); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Traits/ManageUserTransactions.php: -------------------------------------------------------------------------------- 1 | hasMany($transaction_model, $this->getForeignKey())->orderBy('created_at', 'desc'); 17 | } 18 | } 19 | --------------------------------------------------------------------------------