Repository: amsgames/laravel-shop Branch: v0.2 Commit: 0e6c062dcf0a Files: 51 Total size: 161.9 KB Directory structure: gitextract_vn1_djci/ ├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── composer.lock.bk ├── src/ │ ├── .gitkeep │ ├── Commands/ │ │ └── MigrationCommand.php │ ├── Config/ │ │ └── config.php │ ├── Contracts/ │ │ ├── PaymentGatewayInterface.php │ │ ├── ShopCartInterface.php │ │ ├── ShopCouponInterface.php │ │ ├── ShopItemInterface.php │ │ ├── ShopOrderInterface.php │ │ └── ShopTransactionInterface.php │ ├── Core/ │ │ └── PaymentGateway.php │ ├── Events/ │ │ ├── CartCheckout.php │ │ ├── OrderCompleted.php │ │ ├── OrderPlaced.php │ │ └── OrderStatusChanged.php │ ├── Exceptions/ │ │ ├── CheckoutException.php │ │ ├── GatewayException.php │ │ └── ShopException.php │ ├── Gateways/ │ │ ├── GatewayCallback.php │ │ ├── GatewayFail.php │ │ └── GatewayPass.php │ ├── Http/ │ │ └── Controllers/ │ │ ├── Controller.php │ │ └── Shop/ │ │ └── CallbackController.php │ ├── LaravelShop.php │ ├── LaravelShopFacade.php │ ├── LaravelShopProvider.php │ ├── Models/ │ │ ├── ShopCartModel.php │ │ ├── ShopCouponModel.php │ │ ├── ShopItemModel.php │ │ ├── ShopOrderModel.php │ │ └── ShopTransactionModel.php │ ├── Traits/ │ │ ├── ShopCalculationsTrait.php │ │ ├── ShopCartTrait.php │ │ ├── ShopCouponTrait.php │ │ ├── ShopItemTrait.php │ │ ├── ShopOrderTrait.php │ │ ├── ShopTransactionTrait.php │ │ └── ShopUserTrait.php │ └── views/ │ └── generators/ │ ├── migration.blade.php │ └── seeder.blade.php └── tests/ ├── .gitkeep ├── README.md ├── ShopTest.php ├── cart/ │ ├── CartTest.php │ └── ItemTest.php ├── gateway/ │ └── CallbackTest.php └── order/ └── PurchaseTest.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /vendor composer.lock ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Amsgames, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ ITwrx fork of LARAVEL SHOP (minor changes for Laravel 5.2 Compatibility) -------------------------------- [![Latest Stable Version](https://poser.pugx.org/amsgames/laravel-shop/v/stable)](https://packagist.org/packages/amsgames/laravel-shop) [![Total Downloads](https://poser.pugx.org/amsgames/laravel-shop/downloads)](https://packagist.org/packages/amsgames/laravel-shop) [![Latest Unstable Version](https://poser.pugx.org/amsgames/laravel-shop/v/unstable)](https://packagist.org/packages/amsgames/laravel-shop) [![License](https://poser.pugx.org/amsgames/laravel-shop/license)](https://packagist.org/packages/amsgames/laravel-shop) Laravel Shop is flexible way to add shop functionality to **Laravel 5.2**. Aimed to be the e-commerce solution for artisans. Laravel shop adds shopping cart, orders and payments to your new or existing project; letting you transform any model into a shoppable item. **Supports** ![PayPal](http://kamleshyadav.com/demo_ky/eventmanagementsystem/assets/front/images/paypal.png) ![Omnipay](http://s18.postimg.org/g68f3fs09/omnipay.jpg) ## Contents - [Scope](#scope) - [Installation](#installation) - [Configuration](#configuration) - [Database Setup](#database-setup) - [Models Setup](#models) - [Item](#item) - [Cart](#cart) - [Order](#order) - [Transaction](#transaction) - [User](#user) - [Existing Model Conversion](#existing-model-conversion) - [Dump Autoload](#dump-autoload) - [Payment Gateways](#payment-gateways) - [PayPal](#paypal) - [Omnipay](#omnipay) - [Usage](#usage) - [Shop](#shop) - [Purchase Flow](#purchase-flow) - [Payment Gateway](#payment-gateway) - [Checkout](#checkout) - [Order placement](#exceptions) - [Payments](#payments) - [Exceptions](#order-placement) - [Shopping Cart](#shopping-cart) - [Adding Items](#adding-items) - [Removing Items](#removing-items) - [Placing Order](#placing-order) - [Cart Methods](#cart-methods) - [Displaying](#removing-items) - [Item](#item-1) - [Order](#order-1) - [Placing Transactions](#placing-transactions) - [Order Methods](#order-methods) - [Events](#events) - [Handler Example](#event-handler-example) - [Payment Gateway Development](#payment-gateway-development) - [Transaction](#transaction-1) - [Callbacks](#callbacks) - [Exceptions](#exception) - [License](#license) - [Additional Information](#additional-information) - [Change Log](#change-log) ## Scope Current version includes: - Shop Items (transforms existing models into shoppable items that can be added to cart and orders) - Cart - Orders - Transactions - Payment gateways support - PayPal - Events On the horizon: - Guest user cart - Shipping orders - Coupons - Product and variations solution - Backend dashboard - Frontend templates ## Installation With composer ```bash composer require amsgames/laravel-shop ``` Or add ```json "amsgames/laravel-shop": "0.2.*" ``` to your composer.json. Then run `composer install` or `composer update`. Then in your `config/app.php` add ```php Amsgames\LaravelShop\LaravelShopProvider::class, ``` in the `providers` array. Then add ```php 'Shop' => Amsgames\LaravelShop\LaravelShopFacade::class, ``` in the `aliases` array. ## Configuration Set the configuration values in the `config/auth.php` file. This package will use them to refer to the user table and model. Publish the configuration for this package to further customize table names, model namespaces, currencies and other values. Run the following command: ```bash php artisan vendor:publish ``` A `shop.php` file will be created in your app/config directory. ### Database Setup Generate package migration file: ```bash php artisan laravel-shop:migration ``` The command below will generate a new migration file with database commands to create the cart and item tables. The file will be located in `database/migrations`. Add additional fields if needed to fill your software needs. The command will also create a database seeder to fill shop catalog of status and types. Create schema in database: ```bash php artisan migrate ``` Add the seeder to `database/seeds/DatabaseSeeder.php`: ```php class DatabaseSeeder extends Seeder { public function run() { Model::unguard(); $this->call('LaravelShopSeeder'); Model::reguard(); } } ``` Run seeder (do `composer dump-autoload first`): ```bash php artisan db:seed ``` ### Models The following models must be created for the shop to function, these models can be customizable to fir your needs. #### Item Create a Item model: ```bash php artisan make:model Item ``` This will create the model file `app/Item.php`, edit it and make it look like (take in consideration your app's namespace): ```php string('sku')->after('id'); $table->decimal('price', 20, 2)->after('sku'); $table->index('sku'); $table->index('price'); }); } public function down() { // Restore type field Schema::table('MyCustomProduct', function($table) { $table->dropColumn('sku'); $table->dropColumn('price'); }); } } ``` Run the migration: ```bash php artisan migrate ``` ##### Item name By default, Laravel Shop will look for the `name` attribute to define the item's name. If your exisintg model has a different attribute assigned for the name, simply define it in a property within your model: ```php [ 'paypal' => Amsgames\LaravelShopGatewayPaypal\GatewayPayPal::class, 'paypalExpress' => Amsgames\LaravelShopGatewayPaypal\GatewayPayPalExpress::class, ], ``` #### PayPal Laravel Shop comes with PayPal support out of the box. You can use PayPal's `Direct Credit Card` or `PayPal Express` payments. To configure PayPal and know how to use the gateways, please visit the [PayPal Gateway Package](https://github.com/amsgames/laravel-shop-gateway-paypal) page. #### Omnipay Install [Omnipay Gateway](https://github.com/amostajo/laravel-shop-gateway-omnipay) to enable other payment services like 2Checkout, Authorize.net, Stripe and to name a few. You might need to get some extra understanding about how [Omnipay](https://github.com/thephpleague/omnipay) works. ## Usage ### Shop Shop methods to consider: Format prices or other values to the price format specified in config: ```php $formatted = Shop::format(9.99); // i.e. this will return $9.99 or the format set in the config file. ``` #### Purchase Flow With Laravel Shop you can customize things to work your way, although we recommend standarize your purchase or checkout flow as following (will explain how to use the shop methods below): ![Purchase Flow](http://s12.postimg.org/zfmsz6krh/laravelshop_New_Page.png) * (Step 1) - User views his cart. * (Step 2) - Continues into selecting the gateway to use. * (Step 3) - Continues into feeding the gateway selected with required information. * (Step 4) - Checkouts cart and reviews cart before placing order. * (Step 5) - Places order. #### Payment Gateway Before any shop method is called, a payment gateway must be set: ```php // Select the gateway to use Shop::setGateway('paypal'); echo Shop::getGateway(); // echos: paypal ``` You can access the gateway class object as well: ```php $gateway = Shop::gateway(); echo $gateway; // echos: [{"id":"paypal"}] ``` #### Checkout Once a payment gateway has been selected, you can call cart to checkout like this: ```php // Checkout current users' cart $success = Shop::checkout(); // Checkout q specific cart $success = Shop::checkout($cart); ``` This will call the `onCheckout` function in the payment gateway and perform validations. This method will return a bool flag indication if operation was successful. #### Order Placement Once a payment gateway has been selected and user has checkout, you can call order placement like: ```php // Places order based on current users' cart $order = Shop::placeOrder(); // Places order based on a specific cart $order = Shop::placeOrder($cart); ``` **NOTE:** `placeOrder()` will create an order, relate all the items in cart to the order and empty the cart. The `Order` model doen't include methods to add or remove items, any modification to the cart must be done before the order is placed. Be aware of this when designing your checkout flow. This will call the `onCharge` function in the payment gateway and charge the user with the orders' total amount. `placeOrder()` will return an `Order` model with which you can verify the status and retrieve the transactions generated by the gateway. #### Payments Payments are handled gateways, this package comes with PayPal out of the box. You can use PayPal's `Direct Credit Card` or `PayPal Express` payments. To configure PayPal and know how to use its gateways, please visit the [PayPal Gateway Package](https://github.com/amsgames/laravel-shop-gateway-paypal) page. #### Exceptions If checkout or placeOrder had errores, you can call and see the exception related: ```php // On checkout if (!Shop::checkout()) { $exception = Shop::exception(); echo $exception->getMessage(); // echos: error } // Placing order $order = Shop::placeOrder(); if ($order->hasFailed) { $exception = Shop::exception(); echo $exception->getMessage(); // echos: error } ``` Critical exceptions are stored in laravel's log. ### Shopping Cart Carts are created per user in the database, this means that a user can have his cart saved when logged out and when he switches to a different device. Let's start by calling or creating the current user's cart: ```php // From cart $cart = Cart::current(); // Once a cart has been created, it can be accessed from user $user->cart; ``` Note: Laravel Shop doen not support guest at the moment. Get the cart of another user: ```php $userId = 1; $cart = Cart::findByUser($userId); ``` #### Adding Items Lest add one item of our test and existing model `MyCustomProduct`: ```php $cart = Cart::current()->add(MyCustomProduct::find(1)); ``` By default the add method will set a quantity of 1. Instead lets add 3 `MyCustomProduct`; ```php $cart = Cart::current(); $cart->add(MyCustomProduct::find(1), 3); ``` Only one item will be created per sku in the cart. If an item of the same `sku` is added, just on item will remain but its quantity will increase: ```php $product = MyCustomProduct::find(1); // Adds 1 $cart->add($product); // Adds 3 $cart->add($product, 3); // Adds 2 $cart->add($product, 2); echo $cart->count; // echos: 6 $second_product = MyCustomProduct::findBySKU('TEST'); // Adds 2 of product 'TEST' $cart->add($second_product, 2); // Count based on quantity echo $cart->count; // echos: 8 // Count based on products echo $cart->items->count(); // echos: 2 ``` We can reset the quantity of an item to a given value: ```php // Add 3 $cart->add($product, 3); echo $cart->count; // echos: 3 // Reset quantity to 4 $cart->add($product, 4, $forceReset = true); echo $cart->count; // echos: 4 ``` #### Adding Unexistent Model Items You can add unexistent items by inserting them as arrays, each array must contain `sku` and `price` keys: ```php // Adds unexistent item model PROD0001 $cart->add(['sku' => 'PROD0001', 'price' => 9.99]); // Add 4 items of SKU PROD0002 $cart->add(['sku' => 'PROD0002', 'price' => 29.99], 4); ``` #### Removing Items Lest remove our test and existing model `MyCustomProduct` from cart: ```php $product = MyCustomProduct::find(1); // Remove the product from cart $cart = Cart::current()->remove($product); ``` The example below will remove the item completly, but it is possible to only remove a certain quantity from the cart: ```php // Removes only 2 from quantity // If the quantity is greater than 2, then 1 item will remain in cart $cart->remove($product, 2); ``` Arrays can be used to remove unexistent model items: ```php // Removes by sku $cart->remove(['sku' => 'PROD0001']); ``` To empty cart: ```php $cart->clear(); ``` These methods can be chained: ```php $cart->add($product, 5) ->add($product2) ->remove($product3) ->clear(); ``` #### Cart Methods ```php // Checks if cart has item with SKU "PROD0001" $success = $cart->hasItem('PROD0001'); ``` #### Placing Order You can place an order directly from the cart without calling the `Shop` class, although this will only create the order record in the database and no payments will be processed. Same ad when using `Shop`, the cart will be empty after the order is placed. ```php // This will create the order and set it to the status in configuration $order = $cart->placeOrder(); ``` Status can be forced in creation as well: ```php $order = $cart->placeOrder('completed'); ``` #### Displaying Hew is an example of how to display the cart in a blade template: Items count in cart: ```html Items in cart: {{ $cart->count }} ``` Items in cart: ```html @foreach ($cart->items as $item) { @endforeach
{{ $item->sku }} {{ $item->displayName }} {{ $item->price }} {{ $item->displayPrice }} {{ $item->tax }} {{ $item->quantity }} {{ $item->shipping }}
``` Cart amount calculations: ```html
Subtotal: {{ $cart->displayTotalPrice }} {{ $cart->totalPrice }}
Shipping: {{ $cart->displayTotalShipping }}
Tax: {{ $cart->displayTotalTax }}
Total: {{ $cart->displayTotal }} {{ $cart->total }}
``` ### Item Models or arrays inserted in a cart or order are converted into SHOP ITEMS, model `Item` is used instead within the shop. Model objects can be retrieved from a SHOP ITEM: ```php // Lets assume that the first Cart item is MyCustomProduct. $item = $cart->items[0]; // Check if item has model if ($item->hasObject) { $myproduct = $item->object; } ``` `$item->object` is `MyCustomProduct` model already loaded, we can access its properties and methods directly, like: ```php // Assuming MyCustomProduct has a types relationship. $item->object->types; // Assuming MyCustomProduct has myAttribute attribute. $item->object->myAttribute; ``` The following shop methods apply to model `Item` or exiting models that uses `ShopItemTrait`: ```php $item = Item::findBySKU('PROD0001'); $item = MyCustomProduct::findBySKU('PROD0002'); // Quering $item = Item::whereSKU('PROD0001')->where('price', '>', 0)->get(); ``` ### Order Find a specific order number: ```php $order = Order::find(1); ``` Find orders form user: ```php // Get orders from specific user ID. $orders = Order::findByUser($userId); // Get orders from specific user ID and status. $canceled_orders = Order::findByUser($userId, 'canceled'); ``` #### Placing Transactions You can place a transaction directly from the order without calling the `Shop` class, although this will only create the transaction record in the database and no payments will be processed. ```php // This will create the order and set it to the status in configuration $transaction = $order->placeTransaction( $gateway = 'my_gateway', $transactionId = 55555, $detail = 'Custom transaction 55555' ); ``` #### Order Methods ```php $completed = $order->isCompleted // Checks if order is in a specific status. $success = $order->is('completed'); // Quering // Get orders from specific user ID. $orders = Order::whereUser($userId)->get(); // Get orders from specific user ID and status. $completed_orders = Order::whereUser($userId) ->whereStatus('completed') ->get(); ``` #### Order Status Codes Status codes out of the box: - `in_creation` — Order status in creation. Or use `$order->isInCreation`. - `pending` — Pending for payment. Or use `$order->isPending`. - `in_process` — In process of shipping. In process of revision. Or use `$order->isInProcess`. - `completed` — When payment has been made and items were delivered to client. Or use `$order->isCompleted`. - `failed` — When payment failed. Or use `$order->hasFailed`. - `canceled` — When an order has been canceled by the user. Or use `$order->isCanceled`. You can use your own custom status codes. Simply add them manually to the `order_status` database table or create a custom seeder like this: ```php class MyCustomStatusSeeder extends Seeder { public function run() { DB::table('order_status')->insert([ [ 'code' => 'my_status', 'name' => 'My Status', 'description' => 'Custom status used in my shop.', ], ]); } } ``` Then use it like: ```php $myStatusCode = 'my_status'; if ($order->is($myStatusCode)) { echo 'My custom status work!'; } ``` ### Events Laravel Shop follows [Laravel 5 guidelines](http://laravel.com/docs/5.1/events) to fire events, create your handlers and listeners like you would normally do to use them. | Event | Description | Data passed | | ------------- | ------------- | ------------- | | Cart checkout | Event fired after a shop has checkout a cart. | `id` - Cart Id `success` - Checkout result (boolean) | | Order placed | Event fired when an order has been placed. | `id` - Order Id | | Order completed | Event fired when an order has been completed. | `id` - Order Id | | Order status changed | Event fired when an order's status has been changed. | `id` - Order Id `statusCode` - New status `previousStatusCode` - Prev status | Here are the events references: | Event | Reference | | ------------- | ------------- | | Cart checkout | `Amsgames\LaravelShop\Events\CartCheckout` | | Order placed | `Amsgames\LaravelShop\Events\OrderPlaced` | | Order completed | `Amsgames\LaravelShop\Events\OrderCompleted` | | Order status changed | `Amsgames\LaravelShop\Events\OrderStatusChanged` | #### Event Handler Example An example of how to use an event in a handler: ```php id; // Get order model object $order = Order::find($event->id); // My code here... } } ``` Remember to register your handles and listeners at the Event Provider: ```php 'Amsgames\LaravelShop\Events\OrderCompleted' => [ 'App\Handlers\Events\NotifyPurchase', ], ``` ## Payment Gateway Development Laravel Shop has been developed for customization in mind. Allowing the community to expand its capabilities. Missing payment gateways can be easily developed as external packages and then be configured in the config file. Make this proyect a required dependency of your package or laravel's setup and simply extend from Laravel Shop core class, here a PayPal example: ```php [ 'paypal' => Vendor\Package\GatewayPaypal::class, ], ``` And use it like: ```php Shop::setGateway('paypal'); ``` ### Transaction To properly generate the transaction there are 3 properties you must consider on setting during `onCharge`: ```php public function onCharge($order) { // The transaction id generated by the provider i.e. $this->transactionId = $paypal->transactionId; // Custom detail of 1024 chars. $this->detail = 'Paypal: success'; // Order status after method call. $this->statusCode = 'in_process'; return true; } ``` - `transactionId` — Provider's transaction ID, will help identify a transaction. - `detail` — Custom description for the transaction. - `statusCode` — Order status code with which to update the order after onCharge has executed. By default is 'completed'. ### Callbacks Laravel Shop supports gateways that require callbacks. For this, you will need to add 2 additional functions to your gateway: ```php statusCode = 'pending'; // Sets provider with the callback for successful transactions. $provider->setSuccessCallback( $this->callbackSuccess ); // Sets provider with the callback for failed transactions. $provider->setFailCallback( $this->callbackFail ); return true; } /** * Called on callback. * * @param Order $order Order. * @param mixed $data Request input from callback. * * @return bool */ public function onCallbackSuccess($order, $data = null) { $this->statusCode = 'completed'; $this->detail = 'successful callback'; $this->transactionId = $data->transactionId; // My code... } /** * Called on callback. * * @param Order $order Order. * @param mixed $data Request input from callback. * * @return bool */ public function onCallbackFail($order, $data = null) { $this->detail = 'failed callback'; // My code... } } ``` In the example above, `onCharge` instead of creating a completed transaction, it is creating a pending transaction and indicating the provider to which urls to call back with the payment results. The methods `onCallbackSuccess` and `onCallbackFail` are called by `Shop` when the provider calls back with its reponse, the proper function will be called depending on the callback url used by the provider. The method `onCallbackSuccess` will create a new transaction for the order it ends. - `callbackSuccess` — Successful url callback to be used by the provider. - `callbackFail` — i.e. Failure url callback to be used by the provider. - `token` — i.e. Validation token. ### Exceptions Laravel Shop provides several exceptions you can use to report errors. For `onCheckout`: - `CheckoutException` - `GatewayException` - `StoreException` — This exception will be logged in laravel, so use it only for fatal errores. For `onChange`, `onCallbackSuccess` and `onCallbackFail`: - `GatewayException` - `StoreException` — This exception will be logged in laravel, so use it only for fatal errores. **NOTE**: Laravel Shop will not catch any other exception. If a normal `Exception` or any other exceptions is thrown, it will break the method as it normally would, this will affect your checkout flow like in example when you want to get the order from `placeOrder()`. ### Examples You can see the [PayPal gateways](https://github.com/amsgames/laravel-shop-gateway-paypal/tree/master/src) we made as examples. - [GatewayPayPal](https://github.com/amsgames/laravel-shop-gateway-paypal/blob/master/src/GatewayPayPal.php) - Processes credit cards, uses `onCheckout` and `onCharge`. - [GatewayPayPalExpress](https://github.com/amsgames/laravel-shop-gateway-paypal/blob/master/src/GatewayPayPalExpress.php) - Processes callbacks, uses `onCallbackSuccess` and `onCharge`. ## License Laravel Shop is free software distributed under the terms of the MIT license. ## Additional Information This package's architecture and design was inpired by the **Zizaco/entrust** package, we'll like to thank their contributors for their awesome woek. ## Change Log * [v0.2.8](https://github.com/amsgames/laravel-shop/releases/tag/v0.2.8) ================================================ FILE: composer.json ================================================ { "name": "ITwrx/laravel-shop", "description": "Package set to provide shop or e-commerce functionality (such as CART, ORDERS, TRANSACTIONS and ITEMS) to Laravel for customizable builds.", "license": "MIT", "keywords": ["shop","laravel","cart","orders","transactions","paypal","e-commerce","shopping cart","ecommerce","shopping"], "authors": [ { "name": "Amsgames, LLC", "email": "support@amsgames.com" }, { "name": "Alejandro Mostajo", "email": "amostajo@gmail.com" } ], "require": { "php": ">=5.5.9", "illuminate/console": "~5.0", "illuminate/support": "~5.0", "ITwrx/laravel-shop-gateway-paypal": "1.0.*" }, "autoload": { "classmap": [ "src/Commands" ], "psr-4": { "Amsgames\\LaravelShop\\": "src" } }, "minimum-stability": "dev", "extra": { "laravel": { "providers": [ "ITwrx\\LaravelShop\\LaravelShopProvider" ], "aliases": { "Shop": "ITwrx\\LaravelShop\\LaravelShopFacade" } } } } ================================================ FILE: composer.lock.bk ================================================ { "_readme": [ "This file locks the dependencies of your project to a known state", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], "hash": "fff0c5ff15d79f87bda8c01f92af4404", "packages": [ { "name": "ITwrx/laravel-shop-gateway-paypal", "version": "1.0.x-dev", "source": { "type": "git", "url": "https://github.com/amsgames/laravel-shop-gateway-paypal.git", "reference": "c0ba041bda3fdcc696e4a01278647f386e9d8715" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/amsgames/laravel-shop-gateway-paypal/zipball/c0ba041bda3fdcc696e4a01278647f386e9d8715", "reference": "c0ba041bda3fdcc696e4a01278647f386e9d8715", "shasum": "" }, "require": { "illuminate/console": "~5.0", "illuminate/support": "~5.0", "paypal/rest-api-sdk-php": "*", "php": ">=5.4.0" }, "require-dev": { "sami/sami": "dev-master" }, "type": "library", "autoload": { "psr-4": { "Amsgames\\LaravelShopGatewayPaypal\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Amsgames, LLC", "email": "support@amsgames.com" }, { "name": "Alejandro Mostajo", "email": "amostajo@gmail.com" } ], "description": "PayPal gateway for Laravel Shop package.", "keywords": [ "gateway", "laravel shop", "laravel-shop", "paypal" ], "time": "2015-09-19 04:10:42" }, { "name": "danielstjules/stringy", "version": "1.x-dev", "source": { "type": "git", "url": "https://github.com/danielstjules/Stringy.git", "reference": "4749c205db47ee5b32e8d1adf6d9aff8db6caf3b" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/danielstjules/Stringy/zipball/4749c205db47ee5b32e8d1adf6d9aff8db6caf3b", "reference": "4749c205db47ee5b32e8d1adf6d9aff8db6caf3b", "shasum": "" }, "require": { "ext-mbstring": "*", "php": ">=5.3.0" }, "require-dev": { "phpunit/phpunit": "~4.0" }, "type": "library", "autoload": { "psr-4": { "Stringy\\": "src/" }, "files": [ "src/Create.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Daniel St. Jules", "email": "danielst.jules@gmail.com", "homepage": "http://www.danielstjules.com" } ], "description": "A string manipulation library with multibyte support", "homepage": "https://github.com/danielstjules/Stringy", "keywords": [ "UTF", "helpers", "manipulation", "methods", "multibyte", "string", "utf-8", "utility", "utils" ], "time": "2015-07-23 00:54:12" }, { "name": "doctrine/inflector", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/doctrine/inflector.git", "reference": "3a422c73f7bc556d39571f436b61fd58ccae0eb0" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/doctrine/inflector/zipball/3a422c73f7bc556d39571f436b61fd58ccae0eb0", "reference": "3a422c73f7bc556d39571f436b61fd58ccae0eb0", "shasum": "" }, "require": { "php": ">=5.3.2" }, "require-dev": { "phpunit/phpunit": "4.*" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } }, "autoload": { "psr-0": { "Doctrine\\Common\\Inflector\\": "lib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Roman Borschel", "email": "roman@code-factory.org" }, { "name": "Benjamin Eberlei", "email": "kontakt@beberlei.de" }, { "name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com" }, { "name": "Jonathan Wage", "email": "jonwage@gmail.com" }, { "name": "Johannes Schmitt", "email": "schmittjoh@gmail.com" } ], "description": "Common String Manipulations with regard to casing and singular/plural rules.", "homepage": "http://www.doctrine-project.org", "keywords": [ "inflection", "pluralize", "singularize", "string" ], "time": "2015-09-17 13:29:15" }, { "name": "illuminate/console", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/illuminate/console.git", "reference": "5f532c52100e9aa9c7ee66f4581534093ac44975" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/illuminate/console/zipball/5f532c52100e9aa9c7ee66f4581534093ac44975", "reference": "5f532c52100e9aa9c7ee66f4581534093ac44975", "shasum": "" }, "require": { "illuminate/contracts": "5.2.*", "illuminate/support": "5.2.*", "nesbot/carbon": "~1.20", "php": ">=5.5.9", "symfony/console": "3.0.*" }, "suggest": { "guzzlehttp/guzzle": "Required to use the thenPing method on schedules (~6.0).", "mtdowling/cron-expression": "Required to use scheduling component (~1.0).", "symfony/process": "Required to use scheduling component (3.0.*)." }, "type": "library", "extra": { "branch-alias": { "dev-master": "5.2-dev" } }, "autoload": { "psr-4": { "Illuminate\\Console\\": "" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Taylor Otwell", "email": "taylorotwell@gmail.com" } ], "description": "The Illuminate Console package.", "homepage": "http://laravel.com", "time": "2015-09-17 22:37:41" }, { "name": "illuminate/contracts", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/illuminate/contracts.git", "reference": "854d3a6021f3dcda1f5624d0e33ebf2c2ab6e3e5" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/illuminate/contracts/zipball/854d3a6021f3dcda1f5624d0e33ebf2c2ab6e3e5", "reference": "854d3a6021f3dcda1f5624d0e33ebf2c2ab6e3e5", "shasum": "" }, "require": { "php": ">=5.5.9" }, "type": "library", "extra": { "branch-alias": { "dev-master": "5.2-dev" } }, "autoload": { "psr-4": { "Illuminate\\Contracts\\": "" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Taylor Otwell", "email": "taylorotwell@gmail.com" } ], "description": "The Illuminate Contracts package.", "homepage": "http://laravel.com", "time": "2015-09-17 15:05:48" }, { "name": "illuminate/support", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/illuminate/support.git", "reference": "a868dba60dd510d5872bd6b464c2d7e3e5038ba6" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/illuminate/support/zipball/a868dba60dd510d5872bd6b464c2d7e3e5038ba6", "reference": "a868dba60dd510d5872bd6b464c2d7e3e5038ba6", "shasum": "" }, "require": { "danielstjules/stringy": "~1.8", "doctrine/inflector": "~1.0", "ext-mbstring": "*", "illuminate/contracts": "5.2.*", "php": ">=5.5.9" }, "suggest": { "jeremeamia/superclosure": "Required to be able to serialize closures (~2.0).", "symfony/var-dumper": "Required to use the dd function (3.0.*)." }, "type": "library", "extra": { "branch-alias": { "dev-master": "5.2-dev" } }, "autoload": { "psr-4": { "Illuminate\\Support\\": "" }, "files": [ "helpers.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Taylor Otwell", "email": "taylorotwell@gmail.com" } ], "description": "The Illuminate Support package.", "homepage": "http://laravel.com", "time": "2015-09-15 13:49:17" }, { "name": "nesbot/carbon", "version": "1.20.0", "source": { "type": "git", "url": "https://github.com/briannesbitt/Carbon.git", "reference": "bfd3eaba109c9a2405c92174c8e17f20c2b9caf3" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/bfd3eaba109c9a2405c92174c8e17f20c2b9caf3", "reference": "bfd3eaba109c9a2405c92174c8e17f20c2b9caf3", "shasum": "" }, "require": { "php": ">=5.3.0", "symfony/translation": "~2.6|~3.0" }, "require-dev": { "phpunit/phpunit": "~4.0" }, "type": "library", "autoload": { "psr-0": { "Carbon": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Brian Nesbitt", "email": "brian@nesbot.com", "homepage": "http://nesbot.com" } ], "description": "A simple API extension for DateTime.", "homepage": "http://carbon.nesbot.com", "keywords": [ "date", "datetime", "time" ], "time": "2015-06-25 04:19:39" }, { "name": "paypal/rest-api-sdk-php", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/paypal/PayPal-PHP-SDK.git", "reference": "fd6801cda18fc1ae29ef913370c1902679410dab" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/paypal/PayPal-PHP-SDK/zipball/fd6801cda18fc1ae29ef913370c1902679410dab", "reference": "fd6801cda18fc1ae29ef913370c1902679410dab", "shasum": "" }, "require": { "ext-curl": "*", "ext-json": "*", "php": ">=5.3.0" }, "require-dev": { "phpunit/phpunit": "3.7.*" }, "type": "library", "autoload": { "psr-0": { "PayPal": "lib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "Apache2" ], "authors": [ { "name": "PayPal", "homepage": "https://github.com/paypal/rest-api-sdk-php/contributors" } ], "description": "PayPal's PHP SDK for REST APIs", "homepage": "http://paypal.github.io/PayPal-PHP-SDK/", "keywords": [ "payments", "paypal", "rest", "sdk" ], "time": "2015-08-17 19:32:36" }, { "name": "symfony/console", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/symfony/Console.git", "reference": "c32d1e7ffe11b7329d72c94c5970ab4001c9f858" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/Console/zipball/c32d1e7ffe11b7329d72c94c5970ab4001c9f858", "reference": "c32d1e7ffe11b7329d72c94c5970ab4001c9f858", "shasum": "" }, "require": { "php": ">=5.5.9" }, "require-dev": { "psr/log": "~1.0", "symfony/event-dispatcher": "~2.8|~3.0", "symfony/phpunit-bridge": "~2.8|~3.0", "symfony/process": "~2.8|~3.0" }, "suggest": { "psr/log": "For using the console logger", "symfony/event-dispatcher": "", "symfony/process": "" }, "type": "library", "extra": { "branch-alias": { "dev-master": "3.0-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Console\\": "" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Console Component", "homepage": "https://symfony.com", "time": "2015-09-14 14:15:24" }, { "name": "symfony/translation", "version": "dev-master", "source": { "type": "git", "url": "https://github.com/symfony/Translation.git", "reference": "a4aa6e450b1c2a0545fa9724bc943a15ac0e0798" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/symfony/Translation/zipball/a4aa6e450b1c2a0545fa9724bc943a15ac0e0798", "reference": "a4aa6e450b1c2a0545fa9724bc943a15ac0e0798", "shasum": "" }, "require": { "php": ">=5.5.9" }, "conflict": { "symfony/config": "<2.8" }, "require-dev": { "psr/log": "~1.0", "symfony/config": "~2.8|~3.0", "symfony/intl": "~2.8|~3.0", "symfony/phpunit-bridge": "~2.8|~3.0", "symfony/yaml": "~2.8|~3.0" }, "suggest": { "psr/log": "To use logging capability in translator", "symfony/config": "", "symfony/yaml": "" }, "type": "library", "extra": { "branch-alias": { "dev-master": "3.0-dev" } }, "autoload": { "psr-4": { "Symfony\\Component\\Translation\\": "" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com" }, { "name": "Symfony Community", "homepage": "https://symfony.com/contributors" } ], "description": "Symfony Translation Component", "homepage": "https://symfony.com", "time": "2015-09-18 10:59:20" } ], "packages-dev": [], "aliases": [], "minimum-stability": "dev", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, "platform": { "php": ">=5.5.9" }, "platform-dev": [] } ================================================ FILE: src/.gitkeep ================================================ ================================================ FILE: src/Commands/MigrationCommand.php ================================================ laravel->view->addNamespace('laravel-shop', substr(__DIR__, 0, -8).'views'); $cartTable = Config::get('shop.cart_table'); $itemTable = Config::get('shop.item_table'); $couponTable = Config::get('shop.coupon_table'); $orderStatusTable = Config::get('shop.order_status_table'); $orderTable = Config::get('shop.order_table'); $transactionTable = Config::get('shop.transaction_table'); // Migrations $this->line(''); $this->info( "Tables: $cartTable, $itemTable" ); $message = "A migration that creates '$cartTable', '$itemTable', '$orderTable'". " tables will be created in database/migrations directory"; $this->comment($message); $this->line(''); if ($this->confirm('Proceed with the migration creation? [Yes|no]', 'Yes')) { $this->line(''); $this->info('Creating migration...'); if ($this->createMigration(compact( 'cartTable', 'itemTable', 'couponTable', 'orderStatusTable', 'orderTable', 'transactionTable' )) ) { $this->info('Migration successfully created!'); } else { $this->error( "Couldn't create migration.\n Check the write permissions". " within the database/migrations directory." ); } } // Seeder $this->line(''); $this->info( "Table seeders: $orderStatusTable" ); $message = "A seeder that seeds '$orderStatusTable' table(s) with data. Will be created in database/seeds directory"; $this->comment($message); $this->line(''); if ($this->confirm('Proceed with the seeder creation? [Yes|no]', 'Yes')) { $this->line(''); $this->info('Creating seeder...'); if ($this->createSeeder(compact( 'cartTable', 'itemTable', 'couponTable', 'orderStatusTable', 'orderTable', 'transactionTable' )) ) { $this->info('Seeder successfully created!'); } else { $this->error( "Couldn't create seeder.\n Check the write permissions". " within the database/seeds directory." ); } } } /** * Create the migration. * * @param array $data Data with table names. * * @return bool */ protected function createMigration($data) { $migrationFile = base_path('/database/migrations') . '/' . date('Y_m_d_His') . '_shop_setup_tables.php'; $usersTable = Config::get('auth.table'); $userModel = Config::get('auth.model'); $userKeyName = (new $userModel())->getKeyName(); $data = array_merge($data, compact('usersTable', 'userKeyName')); $output = $this->laravel->view->make('laravel-shop::generators.migration')->with($data)->render(); if (!file_exists($migrationFile) && $fs = fopen($migrationFile, 'x')) { fwrite($fs, $output); fclose($fs); return true; } return false; } /** * Create the seeder. * * @param array $data Data with table names. * * @return bool */ protected function createSeeder($data) { $seederFile = base_path('/database/seeds') . '/LaravelShopSeeder.php'; $output = $this->laravel->view->make('laravel-shop::generators.seeder')->with($data)->render(); if (!file_exists($seederFile) && $fs = fopen($seederFile, 'x')) { fwrite($fs, $output); fclose($fs); return true; } return false; } } ================================================ FILE: src/Config/config.php ================================================ 'Laravel Shop', /* |-------------------------------------------------------------------------- | Cart Model |-------------------------------------------------------------------------- | | This is the Cart model used by LaravelShop to create correct relations. | Update the model if it is in a different namespace. | */ 'cart' => 'App\Cart', /* |-------------------------------------------------------------------------- | Cart Database Table |-------------------------------------------------------------------------- | | This is the table used by LaravelShop to save cart data to the database. | */ 'cart_table' => 'cart', /* |-------------------------------------------------------------------------- | Order Model |-------------------------------------------------------------------------- | | This is the Order model used by LaravelShop to create correct relations. | Update the model if it is in a different namespace. | */ 'order' => 'App\Order', /* |-------------------------------------------------------------------------- | Order Database Table |-------------------------------------------------------------------------- | | This is the table used by LaravelShop to save order data to the database. | */ 'order_table' => 'orders', /* |-------------------------------------------------------------------------- | Order Status Database Table |-------------------------------------------------------------------------- | | This is the table used by LaravelShop to save order status data to the database. | */ 'order_status_table' => 'order_status', /* |-------------------------------------------------------------------------- | Item Model |-------------------------------------------------------------------------- | | This is the Item model used by LaravelShop to create correct relations. | Update the model if it is in a different namespace. | */ 'item' => 'App\Item', /* |-------------------------------------------------------------------------- | Item Database Table |-------------------------------------------------------------------------- | | This is the table used by LaravelShop to save cart data to the database. | */ 'item_table' => 'items', /* |-------------------------------------------------------------------------- | Transaction Model |-------------------------------------------------------------------------- | | This is the Transaction model used by LaravelShop to create correct relations. | Update the model if it is in a different namespace. | */ 'transaction' => 'App\Transaction', /* |-------------------------------------------------------------------------- | Transaction Database Table |-------------------------------------------------------------------------- | | This is the table used by LaravelShop to save cart data to the database. | */ 'transaction_table' => 'transactions', /* |-------------------------------------------------------------------------- | Coupon Model |-------------------------------------------------------------------------- | | This is the Coupon model used by LaravelShop to create correct relations. | Update the model if it is in a different namespace. | */ 'coupon' => 'App\Coupon', /* |-------------------------------------------------------------------------- | Coupon Database Table |-------------------------------------------------------------------------- | | This is the table used by LaravelShop to save order data to the database. | */ 'coupon_table' => 'coupons', /* |-------------------------------------------------------------------------- | Shop currency code |-------------------------------------------------------------------------- | | Currency to use within shop. | */ 'currency' => 'USD', /* |-------------------------------------------------------------------------- | Shop currency symbol |-------------------------------------------------------------------------- | | Currency symbol to use within shop. | */ 'currency_symbol' => '$', /* |-------------------------------------------------------------------------- | Shop tax |-------------------------------------------------------------------------- | | Tax percentage to apply to all items. Value must be in decimal. | | Tax to apply: 8% | Tax config value: 0.08 | */ 'tax' => 0.0, /* |-------------------------------------------------------------------------- | Format with which to display prices across the store. |-------------------------------------------------------------------------- | | :symbol = Currency symbol. i.e. "$" | :price = Price. i.e. "0.99" | :currency = Currency code. i.e. "USD" | | Example format: ':symbol:price (:currency)' | Example result: '$0.99 (USD)' | */ 'display_price_format' => ':symbol:price', /* |-------------------------------------------------------------------------- | Allow multiple coupons |-------------------------------------------------------------------------- | | Flag that indicates if user can apply more that one coupon to cart or orders. | */ 'allow_multiple_coupons' => true, /* |-------------------------------------------------------------------------- | Cache shop calculations |-------------------------------------------------------------------------- | | Caches shop calculations, such as item count, cart total amount and similar. | Cache is forgotten when adding or removing items. | If not cached, calculations will be done every time their attributes are called. | This configuration option exists if you don't wish to overload your cache. | */ 'cache_calculations' => true, /* |-------------------------------------------------------------------------- | Cache calculations minutes |-------------------------------------------------------------------------- | | Amount of minutes to cache calculations. | */ 'cache_calculations_minutes' => 15, /* |-------------------------------------------------------------------------- | Order status lock |-------------------------------------------------------------------------- | | Order status where the order will remain locked from modifications. | */ 'order_status_lock' => [], /* |-------------------------------------------------------------------------- | Order status placement |-------------------------------------------------------------------------- | | Status to set when the order is placed and created by the cart. | */ 'order_status_placement' => 'pending', /* |-------------------------------------------------------------------------- | Order status placement |-------------------------------------------------------------------------- | | Status that determines if an order has been established and if items were purchased. | */ 'order_status_purchase' => ['completed', 'in_process'], /* |-------------------------------------------------------------------------- | Payment Gateways |-------------------------------------------------------------------------- | | List of payment gateways. | */ 'gateways' => [ 'paypal' => Amsgames\LaravelShopGatewayPaypal\GatewayPayPal::class, 'paypalExpress' => Amsgames\LaravelShopGatewayPaypal\GatewayPayPalExpress::class, ], /* |-------------------------------------------------------------------------- | Gatewall payment callback |-------------------------------------------------------------------------- | | Which route to call for gateway callbacks. | */ 'callback_route' => 'shop.callback', /* |-------------------------------------------------------------------------- | Redirect route after callback |-------------------------------------------------------------------------- | | Which route to call after the callback has been processed. | */ 'callback_redirect_route' => '/', ]; ================================================ FILE: src/Contracts/PaymentGatewayInterface.php ================================================ id = $id; $this->transactionId = uniqid(); $this->token = uniqid(); } /** * Called on cart checkout. * * @param Order $order Order. */ public function onCheckout($cart) { } /** * Called by shop when payment gateway calls callback url. * Success result * * @param Order $order Order. * @param mixed $data Callback data. * * @return string */ public function onCallbackSuccess($order, $data = null) { } /** * Called by shop when payment gateway calls callback url. * Failed result * * @param Order $order Order. * @param mixed $data Callback data. * * @return string */ public function onCallbackFail($order, $data = null) { } /** * Sets callback urls * * @param Order $order Order. */ public function setCallbacks($order) { $this->callbackSuccess = route(config('shop.callback_route'), [ 'status' => 'success', 'id' => $order->id, 'token' => $this->token, ]); $this->callbackFail = route(config('shop.callback_route'), [ 'status' => 'fail', 'id' => $order->id, 'token' => $this->token, ]); } /** * Returns transaction token. * * @return mixed. */ public function getTransactionToken() { return $this->token; } /** * Returns the transaction ID generated by the gateway. * i.e. PayPal's transaction ID. * * @return mixed */ public function getTransactionId() { return $this->transactionId; } /** * Returns a 1024 length string with extra detail of transaction. * * @return string */ public function getTransactionDetail() { return $this->detail; } /** * Returns transaction status code. * * @return string */ public function getTransactionStatusCode() { return $this->statusCode; } /** * Convert the model instance to an array. * * @return array */ public function toArray() { return ['id' => $this->id]; } /** * Convert the model instance to JSON. * * @param int $options * @return string */ public function toJson($options = 0) { return json_encode($this->jsonSerialize(), $options); } /** * Convert the object into something JSON serializable. * * @return array */ public function jsonSerialize() { return $this->toArray(); } /** * Convert the model to its string representation. * * @return string */ public function __toString() { return $this->toJson(); } } ================================================ FILE: src/Events/CartCheckout.php ================================================ id = $id; $this->success = $success; } } ================================================ FILE: src/Events/OrderCompleted.php ================================================ id = $id; } } ================================================ FILE: src/Events/OrderPlaced.php ================================================ id = $id; } } ================================================ FILE: src/Events/OrderStatusChanged.php ================================================ id = $id; $this->statusCode = $statusCode; $this->previousStatusCode = $previousStatusCode; } } ================================================ FILE: src/Exceptions/CheckoutException.php ================================================ statusCode = 'pending'; $this->detail = 'pending response, token:' . $this->token; return parent::onCharge($order); } /** * Called on callback. * * @param Order $order Order. * @param mixed $data Request input from callback. * * @return bool */ public function onCallbackSuccess($order, $data = null) { $this->statusCode = 'completed'; $this->detail = 'success callback'; $this->didCallback = true; } /** * Called on callback. * * @param Order $order Order. * @param mixed $data Request input from callback. * * @return bool */ public function onCallbackFail($order, $data = null) { $this->statusCode = 'failed'; $this->detail = 'failed callback'; $this->didCallback = true; } /** * Returns successful callback URL * @return false */ public function getCallbackSuccess() { return $this->callbackSuccess; } /** * Returns fail callback URL * @return false */ public function getCallbackFail() { return $this->callbackFail; } /** * Returns successful callback URL * @return false */ public function getDidCallback() { return $this->didCallback; } } ================================================ FILE: src/Gateways/GatewayFail.php ================================================ transactionId = uniqid(); return true; } } ================================================ FILE: src/Http/Controllers/Controller.php ================================================ $request->get('order_id'), 'status' => $request->get('status'), 'shoptoken' => $request->get('shoptoken'), ], [ 'order_id' => 'required|exists:' . config('shop.order_table') . ',id', 'status' => 'required|in:success,fail', 'shoptoken' => 'required|exists:' . config('shop.transaction_table') . ',token,order_id,' . $request->get('order_id'), ] ); if ($validator->fails()) { abort(404); } $order = call_user_func(config('shop.order') . '::find', $request->get('order_id')); $transaction = $order->transactions()->where('token', $request->get('shoptoken'))->first(); Shop::callback($order, $transaction, $request->get('status'), $request->all()); $transaction->token = null; $transaction->save(); return redirect()->route(config('shop.callback_redirect_route'), ['orderId' => $order->id]); } } ================================================ FILE: src/LaravelShop.php ================================================ app = $app; static::$gatewayKey = $this->getGateway(); static::$exception = null; static::$gateway = static::instanceGateway(); } /** * Get the currently authenticated user or null. * * @return Illuminate\Auth\UserInterface|null */ public function user() { return $this->app->auth->user(); } /** * Checkout current user's cart. */ public static function setGateway($gatewayKey) { if (!array_key_exists($gatewayKey, Config::get('shop.gateways'))) throw new ShopException('Invalid gateway.'); static::$gatewayKey = $gatewayKey; static::$gateway = static::instanceGateway(); Session::push('shop.gateway', $gatewayKey); } /** * Checkout current user's cart. */ public static function getGateway() { $gateways = Session::get('shop.gateway'); return $gateways && count($gateways) > 0 ? $gateways[count($gateways) - 1] : null; } /** * Checkout current user's cart. * * @param object $cart For specific cart. * * @return bool */ public static function checkout($cart = null) { $success = true; try { if (empty(static::$gatewayKey)) { throw new ShopException('Payment gateway not selected.'); } if (empty($cart)) $cart = Auth::user()->cart; static::$gateway->onCheckout($cart); } catch (ShopException $e) { static::setException($e); $success = false; } catch (CheckoutException $e) { static::$exception = $e; $success = false; } catch (GatewayException $e) { static::$exception = $e; $success = false; } if ($cart) \event(new CartCheckout($cart->id, $success)); return $success; } /** * Returns placed order. * * @param object $cart For specific cart. * * @return object */ public static function placeOrder($cart = null) { try { if (empty(static::$gatewayKey)) throw new ShopException('Payment gateway not selected.'); if (empty($cart)) $cart = Auth::user()->cart; $order = $cart->placeOrder(); $statusCode = $order->statusCode; \event(new OrderPlaced($order->id)); static::$gateway->setCallbacks($order); if (static::$gateway->onCharge($order)) { $order->statusCode = static::$gateway->getTransactionStatusCode(); $order->save(); // Create transaction $order->placeTransaction( static::$gatewayKey, static::$gateway->getTransactionId(), static::$gateway->getTransactionDetail(), static::$gateway->getTransactionToken() ); // Fire event if ($order->isCompleted) \event(new OrderCompleted($order->id)); } else { $order->statusCode = 'failed'; $order->save(); } } catch (ShopException $e) { static::setException($e); if (isset($order)) { $order->statusCode = 'failed'; $order->save(); // Create failed transaction $order->placeTransaction( static::$gatewayKey, uniqid(), static::$exception->getMessage(), $order->statusCode ); } } catch (GatewayException $e) { static::$exception = $e; if (isset($order)) { $order->statusCode = 'failed'; $order->save(); // Create failed transaction $order->placeTransaction( static::$gatewayKey, uniqid(), static::$exception->getMessage(), $order->statusCode ); } } if ($order) { static::checkStatusChange($order, $statusCode); return $order; } else { return; } } /** * Handles gateway callbacks. * * @param string $order Order. * @param string $status Callback status */ public static function callback($order, $transaction, $status, $data = null) { $statusCode = $order->statusCode; try { if (in_array($status, ['success', 'fail'])) { static::$gatewayKey = $transaction->gateway; static::$gateway = static::instanceGateway(); if ($status == 'success') { static::$gateway->onCallbackSuccess($order, $data); $order->statusCode = static::$gateway->getTransactionStatusCode(); // Create transaction $order->placeTransaction( static::$gatewayKey, static::$gateway->getTransactionId(), static::$gateway->getTransactionDetail(), static::$gateway->getTransactionToken() ); // Fire event if ($order->isCompleted) \event(new OrderCompleted($order->id)); } else if ($status == 'fail') { static::$gateway->onCallbackFail($order, $data); $order->statusCode = 'failed'; } $order->save(); } } catch (ShopException $e) { static::setException($e); $order->statusCode = 'failed'; $order->save(); } catch (GatewayException $e) { static::setException($e); $order->statusCode = 'failed'; $order->save(); } static::checkStatusChange($order, $statusCode); } /** * Formats any value to price format set in config. * * @param mixed $value Value to format. * * @return string */ public static function format($value) { return preg_replace( [ '/:symbol/', '/:price/', '/:currency/' ], [ Config::get('shop.currency_symbol'), $value, Config::get('shop.currency') ], Config::get('shop.display_price_format') ); } /** * Retuns gateway. * * @return object */ public static function gateway() { return static::$gateway; } /** * Retuns exception. * * @return Exception */ public static function exception() { return static::$exception; } /** * Saves exception in class. * * @param mixed $e Exception */ protected static function setException($e) { Log::error($e); static::$exception = $e; } /** * Retunes gateway object. * @return object */ protected static function instanceGateway() { if (empty(static::$gatewayKey)) return; $className = '\\' . Config::get('shop.gateways')[static::$gatewayKey]; return new $className(static::$gatewayKey); } /** * Check on order status differences and fires event. * @param object $order Order. * @param string $prevStatusCode Previous status code. * @return void */ protected static function checkStatusChange($order, $prevStatusCode) { if (!empty($prevStatusCode) && $order->statusCode != $prevStatusCode) \event(new OrderStatusChanged($order->id, $order->statusCode, $prevStatusCode)); } } ================================================ FILE: src/LaravelShopFacade.php ================================================ publishes([ __DIR__ . '/Config/config.php' => config_path('shop.php'), ]); // Register commands $this->commands('command.laravel-shop.migration'); } /** * Register the service provider. * * @return void */ public function register() { $this->registerShop(); $this->registerCommands(); $this->mergeConfig(); } /** * Register the application bindings. * * @return void */ private function registerShop() { $this->app->singleton('shop', function ($app) { return new LaravelShop($app); }); } /** * Merges user's and entrust's configs. * * @return void */ private function mergeConfig() { $this->mergeConfigFrom( __DIR__ . '/Config/config.php', 'shop' ); } /** * Register the artisan commands. * * @return void */ private function registerCommands() { $this->app->singleton('command.laravel-shop.migration', function ($app) { return new MigrationCommand(); }); } /** * Get the services provided. * * @return array */ public function provides() { return [ 'shop', 'command.laravel-shop.migration' ]; } /** * Maps router. * Add package special controllers. * * @param Router $route Router. */ public function map(Router $router) { $router->group(['namespace' => 'Amsgames\LaravelShop\Http\Controllers'], function($router) { $router->group(['prefix' => 'shop'], function ($router) { $router->get('callback/payment/{status}/{id}/{shoptoken}', ['as' => 'shop.callback', 'uses' => 'Shop\CallbackController@process']); $router->post('callback/payment/{status}/{id}/{shoptoken}', ['as' => 'shop.callback', 'uses' => 'Shop\CallbackController@process']); }); }); } } ================================================ FILE: src/Models/ShopCartModel.php ================================================ table = Config::get('shop.cart_table'); } } ================================================ FILE: src/Models/ShopCouponModel.php ================================================ table = Config::get('shop.coupon_table'); } } ================================================ FILE: src/Models/ShopItemModel.php ================================================ table = Config::get('shop.item_table'); } /** * Many-to-Many relations with the user model. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function user() { return $this->belongsTo(config('auth.providers.users.model'), 'user_id'); } /** * One-to-One relations with the cart model. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function cart() { return $this->belongsTo(Config::get('shop.cart'), 'cart_id'); } /** * One-to-One relations with the order model. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function order() { return $this->belongsTo(Config::get('shop.order'), 'order_id'); } } ================================================ FILE: src/Models/ShopOrderModel.php ================================================ table = Config::get('shop.order_table'); } } ================================================ FILE: src/Models/ShopTransactionModel.php ================================================ table = Config::get('shop.transaction_table'); } } ================================================ FILE: src/Traits/ShopCalculationsTrait.php ================================================ shopCalculations)) $this->runCalculations(); return round($this->shopCalculations->itemCount, 2); } /** * Returns total price of all the items in cart. * * @return float */ public function getTotalPriceAttribute() { if (empty($this->shopCalculations)) $this->runCalculations(); return round($this->shopCalculations->totalPrice, 2); } /** * Returns total tax of all the items in cart. * * @return float */ public function getTotalTaxAttribute() { if (empty($this->shopCalculations)) $this->runCalculations(); return round($this->shopCalculations->totalTax + ($this->totalPrice * Config::get('shop.tax')), 2); } /** * Returns total tax of all the items in cart. * * @return float */ public function getTotalShippingAttribute() { if (empty($this->shopCalculations)) $this->runCalculations(); return round($this->shopCalculations->totalShipping, 2); } /** * Returns total discount amount based on all coupons applied. * * @return float */ public function getTotalDiscountAttribute() { /* TODO */ } /** * Returns total amount to be charged base on total price, tax and discount. * * @return float */ public function getTotalAttribute() { if (empty($this->shopCalculations)) $this->runCalculations(); return $this->totalPrice + $this->totalTax + $this->totalShipping; } /** * Returns formatted total price of all the items in cart. * * @return string */ public function getDisplayTotalPriceAttribute() { return Shop::format($this->totalPrice); } /** * Returns formatted total tax of all the items in cart. * * @return string */ public function getDisplayTotalTaxAttribute() { return Shop::format($this->totalTax); } /** * Returns formatted total tax of all the items in cart. * * @return string */ public function getDisplayTotalShippingAttribute() { return Shop::format($this->totalShipping); } /** * Returns formatted total discount amount based on all coupons applied. * * @return string */ public function getDisplayTotalDiscountAttribute() { /* TODO */ } /** * Returns formatted total amount to be charged base on total price, tax and discount. * * @return string */ public function getDisplayTotalAttribute() { return Shop::format($this->total); } /** * Returns cache key used to store calculations. * * @return string. */ public function getCalculationsCacheKeyAttribute() { return 'shop_' . $this->table . '_' . $this->attributes['id'] . '_calculations'; } /** * Runs calculations. */ private function runCalculations() { if (!empty($this->shopCalculations)) return $this->shopCalculations; $cacheKey = $this->calculationsCacheKey; if (Config::get('shop.cache_calculations') && Cache::has($cacheKey) ) { $this->shopCalculations = Cache::get($cacheKey); return $this->shopCalculations; } $this->shopCalculations = DB::table($this->table) ->select([ DB::raw('sum(' . Config::get('shop.item_table') . '.quantity) as itemCount'), DB::raw('sum(' . Config::get('shop.item_table') . '.price * ' . Config::get('shop.item_table') . '.quantity) as totalPrice'), DB::raw('sum(' . Config::get('shop.item_table') . '.tax * ' . Config::get('shop.item_table') . '.quantity) as totalTax'), DB::raw('sum(' . Config::get('shop.item_table') . '.shipping * ' . Config::get('shop.item_table') . '.quantity) as totalShipping') ]) ->join( Config::get('shop.item_table'), Config::get('shop.item_table') . '.' . ($this->table == Config::get('shop.order_table') ? 'order_id' : $this->table . '_id'), '=', $this->table . '.id' ) ->where($this->table . '.id', $this->attributes['id']) ->first(); if (Config::get('shop.cache_calculations')) { Cache::put( $cacheKey, $this->shopCalculations, Config::get('shop.cache_calculations_minutes') ); } return $this->shopCalculations; } /** * Resets cart calculations. */ private function resetCalculations () { $this->shopCalculations = null; if (Config::get('shop.cache_calculations')) { Cache::forget($this->calculationsCacheKey); } } } ================================================ FILE: src/Traits/ShopCartTrait.php ================================================ items()->sync([]); } return true; }); } /** * One-to-One relations with the user model. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function user() { return $this->belongsTo(config('auth.providers.users.model'), 'user_id'); } /** * One-to-Many relations with Item. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function items() { return $this->hasMany(Config::get('shop.item'), 'cart_id'); } /** * Adds item to cart. * * @param mixed $item Item to add, can be an Store Item, a Model with ShopItemTrait or an array. * @param int $quantity Item quantity in cart. */ public function add($item, $quantity = 1, $quantityReset = false) { if (!is_array($item) && !$item->isShoppable) return; // Get item $cartItem = $this->getItem(is_array($item) ? $item['sku'] : $item->sku); // Add new or sum quantity if (empty($cartItem)) { $reflection = null; if (is_object($item)) { $reflection = new \ReflectionClass($item); } $cartItem = call_user_func( Config::get('shop.item') . '::create', [ 'user_id' => $this->user->shopId, 'cart_id' => $this->attributes['id'], 'sku' => is_array($item) ? $item['sku'] : $item->sku, 'price' => is_array($item) ? $item['price'] : $item->price, 'tax' => is_array($item) ? (array_key_exists('tax', $item) ? $item['tax'] : 0 ) : (isset($item->tax) && !empty($item->tax) ? $item->tax : 0 ), 'shipping' => is_array($item) ? (array_key_exists('shipping', $item) ? $item['shipping'] : 0 ) : (isset($item->shipping) && !empty($item->shipping) ? $item->shipping : 0 ), 'currency' => Config::get('shop.currency'), 'quantity' => $quantity, 'class' => is_array($item) ? null : $reflection->getName(), 'reference_id' => is_array($item) ? null : $item->shopId, ]); } else { $cartItem->quantity = $quantityReset ? $quantity : $cartItem->quantity + $quantity; $cartItem->save(); } $this->resetCalculations(); return $this; } /** * Removes an item from the cart or decreases its quantity. * Returns flag indicating if removal was successful. * * @param mixed $item Item to remove, can be an Store Item, a Model with ShopItemTrait or an array. * @param int $quantity Item quantity to decrease. 0 if wanted item to be removed completly. * * @return bool */ public function remove($item, $quantity = 0) { // Get item $cartItem = $this->getItem(is_array($item) ? $item['sku'] : $item->sku); // Remove or decrease quantity if (!empty($cartItem)) { if (!empty($quantity)) { $cartItem->quantity -= $quantity; $cartItem->save(); if ($cartItem->quantity > 0) return true; } $cartItem->delete(); } $this->resetCalculations(); return $this; } /** * Checks if the user has a role by its name. * * @param string|array $name Role name or array of role names. * @param bool $requireAll All roles in the array are required. * * @return bool */ public function hasItem($sku, $requireAll = false) { if (is_array($sku)) { foreach ($sku as $skuSingle) { $hasItem = $this->hasItem($skuSingle); if ($hasItem && !$requireAll) { return true; } elseif (!$hasItem && $requireAll) { return false; } } // If we've made it this far and $requireAll is FALSE, then NONE of the roles were found // If we've made it this far and $requireAll is TRUE, then ALL of the roles were found. // Return the value of $requireAll; return $requireAll; } else { foreach ($this->items as $item) { if ($item->sku == $sku) { return true; } } } return false; } /** * Scope class by a given user ID. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param mixed $userId User ID. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeWhereUser($query, $userId) { return $query->where('user_id', $userId); } /** * Scope to current user cart. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeWhereCurrent($query) { if (Auth::guest()) return $query; return $query->whereUser(Auth::user()->shopId); } /** * Scope to current user cart and returns class model. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * * @return this */ public function scopeCurrent($query) { if (Auth::guest()) return; $cart = $query->whereCurrent()->first(); if (empty($cart)) { $cart = call_user_func( Config::get('shop.cart') . '::create', [ 'user_id' => Auth::user()->shopId ]); } return $cart; } /** * Scope to current user cart and returns class model. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * * @return this */ public function scopeFindByUser($query, $userId) { if (empty($userId)) return; $cart = $query->whereUser($userId)->first(); if (empty($cart)) { $cart = call_user_func( Config::get('shop.cart') . '::create', [ 'user_id' => $userId ]); } return $cart; } /** * Transforms cart into an order. * Returns created order. * * @param string $statusCode Order status to create order with. * * @return Order */ public function placeOrder($statusCode = null) { if (empty($statusCode)) $statusCode = Config::get('shop.order_status_placement'); // Create order $order = call_user_func( Config::get('shop.order') . '::create', [ 'user_id' => $this->user_id, 'statusCode' => $statusCode ]); // Map cart items into order for ($i = count($this->items) - 1; $i >= 0; --$i) { // Attach to order $this->items[$i]->order_id = $order->id; // Remove from cart $this->items[$i]->cart_id = null; // Update $this->items[$i]->save(); } $this->resetCalculations(); return $order; } /** * Whipes put cart */ public function clear() { DB::table(Config::get('shop.item_table')) ->where('cart_id', $this->attributes['id']) ->delete(); $this->resetCalculations(); return $this; } /** * Retrieves item from cart; * * @param string $sku SKU of item. * * @return mixed */ private function getItem($sku) { $className = Config::get('shop.item'); $item = new $className(); return $item->where('sku', $sku) ->where('cart_id', $this->attributes['id']) ->first(); } } ================================================ FILE: src/Traits/ShopCouponTrait.php ================================================ where('code', $code); } /** * Scopes class by coupen code and returns object. * * @return this */ public function scopeFindByCode($query, $code) { return $query->where('code', $code)->first(); } } ================================================ FILE: src/Traits/ShopItemTrait.php ================================================ attributes) && !empty($this->attributes['class']); } /** * Returns flag indicating if the object is shoppable or not. * * @return bool */ public function getIsShoppableAttribute() { return true; } /** * Returns attached object. * * @return mixed */ public function getObjectAttribute() { return $this->hasObject ? call_user_func($this->attributes['class'] . '::find', $this->attributes['reference_id']) : null; } /** * Returns item name. * * @return string */ public function getDisplayNameAttribute() { if ($this->hasObject) return $this->object->displayName; return isset($this->itemName) ? $this->attributes[$this->itemName] : (array_key_exists('name', $this->attributes) ? $this->attributes['name'] : '' ); } /** * Returns item id. * * @return mixed */ public function getShopIdAttribute() { return is_array($this->primaryKey) ? 0 : $this->attributes[$this->primaryKey]; } /** * Returns item url. * * @return string */ public function getShopUrlAttribute() { if ($this->hasObject) return $this->object->shopUrl; if (!property_exists($this, 'itemRouteName') && !property_exists($this, 'itemRouteParams')) return '#'; $params = []; foreach (array_keys($this->attributes) as $attribute) { if (in_array($attribute, $this->itemRouteParams)) $params[$attribute] = $this->attributes[$attribute]; } return empty($this->itemRouteName) ? '#' : \route($this->itemRouteName, $params); } /** * Returns price formatted for display. * * @return string */ public function getDisplayPriceAttribute() { return Shop::format($this->attributes['price']); } /** * Scope class by a given sku. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param mixed $sku SKU. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeWhereSKU($query, $sku) { return $query->where('sku', $sku); } /** * Scope class by a given sku. * Returns item found. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param mixed $sku SKU. * * @return this */ public function scopeFindBySKU($query, $sku) { return $query->whereSKU($sku)->first(); } /** * Returns formatted tax for display. * * @return string */ public function getDisplayTaxAttribute() { return Shop::format(array_key_exists('tax', $this->attributes) ? $this->attributes['tax'] : 0.00); } /** * Returns formatted tax for display. * * @return string */ public function getDisplayShippingAttribute() { return Shop::format(array_key_exists('shipping', $this->attributes) ? $this->attributes['shipping'] : 0.00); } /** * Returns flag indicating if item was purchased by user. * * @return bool */ public function getWasPurchasedAttribute() { if (Auth::guest()) return false; return Auth::user() ->orders() ->whereSKU($this->attributes['sku']) ->whereStatusIn(config('shop.order_status_purchase')) ->count() > 0; } } ================================================ FILE: src/Traits/ShopOrderTrait.php ================================================ items()->sync([]); // } // return true; //}); } /** * One-to-One relations with the user model. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function user() { return $this->belongsTo(config('auth.providers.users.model'), 'user_id'); } /** * One-to-Many relations with Item. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function items() { return $this->hasMany(Config::get('shop.item'), 'order_id'); } /** * One-to-Many relations with Item. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function transactions() { return $this->hasMany(Config::get('shop.transaction'), 'order_id'); } /** * Returns flag indicating if order is lock and cant be modified by the user. * An order is locked the moment it enters pending status. * * @return bool */ public function getIsLockedAttribute() { return in_array($this->attributes['statusCode'], Config::get('shop.order_status_lock')); } /** * Scopes class by user ID and returns object. * Optionally, scopes by status. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param mixed $userId User ID. * * @return this */ public function scopeWhereUser($query, $userId) { return $query->where('user_id', $userId); } /** * Scopes class by item sku. * Optionally, scopes by status. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param mixed $sku Item SKU. * * @return this */ public function scopeWhereSKU($query, $sku) { return $query->join( config('shop.item_table'), config('shop.item_table') . '.order_id', '=', $this->table . '.id' ) ->where(config('shop.item_table') . '.sku', $sku); } /** * Scopes class by user ID and returns object. * Optionally, scopes by status. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param string $statusCode Status. * * @return this */ public function scopeWhereStatus($query, $statusCode) { return $query = $query->where('statusCode', $statusCode); } /** * Scopes class by status codes. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param array $statusCodes Status. * * @return this */ public function scopeWhereStatusIn($query, array $statusCodes) { return $query = $query->whereIn('statusCode', $statusCodes); } /** * Scopes class by user ID and returns object. * Optionally, scopes by status. * * @param \Illuminate\Database\Eloquent\Builder $query Query. * @param mixed $userId User ID. * @param string $statusCode Status. * * @return this */ public function scopeFindByUser($query, $userId, $statusCode = null) { if (!empty($status)) { $query = $query->whereStatus($status); } return $query->whereUser($userId)->get(); } /** * Returns flag indicating if order is in the status specified. * * @param string $status Status code. * * @return bool */ public function is($statusCode) { return $this->attributes['statusCode'] == $statusCode; } /** * Returns flag indicating if order is completed. * * @return bool */ public function getIsCompletedAttribute() { return $this->attributes['statusCode'] == 'completed'; } /** * Returns flag indicating if order has failed. * * @return bool */ public function getHasFailedAttribute() { return $this->attributes['statusCode'] == 'failed'; } /** * Returns flag indicating if order is canceled. * * @return bool */ public function getIsCanceledAttribute() { return $this->attributes['statusCode'] == 'canceled'; } /** * Returns flag indicating if order is in process. * * @return bool */ public function getIsInProcessAttribute() { return $this->attributes['statusCode'] == 'in_process'; } /** * Returns flag indicating if order is in creation. * * @return bool */ public function getIsInCreationAttribute() { return $this->attributes['statusCode'] == 'in_creation'; } /** * Returns flag indicating if order is in creation. * * @return bool */ public function getIsPendingAttribute() { return $this->attributes['statusCode'] == 'pending'; } /** * Creates the order's transaction. * * @param string $gateway Gateway. * @param mixed $transactionId Transaction ID. * @param string $detail Transaction detail. * * @return object */ public function placeTransaction($gateway, $transactionId, $detail = null, $token = null) { return call_user_func(Config::get('shop.transaction') . '::create', [ 'order_id' => $this->attributes['id'], 'gateway' => $gateway, 'transaction_id' => $transactionId, 'detail' => $detail, 'token' => $token, ]); } /** * Retrieves item from order; * * @param string $sku SKU of item. * * @return mixed */ private function getItem($sku) { $className = Config::get('shop.item'); $item = new $className(); return $item->where('sku', $sku) ->where('order_id', $this->attributes['id']) ->first(); } } ================================================ FILE: src/Traits/ShopTransactionTrait.php ================================================ belongsTo(Config::get('shop.order_table'), 'order_id'); } /** * Scopes to get transactions from user. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeWhereUser($query, $userId) { return $query->join( Config::get('shop.order_table'), Config::get('shop.order_table') . '.id', '=', Config::get('shop.transaction_table') . '.order_id' ) ->where(Config::get('shop.order_table') . '.user_id', $userId); } } ================================================ FILE: src/Traits/ShopUserTrait.php ================================================ hasOne(Config::get('shop.cart'), 'user_id'); } /** * One-to-Many relations with Item. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function items() { return $this->hasMany(Config::get('shop.item'), 'user_id'); } /** * One-to-Many relations with Order. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function orders() { return $this->hasMany(Config::get('shop.order'), 'user_id'); } /** * Returns the user ID value based on the primary key set for the table. * * @param mixed */ public function getShopIdAttribute() { return is_array($this->primaryKey) ? 0 : $this->attributes[$this->primaryKey]; } } ================================================ FILE: src/views/generators/migration.blade.php ================================================ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class ShopSetupTables extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Create table for storing carts Schema::create('{{ $cartTable }}', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('user_id')->unsigned(); $table->timestamps(); $table->foreign('user_id') ->references('{{ $userKeyName }}') ->on('{{ $usersTable }}') ->onUpdate('cascade') ->onDelete('cascade'); $table->unique('user_id'); }); // Create table for storing items Schema::create('{{ $itemTable }}', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('user_id')->unsigned(); $table->bigInteger('cart_id')->unsigned()->nullable(); $table->bigInteger('order_id')->unsigned()->nullable(); $table->string('sku'); $table->decimal('price', 20, 2); $table->decimal('tax', 20, 2)->default(0); $table->decimal('shipping', 20, 2)->default(0); $table->string('currency')->nullable(); $table->integer('quantity')->unsigned(); $table->string('class')->nullable(); $table->string('reference_id')->nullable(); $table->timestamps(); $table->foreign('user_id') ->references('{{ $userKeyName }}') ->on('{{ $usersTable }}') ->onUpdate('cascade') ->onDelete('cascade'); $table->foreign('cart_id') ->references('id') ->on('{{ $cartTable }}') ->onUpdate('cascade') ->onDelete('cascade'); $table->unique(['sku', 'cart_id']); $table->unique(['sku', 'order_id']); $table->index(['user_id', 'sku']); $table->index(['user_id', 'sku', 'cart_id']); $table->index(['user_id', 'sku', 'order_id']); $table->index(['reference_id']); }); // Create table for storing coupons Schema::create('{{ $couponTable }}', function (Blueprint $table) { $table->increments('id'); $table->string('code')->unique(); $table->string('name'); $table->string('description', 1024)->nullable(); $table->string('sku'); $table->decimal('value', 20, 2)->nullable(); $table->decimal('discount', 3, 2)->nullable(); $table->integer('active')->default(1); $table->dateTime('expires_at')->nullable(); $table->timestamps(); $table->index(['code', 'expires_at']); $table->index(['code', 'active']); $table->index(['code', 'active', 'expires_at']); $table->index(['sku']); }); // Create table for storing coupons Schema::create('{{ $orderStatusTable }}', function (Blueprint $table) { $table->string('code', 32); $table->string('name'); $table->string('description')->nullable(); $table->timestamps(); $table->primary('code'); }); // Create table for storing carts Schema::create('{{ $orderTable }}', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('user_id')->unsigned(); $table->string('statusCode', 32); $table->timestamps(); $table->foreign('user_id') ->references('{{ $userKeyName }}') ->on('{{ $usersTable }}') ->onUpdate('cascade') ->onDelete('cascade'); $table->foreign('statusCode') ->references('code') ->on('{{ $orderStatusTable }}') ->onUpdate('cascade'); $table->index(['user_id', 'statusCode']); $table->index(['id', 'user_id', 'statusCode']); }); // Create table for storing transactions Schema::create('{{ $transactionTable }}', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('order_id')->unsigned(); $table->string('gateway', 64); $table->string('transaction_id', 64); $table->string('detail', 1024)->nullable(); $table->string('token')->nullable(); $table->timestamps(); $table->foreign('order_id') ->references('id') ->on('{{ $orderTable }}') ->onUpdate('cascade') ->onDelete('cascade'); $table->index(['order_id']); $table->index(['gateway', 'transaction_id']); $table->index(['order_id', 'token']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('{{ $transactionTable }}'); Schema::drop('{{ $orderTable }}'); Schema::drop('{{ $orderStatusTable }}'); Schema::drop('{{ $couponTable }}'); Schema::drop('{{ $itemTable }}'); Schema::drop('{{ $cartTable }}'); } } ================================================ FILE: src/views/generators/seeder.blade.php ================================================ use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; /** * Seeds database with shop data. */ class LaravelShopSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('{{ $orderStatusTable }}')->delete(); DB::table('{{ $orderStatusTable }}')->insert([ [ 'code' => 'in_creation', 'name' => 'In creation', 'description' => 'Order being created.', ], [ 'code' => 'pending', 'name' => 'Pending', 'description' => 'Created / placed order pending payment or similar.', ], [ 'code' => 'in_process', 'name' => 'In process', 'description' => 'Completed order in process of shipping or revision.', ], [ 'code' => 'completed', 'name' => 'Completed', 'description' => 'Completed order. Payment and other processes have been made.', ], [ 'code' => 'failed', 'name' => 'Failed', 'description' => 'Failed order. Payment or other process failed.', ], [ 'code' => 'canceled', 'name' => 'Canceled', 'description' => 'Canceled order.', ], ]); } } ================================================ FILE: tests/.gitkeep ================================================ ================================================ FILE: tests/README.md ================================================ # Test Case Configuration In order to run test cases you must setup your laravel package development environment and create the TestProduct model. ## Create testing environment There are multiple solutions to test this package. Our testing environment uses a new installation of **Laravel** and [studio](https://github.com/franzliedke/studio). After studio is install in composer and created as dependency of the project. Laravel's `composer.json` autoload section must configured to map the paths to package's `src` and `commands` folder: ```json "autoload": { "classmap": [ "database", "Amsgames/laravel-shop/src/commands" ], "psr-4": { "App\\": "app/", "Amsgames\\LaravelShop\\": "Amsgames/laravel-shop/src" } }, ``` The `tests` directory must be added to the project's `phpunit.xml` file: ```xml ./tests/ ./amsgames/laravel-shop/tests/ ``` Then be sure to setup and configure the package in the laravel's project as stated in the package's readme file. ## Gateways Add the following test gateways the array in `shop.php` config file: ```php 'gateways' => [ 'testFail' => Amsgames\LaravelShop\Gateways\GatewayFail::class, 'testPass' => Amsgames\LaravelShop\Gateways\GatewayPass::class, 'testCallback' => Amsgames\LaravelShop\Gateways\GatewayCallback::class, ], ``` ## Test Product Create the TestProduct model and database table used in the test cases: ```bash php artisan make:model TestProduct --migration ``` This will create a model file `app\TestProduct.php` and a new migration in `database\migrations` folder. Modify the migration to look like: ```php increments('id'); $table->string('sku'); $table->string('name'); $table->decimal('price', 20, 2)->nullable(); $table->string('description', 1024)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('test_products'); } } ``` And the model file to look like: ```php 'product', function ($sku) { return view('product', ['product' => App\TestProduct::findBySKU($sku)]); }]); ``` Then add the following view, called `product.blade.php`, in `resources\views\` folder: ```php {{ $product->id }} ``` ================================================ FILE: tests/ShopTest.php ================================================ assertEquals(Shop::format(1.99), '$1.99'); } /** * Tests shop class constants */ public function testConstants() { $this->assertTrue(Amsgames\LaravelShop\LaravelShop::QUANTITY_RESET); } } ================================================ FILE: tests/cart/CartTest.php ================================================ user = factory('App\User')->create(['password' => Hash::make('laravel-shop')]); Auth::attempt(['email' => $this->user->email, 'password' => 'laravel-shop']); } /** * Tests if cart is being created correctly. */ public function testCreationBasedOnUser() { $user = factory('App\User')->create(); $cart = App\Cart::findByUser($user->id); $this->assertNotEmpty($cart); $user->delete(); } /** * Tests if cart is being created correctly. */ public function testMultipleCurrentCalls() { $cart = App\Cart::current(); $this->assertNotEmpty($cart); $cart = App\Cart::findByUser($this->user->id); $this->assertNotEmpty($cart); $this->assertEquals($cart->user->id, $this->user->id); $cart = App\Cart::current(); $this->assertNotEmpty($cart); $this->assertEquals($cart->user->id, $this->user->id); } /** * Tests if cart is being created correctly. */ public function testCreationBasedOnNull() { $cart = App\Cart::findByUser(null); $this->assertNotEmpty($cart); } /** * Tests if cart is being created correctly. */ public function testCreationBasedOnAuthUser() { $cart = App\Cart::current(); $this->assertNotEmpty($cart); } /** * Tests cart item addition and removal. */ public function testAddingRemovingItems() { $products = []; while (count($products) < 3) { $products[] = App\TestProduct::create([ 'price' => count($products) + 0.99, 'sku' => str_random(15), 'name' => str_random(64), 'description' => str_random(500), ]); } $cart = App\Cart::current() ->add($products[0]) ->add($products[1], 2) ->add($products[2], 3); $this->assertEquals($cart->count, 6); $cart->add($products[2], 1, true); $this->assertEquals($cart->count, 4); $cart->remove($products[0], 1); $this->assertEquals($cart->count, 3); $cart->remove($products[2], 1); $this->assertEquals($cart->count, 2); $cart->clear(); $this->assertEquals($cart->items->count(), 0); foreach ($products as $product) { $product->delete(); } } /** * Tests cart additional methods, such as item find and calculations. */ public function testCartMethods() { $product = App\TestProduct::create([ 'price' => 1.29, 'sku' => str_random(15), 'name' => str_random(64), 'description' => str_random(500), ]); $cart = App\Cart::current() ->add($product) ->add(['sku' => 'TEST001', 'price' => 6.99]); $this->assertTrue($cart->hasItem('TEST001')); $this->assertFalse($cart->hasItem('XXX')); $this->assertEquals($cart->totalPrice, 8.28); $this->assertEquals($cart->totalTax, 0); $this->assertEquals($cart->totalShipping, 0); $this->assertEquals($cart->total, 8.28); $product->delete(); } /** * Tests cart order placement. */ public function testOrderPlacement() { $cart = App\Cart::current() ->add(['sku' => str_random(15), 'price' => 1.99]) ->add(['sku' => str_random(15), 'price' => 1.99]); $order = $cart->placeOrder(); $this->assertNotEmpty($order); $this->assertEquals($order->totalPrice, 3.98); $this->assertEquals($cart->count, 0); $this->assertEquals($order->count, 2); $this->assertTrue($order->isPending); } /** * Removes test data. */ public function tearDown() { $this->user->delete(); parent::tearDown(); } } ================================================ FILE: tests/cart/ItemTest.php ================================================ 9.99, 'sku' => str_random(15), 'name' => str_random(64), 'description' => str_random(500), ]); $this->assertTrue($product->isShoppable); $this->assertEquals($product->displayName, $product->name); $this->assertEquals($product->shopId, $product->id); $this->assertEquals($product->displayPrice, Shop::format(9.99)); $this->assertEquals($product->displayTax, Shop::format(0.00)); $this->assertEquals($product->displayShipping, Shop::format(0.00)); $response = $this->call('GET', $product->shopUrl); $this->assertResponseOk(); $this->assertEquals($product->id, $response->getContent()); $product->delete(); } /** * Tests item in cart functionality. */ public function testItemInCart() { $product = App\TestProduct::create([ 'price' => 9.99, 'sku' => str_random(15), 'name' => str_random(64), 'description' => str_random(500), ]); $user = factory('App\User')->create(); $cart = App\Cart::findByUser($user->id) ->add($product) ->add(['sku' => 'TEST0001', 'price' => 1.99]); foreach ($cart->items as $item) { if ($item->sku == 'TEST0001') { $this->assertFalse($item->hasObject); $this->assertNull($item->object); $this->assertEquals($item->shopUrl, '#'); } else { $this->assertTrue($item->hasObject); $this->assertNotEmpty($item->object); $this->assertNotEquals($item->shopUrl, '#'); } } $user->delete(); $product->delete(); } /** * Tests item in cart functionality. */ public function testPurchasedItemAttribute() { $user = factory('App\User')->create(['password' => Hash::make('laravel-shop')]); Auth::attempt(['email' => $user->email, 'password' => 'laravel-shop']); $product = App\TestProduct::create([ 'price' => 9.99, 'sku' => str_random(15), 'name' => str_random(64), 'description' => str_random(500), ]); $cart = App\Cart::current() ->add($product); Shop::setGateway('testPass'); $order = Shop::placeOrder(); $this->assertTrue($order->isCompleted); $this->assertTrue($product->wasPurchased); $user->delete(); $product->delete(); } } ================================================ FILE: tests/gateway/CallbackTest.php ================================================ user = factory('App\User')->create(['password' => Hash::make('laravel-shop')]); Auth::attempt(['email' => $this->user->email, 'password' => 'laravel-shop']); $this->product = App\TestProduct::create([ 'price' => 9.99, 'sku' => str_random(15), 'name' => str_random(64), 'description' => str_random(500), ]); $this->cart = App\Cart::current()->add($this->product); } /** * Removes test data. */ public function tearDown() { $this->user->delete(); $this->product->delete(); parent::tearDown(); } /** * Tests success callback. */ public function testSuccessCallback() { Shop::setGateway('testCallback'); Shop::checkout(); $order = Shop::placeOrder(); $callback = Shop::gateway()->getCallbackSuccess(); $this->assertTrue($order->isPending); $response = $this->call('GET', $callback); $this->assertTrue(Shop::gateway()->getDidCallback()); } /** * Tests success callback. */ public function testFailCallback() { Shop::setGateway('testCallback'); Shop::checkout(); $order = Shop::placeOrder(); $callback = Shop::gateway()->getCallbackFail(); $this->assertTrue($order->isPending); $response = $this->call('GET', $callback); $this->assertTrue(Shop::gateway()->getDidCallback()); } } ================================================ FILE: tests/order/PurchaseTest.php ================================================ assertEquals(Shop::getGateway(), 'testPass'); $gateway = Shop::gateway(); $this->assertNotNull($gateway); $this->assertNotEmpty($gateway->toJson()); } /** * Tests if gateway is being selected and created correctly. */ public function testUnselectedGateway() { $this->assertFalse(Shop::checkout()); $this->assertEquals(Shop::exception()->getMessage(), 'Payment gateway not selected.'); } /** * Tests a purchase and shop flow. */ public function testPurchaseFlow() { // Prepare $user = factory('App\User')->create(['password' => Hash::make('laravel-shop')]); $bool = Auth::attempt(['email' => $user->email, 'password' => 'laravel-shop']); $cart = App\Cart::current() ->add(['sku' => '0001', 'price' => 1.99]) ->add(['sku' => '0002', 'price' => 2.99]); Shop::setGateway('testPass'); Shop::checkout(); $order = Shop::placeOrder(); $this->assertNotNull($order); $this->assertNotEmpty($order->id); $this->assertTrue($order->isCompleted); $user->delete(); } /** * Tests a purchase and shop flow. */ public function testFailPurchase() { // Prepare $user = factory('App\User')->create(['password' => Hash::make('laravel-shop')]); $bool = Auth::attempt(['email' => $user->email, 'password' => 'laravel-shop']); $cart = App\Cart::current() ->add(['sku' => '0001', 'price' => 1.99]) ->add(['sku' => '0002', 'price' => 2.99]); Shop::setGateway('testFail'); $this->assertFalse(Shop::checkout()); $this->assertEquals(Shop::exception()->getMessage(), 'Checkout failed.'); $order = Shop::placeOrder(); $this->assertNotNull($order); $this->assertNotEmpty($order->id); $this->assertTrue($order->hasFailed); $this->assertEquals(Shop::exception()->getMessage(), 'Payment failed.'); $user->delete(); } /** * Tests if failed transactions are being created. */ public function testFailedTransactions() { // Prepare $user = factory('App\User')->create(['password' => Hash::make('laravel-shop')]); $bool = Auth::attempt(['email' => $user->email, 'password' => 'laravel-shop']); $cart = App\Cart::current() ->add(['sku' => '0001', 'price' => 1.99]) ->add(['sku' => '0002', 'price' => 2.99]); Shop::setGateway('testFail'); // Beging test $order = Shop::placeOrder(); $this->assertNotNull($order); $this->assertNotEmpty($order->id); $this->assertTrue($order->hasFailed); $this->assertEquals(count($order->transactions), 1); $user->delete(); } }