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)
--------------------------------
[](https://packagist.org/packages/amsgames/laravel-shop)
[](https://packagist.org/packages/amsgames/laravel-shop)
[](https://packagist.org/packages/amsgames/laravel-shop)
[](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**
 
## 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
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopItemModel;
class Item extends ShopItemModel
{
}
```
The `Item` model has the following main attributes:
- `id` — Item id.
- `sku` — Stock Keeping Unit, aka your unique product identification within your store.
- `price` — Item price.
- `tax` — Item tax. Defaulted to 0.
- `shipping` — Item shipping. Defaulted to 0.
- `currency` — Current version of package will use USD as default.
- `quantity` — Item quantity.
- `class` — Class reference of the model being used as shoppable item. Optional when using array data.
- `reference_id` — Id reference of the model being used as shoppable item. Optional when using array data.
- `user_id` — Owner.
- `displayPrice` — Price value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTax` — Tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayShipping` — Tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayName` — Based on the model's item name property.
- `shopUrl` — Based on the model's item route property.
- `wasPurchased` — Flag that indicates if item was purchased. This base on the status set in config file.
- `created_at` — When the item record was created in the database.
- `updated_at` — Last time when the item was updated.
Business definition: Item used as a **cart item** or an **order item**.
#### Cart
Create a Cart model:
```bash
php artisan make:model Cart
```
This will create the model file `app/Cart.php`, edit it and make it look like (take in consideration your app's namespace):
```php
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopCartModel;
class Cart extends ShopCartModel
{
}
```
The `Item` model has the following main attributes:
- `id` — Cart id.
- `user_id` — Owner.
- `items` — Items in cart.
- `count` — Total amount of items in cart.
- `totalPrice` — Total price from all items in cart.
- `totalTax` — Total tax from all items in cart, plus global tax set in config.
- `totalShipping` — Total shipping from all items in cart.
- `total` — Total amount to be charged, sums total price, total tax and total shipping.
- `displayTotalPrice` — Total price value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalTax` — Total tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalShipping` — Total shipping value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotal` — Total amount value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `created_at` — When the cart record was created in the database.
- `updated_at` — Last time when the cart was updated.
#### Order
Create a Order model:
```bash
php artisan make:model Order
```
This will create the model file `app/Order.php`, edit it and make it look like (take in consideration your app's namespace):
```php
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopOrderModel;
class Order extends ShopOrderModel
{
}
```
The `Order` model has the following main attributes:
- `id` — Order id or order number.
- `user_id` — Owner.
- `items` — Items in order.
- `transactions` — Transactions made on order.
- `statusCode` — Status code.
- `count` — Total amount of items in order.
- `totalPrice` — Total price from all items in order.
- `totalTax` — Total tax from all items in order, plus global tax set in config.
- `totalShipping` — Total shipping from all items in order.
- `total` — Total amount to be charged, sums total price, total tax and total shipping.
- `displayTotalPrice` — Total price value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalTax` — Total tax value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotalShipping` — Total shipping value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `displayTotal` — Total amount value formatted for shop display. i.e. "$9.99" instead of just "9.99".
- `created_at` — When the order record was created in the database.
- `updated_at` — Last time when the order was updated.
#### Transaction
Create a Transaction model:
```bash
php artisan make:model Transaction
```
This will create the model file `app/Transaction.php`, edit it and make it look like (take in consideration your app's namespace):
```php
<?php
namespace App;
use Amsgames\LaravelShop\Models\ShopTransactionModel;
class Transaction extends ShopTransactionModel
{
}
```
The `Order` model has the following main attributes:
- `id` — Order id or order number.
- `order` — Items in order.
- `gateway` — Gateway used.
- `transaction_id` — Transaction id returned by gateway.
- `detail` — Detail returned by gateway.
- `token` — Token for gateway callbacks.
- `created_at` — When the order record was created in the database.
- `updated_at` — Last time when the order was updated.
#### User
Use the `ShopUserTrait` trait in your existing `User` model. By adding `use Amsgames\LaravelShop\Traits\ShopUserTrait` and `use ShopUserTrait` like in the following example:
```php
<?php
use Amsgames\LaravelShop\Traits\ShopUserTrait;
class User extends Model {
use Authenticatable, CanResetPassword, ShopUserTrait;
}
```
This will enable the relation with `Cart` and shop needed methods and attributes.
- `cart` — User's cart.
- `items` — Items (either order or cart).
- `orders` — User's orders.
#### Existing Model Conversion
Laravel Shop package lets you convert any existing `Eloquent` model to a shoppable item that can be used within the shop without sacrificing any existing functionality. This feature will let the model be added to carts or orders. The will require two small steps:
Use the `ShopItemTrait` in your existing model. By adding `use Amsgames\LaravelShop\Traits\ShopItemTrait` and `use ShopItemTrait` like in the following example:
```php
<?php
use Amsgames\LaravelShop\Traits\ShopItemTrait;
class MyCustomProduct extends Model {
use ShopItemTrait;
// MY METHODS AND MODEL DEFINITIONS........
}
```
Add `sku` (string) and `price` (decimal, 20, 2) fields to your model's table. You can also include `name` (string), `tax` (decimal, 20, 2) and `shipping` (decimal, 20, 2), although these are optional. You can do this by creating a new migration:
```bash
php artisan make:migration alter_my_table
```
Define migration to look like the following example:
```php
<?php
class AlterMyTable extends Migration {
public function up()
{
Schema::table('MyCustomProduct', function($table)
{
$table->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
<?php
use Amsgames\LaravelShop\Traits\ShopItemTrait;
class MyCustomProduct extends Model {
use ShopItemTrait;
/**
* Custom field name to define the item's name.
* @var string
*/
protected $itemName = 'product_name';
// MY METHODS AND MODEL DEFINITIONS........
}
```
##### Item url
You can define the URL attribute of the item by setting `itemRouteName` and `itemRouteParams` class properties. In the following example the url defined to show the product's profile is `product/{slug}`, the following changes must be applied to the model:
```php
<?php
use Amsgames\LaravelShop\Traits\ShopItemTrait;
class MyCustomProduct extends Model {
use ShopItemTrait;
/**
* Name of the route to generate the item url.
*
* @var string
*/
protected $itemRouteName = 'product';
/**
* Name of the attributes to be included in the route params.
*
* @var string
*/
protected $itemRouteParams = ['slug'];
// MY METHODS AND MODEL DEFINITIONS........
}
```
### Dump Autoload
Dump composer autoload
```bash
composer dump-autoload
```
### Payment Gateways
Installed payment gateways can be configured and added in the `gateways` array in the `shop.php` config file, like:
```php
'gateways' => [
'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):

* (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
<span>Items in cart: {{ $cart->count }}</span>
```
Items in cart:
```html
<table>
@foreach ($cart->items as $item) {
<tr>
<td>{{ $item->sku }}</td>
<td><a href="{{ $item->shopUrl }}">{{ $item->displayName }}</a></td>
<td>{{ $item->price }}</td>
<td>{{ $item->displayPrice }}</td>
<td>{{ $item->tax }}</td>
<td>{{ $item->quantity }}</td>
<td>{{ $item->shipping }}</td>
</tr>
@endforeach
</table>
```
Cart amount calculations:
```html
<table>
<tbody>
<tr>
<td>Subtotal:</td>
<td>{{ $cart->displayTotalPrice }}</td>
<td>{{ $cart->totalPrice }}</td>
</tr>
<tr>
<td>Shipping:</td>
<td>{{ $cart->displayTotalShipping }}</td>
</tr>
<tr>
<td>Tax:</td>
<td>{{ $cart->displayTotalTax }}</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total:</th>
<th>{{ $cart->displayTotal }}</th>
<th>{{ $cart->total }}</th>
</tr>
</tfoot>
</table>
```
### 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
<?php
namespace App\Handlers\Events;
use App\Order;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Amsgames\LaravelShop\Events\OrderCompleted;
class NotifyPurchase implements ShouldQueue
{
use InteractsWithQueue;
/**
* Handle the event.
*
* @param OrderPurchased $event
* @return void
*/
public function handle(OrderCompleted $event)
{
// The order ID
echo $event->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
<?php
namespace Vendor\Package;
use Amsgames\LaravelShop\Core\PaymentGateway;
use Amsgames\LaravelShop\Exceptions\CheckoutException;
use Amsgames\LaravelShop\Exceptions\GatewayException;
class GatewayPayPal extends PaymentGateway
{
/**
* Called on cart checkout.
* THIS METHOD IS OPTIONAL, DONE FOR GATEWAY VALIDATIONS BEFORE PLACING AN ORDER
*
* @param Order $order Order.
*/
public function onCheckout($cart)
{
throw new CheckoutException('Checkout failed.');
}
/**
* Called by shop to charge order's amount.
*
* @param Order $order Order.
*
* @return bool
*/
public function onCharge($order)
{
throw new GatewayException('Payment failed.');
return false;
}
}
```
The gateway will require `onCharge` method as minimun. You can add more depending your needs.
Once created, you can add it to the `shop.php` config file, like:
```php
'gateways' => [
'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
<?php
namespace Vendor\Package;
use Amsgames\LaravelShop\Core\PaymentGateway;
use Amsgames\LaravelShop\Exceptions\CheckoutException;
use Amsgames\LaravelShop\Exceptions\GatewayException;
class GatewayWithCallbacks extends PaymentGateway
{
/**
* Called by shop to charge order's amount.
*
* @param Order $order Order.
*
* @return bool
*/
public function onCharge($order)
{
// Set the order to pending.
$this->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
================================================
<?php
namespace Amsgames\LaravelShop;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
class MigrationCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'laravel-shop:migration';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Creates a migration following the LaravelShop specifications.';
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$this->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
================================================
<?php
/**
* This file is part of Amsgames\LaravelShop,
* Shop functionality for Laravel.
*
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
return [
/*
|--------------------------------------------------------------------------
| Shop name
|--------------------------------------------------------------------------
|
| Shop name.
|
*/
'name' => '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
================================================
<?php
namespace Amsgames\LaravelShop\Contracts;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
interface PaymentGatewayInterface
{
/**
* Constructor.
*/
public function __construct($id = '');
/**
* Called on cart checkout.
*
* @param Cart $cart Cart.
*/
public function onCheckout($cart);
/**
* Called by shop to charge order's amount.
*
* @param Order $order Order.
*
* @return bool
*/
public function onCharge($order);
/**
* Returns the transaction ID generated by the gateway.
* i.e. PayPal's transaction ID.
*
* @return mixed
*/
public function getTransactionId();
/**
* Returns a 1024 length string with extra detail of transaction.
*
* @return string
*/
public function getTransactionDetail();
/**
* Returns token.
*
* @return string
*/
public function getTransactionToken();
/**
* Called by shop when payment gateway calls callback url.
* Success result
*
* @param Order $order Order.
* @param mixed $data Request input from callback.
*/
public function onCallbackSuccess($order, $data = null);
/**
* Called by shop when payment gateway calls callback url.
* Failed result
*
* @param Order $order Order.
* @param mixed $data Request input from callback.
*/
public function onCallbackFail($order, $data = null);
/**
* Sets callback urls
*
* @param Order $order Order.
*/
public function setCallbacks($order);
/**
* Returns transaction status code.
*
* @return string
*/
public function getTransactionStatusCode();
}
================================================
FILE: src/Contracts/ShopCartInterface.php
================================================
<?php
namespace Amsgames\LaravelShop\Contracts;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
interface ShopCartInterface
{
/**
* One-to-One relations with the user model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function user();
/**
* One-to-Many relations with Item.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function items();
/**
* 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 = self::QUANTITY_ADDITION);
/**
* 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);
/**
* 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);
/**
* Scope to current user cart and returns class model.
*
* @param \Illuminate\Database\Eloquent\Builder $query Query.
*
* @return this
*/
public function scopeCurrent($query);
/**
* Returns total amount of items in cart.
*
* @return int
*/
public function getCountAttribute();
/**
* Returns total price of all the items in cart.
*
* @return float
*/
public function getTotalPriceAttribute();
/**
* Returns total tax of all the items in cart.
*
* @return float
*/
public function getTotalTaxAttribute();
/**
* Returns total tax of all the items in cart.
*
* @return float
*/
public function getTotalShippingAttribute();
/**
* Returns total discount amount based on all coupons applied.
*
* @return float
*/
public function getTotalDiscountAttribute();
/**
* Returns total amount to be charged base on total price, tax and discount.
*
* @return float
*/
public function getTotalAttribute();
/**
* Returns formatted total price of all the items in cart.
*
* @return string
*/
public function getDisplayTotalPriceAttribute();
/**
* Returns formatted total tax of all the items in cart.
*
* @return string
*/
public function getDisplayTotalTaxAttribute();
/**
* Returns formatted total tax of all the items in cart.
*
* @return string
*/
public function getDisplayTotalShippingAttribute();
/**
* Returns formatted total discount amount based on all coupons applied.
*
* @return string
*/
public function getDisplayTotalDiscountAttribute();
/**
* Returns formatted total amount to be charged base on total price, tax and discount.
*
* @return string
*/
public function getDisplayTotalAttribute();
/**
* Transforms cart into an order.
* Returns created order.
*
* @param mixed $status Order status to create order with.
*
* @return Order
*/
public function placeOrder($statusCode = null);
/**
* Whipes put cart
*/
public function clear();
}
================================================
FILE: src/Contracts/ShopCouponInterface.php
================================================
<?php
namespace Amsgames\LaravelShop\Contracts;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
interface ShopCouponInterface
{
/**
* Scopes class by coupon code.
*
* @return QueryBuilder
*/
public function scopeWhereCode($query, $code);
/**
* Scopes class by coupen code and returns object.
*
* @return this
*/
public function scopeFindByCode($query, $code);
}
================================================
FILE: src/Contracts/ShopItemInterface.php
================================================
<?php
namespace Amsgames\LaravelShop\Contracts;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
interface ShopItemInterface
{
/**
* One-to-One relations with the user model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function user();
/**
* One-to-One relations with the cart model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function cart();
/**
* One-to-One relations with Order.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function order();
/**
* Returns flag indicating if item has an object.
*
* @return bool
*/
public function getHasObjectAttribute();
/**
* Returns attached object.
*
* @return mixed
*/
public function getObjectAttribute();
/**
* Returns item name.
*
* @return string
*/
public function getDisplayNameAttribute();
/**
* Returns shop it.
*
* @return mixed
*/
public function getShopIdAttribute();
/**
* Returns formatted price for display.
*
* @return string
*/
public function getDisplayPriceAttribute();
/**
* Returns formatted tax for display.
*
* @return string
*/
public function getDisplayTaxAttribute();
/**
* Returns formatted tax for display.
*
* @return string
*/
public function getDisplayShippingAttribute();
/**
* Returns flag indicating if item was purchased by user.
*
* @return bool
*/
public function getWasPurchasedAttribute();
}
================================================
FILE: src/Contracts/ShopOrderInterface.php
================================================
<?php
namespace Amsgames\LaravelShop\Contracts;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
interface ShopOrderInterface
{
/**
* One-to-One relations with the user model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToOne
*/
public function user();
/**
* One-to-Many relations with Item.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function items();
/**
* One-to-Many relations with Item.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function transactions();
/**
* 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();
/**
* 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);
/**
* Returns total amount of items in cart.
*
* @return int
*/
public function getCountAttribute();
/**
* Returns total price of all the items in cart.
*
* @return float
*/
public function getTotalPriceAttribute();
/**
* Returns total tax of all the items in cart.
*
* @return float
*/
public function getTotalTaxAttribute();
/**
* Returns total tax of all the items in cart.
*
* @return float
*/
public function getTotalShippingAttribute();
/**
* Returns total discount amount based on all coupons applied.
*
* @return float
*/
public function getTotalDiscountAttribute();
/**
* Returns total amount to be charged base on total price, tax and discount.
*
* @return float
*/
public function getTotalAttribute();
/**
* Returns formatted total price of all the items in cart.
*
* @return string
*/
public function getDisplayTotalPriceAttribute();
/**
* Returns formatted total tax of all the items in cart.
*
* @return string
*/
public function getDisplayTotalTaxAttribute();
/**
* Returns formatted total tax of all the items in cart.
*
* @return string
*/
public function getDisplayTotalShippingAttribute();
/**
* Returns formatted total discount amount based on all coupons applied.
*
* @return string
*/
public function getDisplayTotalDiscountAttribute();
/**
* Returns formatted total amount to be charged base on total price, tax and discount.
*
* @return string
*/
public function getDisplayTotalAttribute();
/**
* Returns flag indicating if order is in the status specified.
*
* @param string $status Status code.
*
* @return bool
*/
public function is($statusCode);
/**
* 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 = '');
/**
* 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);
/**
* Scopes class by status codes.
*
* @param \Illuminate\Database\Eloquent\Builder $query Query.
* @param array $statusCodes Status.
*
* @return this
*/
public function scopeWhereStatusIn($query, array $statusCodes);
}
================================================
FILE: src/Contracts/ShopTransactionInterface.php
================================================
<?php
namespace Amsgames\LaravelShop\Contracts;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
interface ShopTransactionInterface
{
/**
* One-to-One relations with the order model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function order();
/**
* Scopes to get transactions from user.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhereUser($query, $userId);
}
================================================
FILE: src/Core/PaymentGateway.php
================================================
<?php
namespace Amsgames\LaravelShop\Core;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use JsonSerializable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Amsgames\LaravelShop\Contracts\PaymentGatewayInterface;
abstract class PaymentGateway implements PaymentGatewayInterface, Arrayable, Jsonable, JsonSerializable
{
/**
* Gateway Id, set by shop.
*
* @var mixed
*/
protected $id;
/**
* Gateway generated transaction id.
*
* @var mixed
*/
protected $transactionId;
/**
* Gateway generated transaction id.
*
* @var string
*/
protected $detail = null;
/**
* Gateway generated token.
*
* @var mixed
*/
protected $token = null;
/**
* Success call back url.
*
* @var mixed
*/
protected $callbackSuccess = '';
/**
* Fail call back url.
*
* @var mixed
*/
protected $callbackFail = '';
/**
* Status code after placing order successfully.
*
* @var string
*/
protected $statusCode = 'completed';
/**
* Constructor.
*
* @param mixed $if Gateway id.
*/
public function __construct($id = '')
{
$this->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
================================================
<?php
namespace Amsgames\LaravelShop\Events;
use Illuminate\Queue\SerializesModels;
/**
* Event fired when an order has been completed.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
class CartCheckout
{
use SerializesModels;
/**
* Cart ID.
* @var int
*/
public $id;
/**
* Flag that indicates if the checkout was successful or not.
* @var bool
*/
public $success;
/**
* Create a new event instance.
*
* @param int $id Order ID.
* @param bool $success Checkout flag result.
*
* @return void
*/
public function __construct($id, $success)
{
$this->id = $id;
$this->success = $success;
}
}
================================================
FILE: src/Events/OrderCompleted.php
================================================
<?php
namespace Amsgames\LaravelShop\Events;
use Illuminate\Queue\SerializesModels;
/**
* Event fired when an order has been completed.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
class OrderCompleted
{
use SerializesModels;
/**
* Order ID.
* @var int
*/
public $id;
/**
* Create a new event instance.
*
* @param int $id Order ID.
*
* @return void
*/
public function __construct($id)
{
$this->id = $id;
}
}
================================================
FILE: src/Events/OrderPlaced.php
================================================
<?php
namespace Amsgames\LaravelShop\Events;
use Illuminate\Queue\SerializesModels;
/**
* Event fired when an order is placed.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
class OrderPlaced
{
use SerializesModels;
/**
* Order ID.
* @var int
*/
public $id;
/**
* Create a new event instance.
*
* @param int $id Order ID.
*
* @return void
*/
public function __construct($id)
{
$this->id = $id;
}
}
================================================
FILE: src/Events/OrderStatusChanged.php
================================================
<?php
namespace Amsgames\LaravelShop\Events;
use Illuminate\Queue\SerializesModels;
/**
* Event fired when an order has changed status code.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
class OrderStatusChanged
{
use SerializesModels;
/**
* Order ID.
* @var int
*/
public $id;
/**
* Order status code.
* @var string
*/
public $statusCode;
/**
* Previous order status code.
* @var string
*/
public $previousStatusCode;
/**
* Create a new event instance.
*
* @param int $id Order ID.
* @param string $statusCode Order status code.
*
* @return void
*/
public function __construct($id, $statusCode, $previousStatusCode)
{
$this->id = $id;
$this->statusCode = $statusCode;
$this->previousStatusCode = $previousStatusCode;
}
}
================================================
FILE: src/Exceptions/CheckoutException.php
================================================
<?php
namespace Amsgames\LaravelShop\Exceptions;
/**
* This class is the main entry point of laravel shop. Usually this the interaction
* with this class will be done through the LaravelShop Facade
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
class CheckoutException extends \Exception
{
}
================================================
FILE: src/Exceptions/GatewayException.php
================================================
<?php
namespace Amsgames\LaravelShop\Exceptions;
/**
* This class is the main entry point of laravel shop. Usually this the interaction
* with this class will be done through the LaravelShop Facade
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
class GatewayException extends \Exception
{
}
================================================
FILE: src/Exceptions/ShopException.php
================================================
<?php
namespace Amsgames\LaravelShop\Exceptions;
/**
* This class is the main entry point of laravel shop. Usually this the interaction
* with this class will be done through the LaravelShop Facade
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
class ShopException extends \Exception
{
}
================================================
FILE: src/Gateways/GatewayCallback.php
================================================
<?php
namespace Amsgames\LaravelShop\Gateways;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Amsgames\LaravelShop\Gateways\GatewayPass;
class GatewayCallback extends GatewayPass
{
/**
* For callback uses.
*/
protected $didCallback = false;
/**
* Called by shop to charge order's amount.
*
* @param Order $order Order.
*
* @return bool
*/
public function onCharge($order)
{
$this->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
================================================
<?php
namespace Amsgames\LaravelShop\Gateways;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Amsgames\LaravelShop\Exceptions\CheckoutException;
use Amsgames\LaravelShop\Exceptions\GatewayException;
use Amsgames\LaravelShop\Exceptions\ShopException;
use Amsgames\LaravelShop\Core\PaymentGateway;
class GatewayFail extends PaymentGateway
{
/**
* Called on cart checkout.
*
* @param Order $order Order.
*/
public function onCheckout($cart)
{
throw new CheckoutException('Checkout failed.');
}
/**
* Called by shop to charge order's amount.
*
* @param Order $order Order.
*
* @return bool
*/
public function onCharge($order)
{
throw new GatewayException('Payment failed.');
return false;
}
}
================================================
FILE: src/Gateways/GatewayPass.php
================================================
<?php
namespace Amsgames\LaravelShop\Gateways;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Log;
use Amsgames\LaravelShop\Core\PaymentGateway;
class GatewayPass extends PaymentGateway
{
/**
* Called by shop to charge order's amount.
*
* @param Order $order Order.
*
* @return bool
*/
public function onCharge($order)
{
$this->transactionId = uniqid();
return true;
}
}
================================================
FILE: src/Http/Controllers/Controller.php
================================================
<?php
namespace Amsgames\LaravelShop\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests;
}
================================================
FILE: src/Http/Controllers/Shop/CallbackController.php
================================================
<?php
namespace Amsgames\LaravelShop\Http\Controllers\Shop;
use Validator;
use Shop;
use Illuminate\Http\Request;
use Amsgames\LaravelShop\Http\Controllers\Controller;
class CallbackController extends Controller
{
/**
* Process payment callback.
*
* @param Request $request Request.
*
* @return redirect
*/
protected function process(Request $request)
{
$validator = Validator::make(
[
'order_id' => $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
================================================
<?php
namespace Amsgames\LaravelShop;
/**
* This class is the main entry point of laravel shop. Usually this the interaction
* with this class will be done through the LaravelShop Facade
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Auth;
use Amsgames\LaravelShop\Gateways;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
use Amsgames\LaravelShop\Exceptions\CheckoutException;
use Amsgames\LaravelShop\Exceptions\GatewayException;
use Amsgames\LaravelShop\Exceptions\ShopException;
use Amsgames\LaravelShop\Events\CartCheckout;
use Amsgames\LaravelShop\Events\OrderCompleted;
use Amsgames\LaravelShop\Events\OrderPlaced;
use Amsgames\LaravelShop\Events\OrderStatusChanged;
class LaravelShop
{
/**
* Forces quantity to reset when adding items to cart.
* @var bool
*/
const QUANTITY_RESET = true;
/**
* Gateway in use.
* @var string
*/
protected static $gatewayKey = null;
/**
* Gateway instance.
* @var object
*/
protected static $gateway = null;
/**
* Gatway in use.
* @var string
*/
protected static $exception = null;
/**
* Laravel application
*
* @var \Illuminate\Foundation\Application
*/
private $errorMessage;
/**
* Laravel application
*
* @var \Illuminate\Foundation\Application
*/
public $app;
/**
* Create a new confide instance.
*
* @param \Illuminate\Foundation\Application $app
*
* @return void
*/
public function __construct($app)
{
$this->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
================================================
<?php
namespace Amsgames\LaravelShop;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Illuminate\Support\Facades\Facade;
class LaravelShopFacade extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'shop';
}
}
================================================
FILE: src/LaravelShopProvider.php
================================================
<?php
namespace Amsgames\LaravelShop;
/**
* Service provider for laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class LaravelShopProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
// Publish config files
$this->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
================================================
<?php
namespace Amsgames\LaravelShop\Models;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Amsgames\LaravelShop\Contracts\ShopCartInterface;
use Amsgames\LaravelShop\Traits\ShopCartTrait;
use Amsgames\LaravelShop\Traits\ShopCalculationsTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
class ShopCartModel extends Model implements ShopCartInterface
{
use ShopCartTrait, ShopCalculationsTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table;
/**
* Fillable attributes for mass assignment.
*
* @var array
*/
protected $fillable = ['user_id'];
/**
* Creates a new instance of the model.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->table = Config::get('shop.cart_table');
}
}
================================================
FILE: src/Models/ShopCouponModel.php
================================================
<?php
namespace Amsgames\LaravelShop\Models;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Amsgames\LaravelShop\Contracts\ShopCouponInterface;
use Amsgames\LaravelShop\Traits\ShopCouponTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
class ShopCouponModel extends Model implements ShopCouponInterface
{
use ShopCouponTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table;
/**
* Fillable attributes for mass assignment.
*
* @var array
*/
protected $fillable = ['code', 'sku', 'value', 'discount', 'name', 'description', 'expires_at'];
/**
* Creates a new instance of the model.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->table = Config::get('shop.coupon_table');
}
}
================================================
FILE: src/Models/ShopItemModel.php
================================================
<?php
namespace Amsgames\LaravelShop\Models;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Amsgames\LaravelShop\Contracts\ShopItemInterface;
use Amsgames\LaravelShop\Traits\ShopItemTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
class ShopItemModel extends Model implements ShopItemInterface
{
use ShopItemTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table;
/**
* Name of the route to generate the item url.
*
* @var string
*/
protected $itemRouteName = '';
/**
* Name of the attributes to be included in the route params.
*
* @var string
*/
protected $itemRouteParams = [];
/**
* Name of the attributes to be included in the route params.
*
* @var string
*/
protected $fillable = ['user_id', 'cart_id', 'shop_id', 'sku', 'price', 'tax', 'shipping', 'currency', 'quantity', 'class', 'reference_id'];
/**
* Creates a new instance of the model.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->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
================================================
<?php
namespace Amsgames\LaravelShop\Models;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Amsgames\LaravelShop\Contracts\ShopOrderInterface;
use Amsgames\LaravelShop\Traits\ShopOrderTrait;
use Amsgames\LaravelShop\Traits\ShopCalculationsTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
class ShopOrderModel extends Model implements ShopOrderInterface
{
use ShopOrderTrait, ShopCalculationsTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table;
/**
* Fillable attributes for mass assignment.
*
* @var array
*/
protected $fillable = ['user_id', 'statusCode'];
/**
* Creates a new instance of the model.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->table = Config::get('shop.order_table');
}
}
================================================
FILE: src/Models/ShopTransactionModel.php
================================================
<?php
namespace Amsgames\LaravelShop\Models;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Amsgames\LaravelShop\Contracts\ShopTransactionInterface;
use Amsgames\LaravelShop\Traits\ShopTransactionTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
class ShopTransactionModel extends Model implements ShopTransactionInterface
{
use ShopTransactionTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table;
/**
* Fillable attributes for mass assignment.
*
* @var array
*/
protected $fillable = ['order_id', 'gateway', 'transaction_id', 'detail', 'token'];
/**
* Creates a new instance of the model.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->table = Config::get('shop.transaction_table');
}
}
================================================
FILE: src/Traits/ShopCalculationsTrait.php
================================================
<?php
namespace Amsgames\LaravelShop\Traits;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Shop;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
trait ShopCalculationsTrait
{
/**
* Property used to stored calculations.
* @var array
*/
private $shopCalculations = null;
/**
* Returns total amount of items in cart.
*
* @return int
*/
public function getCountAttribute()
{
if (empty($this->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
================================================
<?php
namespace Amsgames\LaravelShop\Traits;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Shop;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
trait ShopCartTrait
{
/**
* Property used to stored calculations.
* @var array
*/
private $cartCalculations = null;
/**
* Boot the user model
* Attach event listener to remove the relationship records when trying to delete
* Will NOT delete any records if the user model uses soft deletes.
*
* @return void|bool
*/
public static function boot()
{
parent::boot();
static::deleting(function($user) {
if (!method_exists(Config::get('auth.providers.users.model'), 'bootSoftDeletingTrait')) {
$user->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
================================================
<?php
namespace Amsgames\LaravelShop\Traits;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Illuminate\Support\Facades\Config;
use InvalidArgumentException;
trait ShopCouponTrait
{
/**
* Scopes class by coupon code.
*
* @return QueryBuilder
*/
public function scopeWhereCode($query, $code)
{
return $query->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
================================================
<?php
namespace Amsgames\LaravelShop\Traits;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Auth;
use Shop;
use Illuminate\Support\Facades\Config;
use InvalidArgumentException;
trait ShopItemTrait
{
/**
* Returns flag indicating if item has an object.
*
* @return bool
*/
public function getHasObjectAttribute()
{
return array_key_exists('class', $this->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
================================================
<?php
namespace Amsgames\LaravelShop\Traits;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Illuminate\Support\Facades\Config;
use InvalidArgumentException;
trait ShopOrderTrait
{
/**
* Boot the user model
* Attach event listener to remove the relationship records when trying to delete
* Will NOT delete any records if the user model uses soft deletes.
*
* @return void|bool
*/
public static function boot()
{
parent::boot();
//static::deleting(function($user) {
// if (!method_exists(Config::get('auth.model'), 'bootSoftDeletingTrait')) {
//$user->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
================================================
<?php
namespace Amsgames\LaravelShop\Traits;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Illuminate\Support\Facades\Config;
use InvalidArgumentException;
trait ShopTransactionTrait
{
/**
* One-to-One relations with the order model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function order()
{
return $this->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
================================================
<?php
namespace Amsgames\LaravelShop\Traits;
/**
* This file is part of LaravelShop,
* A shop solution for Laravel.
*
* @author Alejandro Mostajo
* @copyright Amsgames, LLC
* @license MIT
* @package Amsgames\LaravelShop
*/
use Illuminate\Support\Facades\Config;
use InvalidArgumentException;
trait ShopUserTrait
{
/**
* One-to-Many relations with cart.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function cart()
{
return $this->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
================================================
<?php echo '<?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
================================================
<?php echo '<?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
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
<directory>./amsgames/laravel-shop/tests/</directory>
</testsuite>
</testsuites>
```
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
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTestProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('test_products', function (Blueprint $table) {
$table->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
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Amsgames\LaravelShop\Traits\ShopItemTrait;
class TestProduct extends Model
{
use ShopItemTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'test_products';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'sku', 'description', 'price'];
/**
* Name of the route to generate the item url.
*
* @var string
*/
protected $itemRouteName = 'product';
/**
* Name of the attributes to be included in the route params.
*
* @var string
*/
protected $itemRouteParams = ['sku'];
}
```
Additionally add the following route in `app\Http\routes.php`:
```php
Route::get('/product/{sku}', ['as' => '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
================================================
<?php
use App;
use Log;
use Shop;
use Amsgames\LaravelShop;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ShopTest extends TestCase
{
/**
* Tests shop class static methods.
*/
public function testStaticMethods()
{
$this->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
================================================
<?php
use App;
use Auth;
use Hash;
use Log;
use Shop;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CartTest extends TestCase
{
/**
* User set for tests.
*/
protected $user;
/**
* Setups test data.
*/
public function setUp()
{
parent::setUp();
$this->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
================================================
<?php
use App;
use Auth;
use Hash;
use Shop;
use Log;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ItemTest extends TestCase
{
/**
* Tests item trait methods on external model.
*/
public function testItemMethodsAndAttributes()
{
$product = App\TestProduct::create([
'price' => 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
================================================
<?php
use App;
use Shop;
use Log;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CallbackTest extends TestCase
{
/**
* User set for tests.
*/
protected $user;
/**
* Cart set for tests.
*/
protected $cart;
/**
* Product set for tests.
*/
protected $product;
/**
* Setups test data.
*/
public function setUp()
{
parent::setUp();
$this->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
================================================
<?php
use App;
use Auth;
use Hash;
use Log;
use Shop;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PurchaseTest extends TestCase
{
/**
* Tests if gateway is being selected and created correctly.
*/
public function testGateway()
{
Shop::setGateway('testPass');
$this->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();
}
}
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
SYMBOL INDEX (252 symbols across 40 files)
FILE: src/Commands/MigrationCommand.php
class MigrationCommand (line 18) | class MigrationCommand extends Command
method fire (line 39) | public function fire()
method createMigration (line 126) | protected function createMigration($data)
method createSeeder (line 154) | protected function createSeeder($data)
FILE: src/Contracts/PaymentGatewayInterface.php
type PaymentGatewayInterface (line 15) | interface PaymentGatewayInterface
method __construct (line 20) | public function __construct($id = '');
method onCheckout (line 27) | public function onCheckout($cart);
method onCharge (line 36) | public function onCharge($order);
method getTransactionId (line 44) | public function getTransactionId();
method getTransactionDetail (line 51) | public function getTransactionDetail();
method getTransactionToken (line 58) | public function getTransactionToken();
method onCallbackSuccess (line 67) | public function onCallbackSuccess($order, $data = null);
method onCallbackFail (line 76) | public function onCallbackFail($order, $data = null);
method setCallbacks (line 83) | public function setCallbacks($order);
method getTransactionStatusCode (line 90) | public function getTransactionStatusCode();
FILE: src/Contracts/ShopCartInterface.php
type ShopCartInterface (line 15) | interface ShopCartInterface
method user (line 23) | public function user();
method items (line 30) | public function items();
method add (line 38) | public function add($item, $quantity = 1, $quantityReset = self::QUANT...
method remove (line 49) | public function remove($item, $quantity = 0);
method hasItem (line 59) | public function hasItem($sku, $requireAll = false);
method scopeCurrent (line 68) | public function scopeCurrent($query);
method getCountAttribute (line 75) | public function getCountAttribute();
method getTotalPriceAttribute (line 82) | public function getTotalPriceAttribute();
method getTotalTaxAttribute (line 89) | public function getTotalTaxAttribute();
method getTotalShippingAttribute (line 96) | public function getTotalShippingAttribute();
method getTotalDiscountAttribute (line 103) | public function getTotalDiscountAttribute();
method getTotalAttribute (line 110) | public function getTotalAttribute();
method getDisplayTotalPriceAttribute (line 117) | public function getDisplayTotalPriceAttribute();
method getDisplayTotalTaxAttribute (line 124) | public function getDisplayTotalTaxAttribute();
method getDisplayTotalShippingAttribute (line 131) | public function getDisplayTotalShippingAttribute();
method getDisplayTotalDiscountAttribute (line 138) | public function getDisplayTotalDiscountAttribute();
method getDisplayTotalAttribute (line 145) | public function getDisplayTotalAttribute();
method placeOrder (line 155) | public function placeOrder($statusCode = null);
method clear (line 160) | public function clear();
FILE: src/Contracts/ShopCouponInterface.php
type ShopCouponInterface (line 15) | interface ShopCouponInterface
method scopeWhereCode (line 23) | public function scopeWhereCode($query, $code);
method scopeFindByCode (line 30) | public function scopeFindByCode($query, $code);
FILE: src/Contracts/ShopItemInterface.php
type ShopItemInterface (line 15) | interface ShopItemInterface
method user (line 23) | public function user();
method cart (line 30) | public function cart();
method order (line 37) | public function order();
method getHasObjectAttribute (line 44) | public function getHasObjectAttribute();
method getObjectAttribute (line 51) | public function getObjectAttribute();
method getDisplayNameAttribute (line 58) | public function getDisplayNameAttribute();
method getShopIdAttribute (line 65) | public function getShopIdAttribute();
method getDisplayPriceAttribute (line 72) | public function getDisplayPriceAttribute();
method getDisplayTaxAttribute (line 79) | public function getDisplayTaxAttribute();
method getDisplayShippingAttribute (line 86) | public function getDisplayShippingAttribute();
method getWasPurchasedAttribute (line 93) | public function getWasPurchasedAttribute();
FILE: src/Contracts/ShopOrderInterface.php
type ShopOrderInterface (line 15) | interface ShopOrderInterface
method user (line 23) | public function user();
method items (line 30) | public function items();
method transactions (line 37) | public function transactions();
method getIsLockedAttribute (line 45) | public function getIsLockedAttribute();
method scopeFindByUser (line 57) | public function scopeFindByUser($query, $userId, $statusCode = null);
method getCountAttribute (line 64) | public function getCountAttribute();
method getTotalPriceAttribute (line 71) | public function getTotalPriceAttribute();
method getTotalTaxAttribute (line 78) | public function getTotalTaxAttribute();
method getTotalShippingAttribute (line 85) | public function getTotalShippingAttribute();
method getTotalDiscountAttribute (line 92) | public function getTotalDiscountAttribute();
method getTotalAttribute (line 99) | public function getTotalAttribute();
method getDisplayTotalPriceAttribute (line 106) | public function getDisplayTotalPriceAttribute();
method getDisplayTotalTaxAttribute (line 113) | public function getDisplayTotalTaxAttribute();
method getDisplayTotalShippingAttribute (line 120) | public function getDisplayTotalShippingAttribute();
method getDisplayTotalDiscountAttribute (line 127) | public function getDisplayTotalDiscountAttribute();
method getDisplayTotalAttribute (line 134) | public function getDisplayTotalAttribute();
method is (line 143) | public function is($statusCode);
method placeTransaction (line 154) | public function placeTransaction($gateway, $transactionId, $detail = '');
method scopeWhereSKU (line 165) | public function scopeWhereSKU($query, $sku);
method scopeWhereStatusIn (line 175) | public function scopeWhereStatusIn($query, array $statusCodes);
FILE: src/Contracts/ShopTransactionInterface.php
type ShopTransactionInterface (line 15) | interface ShopTransactionInterface
method order (line 22) | public function order();
method scopeWhereUser (line 29) | public function scopeWhereUser($query, $userId);
FILE: src/Core/PaymentGateway.php
class PaymentGateway (line 20) | abstract class PaymentGateway implements PaymentGatewayInterface, Arraya...
method __construct (line 76) | public function __construct($id = '')
method onCheckout (line 88) | public function onCheckout($cart)
method onCallbackSuccess (line 101) | public function onCallbackSuccess($order, $data = null)
method onCallbackFail (line 114) | public function onCallbackFail($order, $data = null)
method setCallbacks (line 123) | public function setCallbacks($order)
method getTransactionToken (line 143) | public function getTransactionToken()
method getTransactionId (line 154) | public function getTransactionId()
method getTransactionDetail (line 164) | public function getTransactionDetail()
method getTransactionStatusCode (line 174) | public function getTransactionStatusCode()
method toArray (line 184) | public function toArray()
method toJson (line 195) | public function toJson($options = 0)
method jsonSerialize (line 205) | public function jsonSerialize()
method __toString (line 215) | public function __toString()
FILE: src/Events/CartCheckout.php
class CartCheckout (line 15) | class CartCheckout
method __construct (line 39) | public function __construct($id, $success)
FILE: src/Events/OrderCompleted.php
class OrderCompleted (line 15) | class OrderCompleted
method __construct (line 32) | public function __construct($id)
FILE: src/Events/OrderPlaced.php
class OrderPlaced (line 15) | class OrderPlaced
method __construct (line 32) | public function __construct($id)
FILE: src/Events/OrderStatusChanged.php
class OrderStatusChanged (line 15) | class OrderStatusChanged
method __construct (line 45) | public function __construct($id, $statusCode, $previousStatusCode)
FILE: src/Exceptions/CheckoutException.php
class CheckoutException (line 15) | class CheckoutException extends \Exception
FILE: src/Exceptions/GatewayException.php
class GatewayException (line 15) | class GatewayException extends \Exception
FILE: src/Exceptions/ShopException.php
class ShopException (line 15) | class ShopException extends \Exception
FILE: src/Gateways/GatewayCallback.php
class GatewayCallback (line 17) | class GatewayCallback extends GatewayPass
method onCharge (line 31) | public function onCharge($order)
method onCallbackSuccess (line 46) | public function onCallbackSuccess($order, $data = null)
method onCallbackFail (line 61) | public function onCallbackFail($order, $data = null)
method getCallbackSuccess (line 72) | public function getCallbackSuccess()
method getCallbackFail (line 81) | public function getCallbackFail()
method getDidCallback (line 90) | public function getDidCallback()
FILE: src/Gateways/GatewayFail.php
class GatewayFail (line 20) | class GatewayFail extends PaymentGateway
method onCheckout (line 27) | public function onCheckout($cart)
method onCharge (line 39) | public function onCharge($order)
FILE: src/Gateways/GatewayPass.php
class GatewayPass (line 18) | class GatewayPass extends PaymentGateway
method onCharge (line 27) | public function onCharge($order)
FILE: src/Http/Controllers/Controller.php
class Controller (line 9) | abstract class Controller extends BaseController
FILE: src/Http/Controllers/Shop/CallbackController.php
class CallbackController (line 7) | class CallbackController extends Controller
method process (line 16) | protected function process(Request $request)
FILE: src/LaravelShop.php
class LaravelShop (line 28) | class LaravelShop
method __construct (line 75) | public function __construct($app)
method user (line 88) | public function user()
method setGateway (line 96) | public static function setGateway($gatewayKey)
method getGateway (line 108) | public static function getGateway()
method checkout (line 123) | public static function checkout($cart = null)
method placeOrder (line 154) | public static function placeOrder($cart = null)
method callback (line 222) | public static function callback($order, $transaction, $status, $data =...
method format (line 267) | public static function format($value)
method gateway (line 289) | public static function gateway()
method exception (line 299) | public static function exception()
method setException (line 309) | protected static function setException($e)
method instanceGateway (line 319) | protected static function instanceGateway()
method checkStatusChange (line 332) | protected static function checkStatusChange($order, $prevStatusCode)
FILE: src/LaravelShopFacade.php
class LaravelShopFacade (line 17) | class LaravelShopFacade extends Facade
method getFacadeAccessor (line 24) | protected static function getFacadeAccessor()
FILE: src/LaravelShopProvider.php
class LaravelShopProvider (line 17) | class LaravelShopProvider extends ServiceProvider
method boot (line 32) | public function boot(Router $router)
method register (line 51) | public function register()
method registerShop (line 65) | private function registerShop()
method mergeConfig (line 77) | private function mergeConfig()
method registerCommands (line 89) | private function registerCommands()
method provides (line 101) | public function provides()
method map (line 114) | public function map(Router $router)
FILE: src/Models/ShopCartModel.php
class ShopCartModel (line 21) | class ShopCartModel extends Model implements ShopCartInterface
method __construct (line 45) | public function __construct(array $attributes = [])
FILE: src/Models/ShopCouponModel.php
class ShopCouponModel (line 20) | class ShopCouponModel extends Model implements ShopCouponInterface
method __construct (line 44) | public function __construct(array $attributes = [])
FILE: src/Models/ShopItemModel.php
class ShopItemModel (line 20) | class ShopItemModel extends Model implements ShopItemInterface
method __construct (line 58) | public function __construct(array $attributes = [])
method user (line 69) | public function user()
method cart (line 79) | public function cart()
method order (line 89) | public function order()
FILE: src/Models/ShopOrderModel.php
class ShopOrderModel (line 21) | class ShopOrderModel extends Model implements ShopOrderInterface
method __construct (line 45) | public function __construct(array $attributes = [])
FILE: src/Models/ShopTransactionModel.php
class ShopTransactionModel (line 20) | class ShopTransactionModel extends Model implements ShopTransactionInter...
method __construct (line 43) | public function __construct(array $attributes = [])
FILE: src/Traits/ShopCalculationsTrait.php
type ShopCalculationsTrait (line 21) | trait ShopCalculationsTrait
method getCountAttribute (line 34) | public function getCountAttribute()
method getTotalPriceAttribute (line 45) | public function getTotalPriceAttribute()
method getTotalTaxAttribute (line 56) | public function getTotalTaxAttribute()
method getTotalShippingAttribute (line 67) | public function getTotalShippingAttribute()
method getTotalDiscountAttribute (line 78) | public function getTotalDiscountAttribute() { /* TODO */ }
method getTotalAttribute (line 85) | public function getTotalAttribute()
method getDisplayTotalPriceAttribute (line 96) | public function getDisplayTotalPriceAttribute()
method getDisplayTotalTaxAttribute (line 106) | public function getDisplayTotalTaxAttribute()
method getDisplayTotalShippingAttribute (line 116) | public function getDisplayTotalShippingAttribute()
method getDisplayTotalDiscountAttribute (line 126) | public function getDisplayTotalDiscountAttribute() { /* TODO */ }
method getDisplayTotalAttribute (line 133) | public function getDisplayTotalAttribute()
method getCalculationsCacheKeyAttribute (line 143) | public function getCalculationsCacheKeyAttribute()
method runCalculations (line 151) | private function runCalculations()
method resetCalculations (line 189) | private function resetCalculations ()
FILE: src/Traits/ShopCartTrait.php
type ShopCartTrait (line 21) | trait ShopCartTrait
method boot (line 36) | public static function boot()
method user (line 54) | public function user()
method items (line 64) | public function items()
method add (line 75) | public function add($item, $quantity = 1, $quantityReset = false)
method remove (line 133) | public function remove($item, $quantity = 0)
method hasItem (line 158) | public function hasItem($sku, $requireAll = false)
method scopeWhereUser (line 194) | public function scopeWhereUser($query, $userId)
method scopeWhereCurrent (line 206) | public function scopeWhereCurrent($query)
method scopeCurrent (line 219) | public function scopeCurrent($query)
method scopeFindByUser (line 238) | public function scopeFindByUser($query, $userId)
method placeOrder (line 258) | public function placeOrder($statusCode = null)
method clear (line 282) | public function clear()
method getItem (line 298) | private function getItem($sku)
FILE: src/Traits/ShopCouponTrait.php
type ShopCouponTrait (line 18) | trait ShopCouponTrait
method scopeWhereCode (line 26) | public function scopeWhereCode($query, $code)
method scopeFindByCode (line 36) | public function scopeFindByCode($query, $code)
FILE: src/Traits/ShopItemTrait.php
type ShopItemTrait (line 20) | trait ShopItemTrait
method getHasObjectAttribute (line 28) | public function getHasObjectAttribute()
method getIsShoppableAttribute (line 38) | public function getIsShoppableAttribute()
method getObjectAttribute (line 48) | public function getObjectAttribute()
method getDisplayNameAttribute (line 58) | public function getDisplayNameAttribute()
method getShopIdAttribute (line 74) | public function getShopIdAttribute()
method getShopUrlAttribute (line 84) | public function getShopUrlAttribute()
method getDisplayPriceAttribute (line 100) | public function getDisplayPriceAttribute()
method scopeWhereSKU (line 113) | public function scopeWhereSKU($query, $sku)
method scopeFindBySKU (line 127) | public function scopeFindBySKU($query, $sku)
method getDisplayTaxAttribute (line 137) | public function getDisplayTaxAttribute()
method getDisplayShippingAttribute (line 147) | public function getDisplayShippingAttribute()
method getWasPurchasedAttribute (line 157) | public function getWasPurchasedAttribute()
FILE: src/Traits/ShopOrderTrait.php
type ShopOrderTrait (line 18) | trait ShopOrderTrait
method boot (line 27) | public static function boot()
method user (line 45) | public function user()
method items (line 55) | public function items()
method transactions (line 65) | public function transactions()
method getIsLockedAttribute (line 76) | public function getIsLockedAttribute() {
method scopeWhereUser (line 89) | public function scopeWhereUser($query, $userId) {
method scopeWhereSKU (line 102) | public function scopeWhereSKU($query, $sku) {
method scopeWhereStatus (line 121) | public function scopeWhereStatus($query, $statusCode) {
method scopeWhereStatusIn (line 133) | public function scopeWhereStatusIn($query, array $statusCodes) {
method scopeFindByUser (line 147) | public function scopeFindByUser($query, $userId, $statusCode = null) {
method is (line 161) | public function is($statusCode)
method getIsCompletedAttribute (line 171) | public function getIsCompletedAttribute()
method getHasFailedAttribute (line 181) | public function getHasFailedAttribute()
method getIsCanceledAttribute (line 191) | public function getIsCanceledAttribute()
method getIsInProcessAttribute (line 201) | public function getIsInProcessAttribute()
method getIsInCreationAttribute (line 211) | public function getIsInCreationAttribute()
method getIsPendingAttribute (line 221) | public function getIsPendingAttribute()
method placeTransaction (line 235) | public function placeTransaction($gateway, $transactionId, $detail = n...
method getItem (line 253) | private function getItem($sku)
FILE: src/Traits/ShopTransactionTrait.php
type ShopTransactionTrait (line 18) | trait ShopTransactionTrait
method order (line 25) | public function order()
method scopeWhereUser (line 35) | public function scopeWhereUser($query, $userId)
FILE: src/Traits/ShopUserTrait.php
type ShopUserTrait (line 18) | trait ShopUserTrait
method cart (line 26) | public function cart()
method items (line 36) | public function items()
method orders (line 46) | public function orders()
method getShopIdAttribute (line 56) | public function getShopIdAttribute()
FILE: tests/ShopTest.php
class ShopTest (line 11) | class ShopTest extends TestCase
method testStaticMethods (line 17) | public function testStaticMethods()
method testConstants (line 25) | public function testConstants()
FILE: tests/cart/CartTest.php
class CartTest (line 12) | class CartTest extends TestCase
method setUp (line 23) | public function setUp()
method testCreationBasedOnUser (line 35) | public function testCreationBasedOnUser()
method testMultipleCurrentCalls (line 49) | public function testMultipleCurrentCalls()
method testCreationBasedOnNull (line 71) | public function testCreationBasedOnNull()
method testCreationBasedOnAuthUser (line 81) | public function testCreationBasedOnAuthUser()
method testAddingRemovingItems (line 92) | public function testAddingRemovingItems()
method testCartMethods (line 137) | public function testCartMethods()
method testOrderPlacement (line 168) | public function testOrderPlacement()
method tearDown (line 190) | public function tearDown()
FILE: tests/cart/ItemTest.php
class ItemTest (line 12) | class ItemTest extends TestCase
method testItemMethodsAndAttributes (line 17) | public function testItemMethodsAndAttributes()
method testItemInCart (line 50) | public function testItemInCart()
method testPurchasedItemAttribute (line 95) | public function testPurchasedItemAttribute()
FILE: tests/gateway/CallbackTest.php
class CallbackTest (line 10) | class CallbackTest extends TestCase
method setUp (line 31) | public function setUp()
method tearDown (line 52) | public function tearDown()
method testSuccessCallback (line 64) | public function testSuccessCallback()
method testFailCallback (line 84) | public function testFailCallback()
FILE: tests/order/PurchaseTest.php
class PurchaseTest (line 12) | class PurchaseTest extends TestCase
method testGateway (line 17) | public function testGateway()
method testUnselectedGateway (line 32) | public function testUnselectedGateway()
method testPurchaseFlow (line 42) | public function testPurchaseFlow()
method testFailPurchase (line 72) | public function testFailPurchase()
method testFailedTransactions (line 105) | public function testFailedTransactions()
Condensed preview — 51 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (178K chars).
[
{
"path": ".gitignore",
"chars": 21,
"preview": "/vendor\ncomposer.lock"
},
{
"path": "LICENSE",
"chars": 1081,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Amsgames, LLC\n\nPermission is hereby granted, free of charge, to any person obt"
},
{
"path": "README.md",
"chars": 33292,
"preview": "ITwrx fork of LARAVEL SHOP (minor changes for Laravel 5.2 Compatibility)\n--------------------------------\n\n[![Latest Sta"
},
{
"path": "composer.json",
"chars": 1167,
"preview": "{\n \"name\": \"ITwrx/laravel-shop\",\n \"description\": \"Package set to provide shop or e-commerce functionality (such as"
},
{
"path": "composer.lock.bk",
"chars": 19225,
"preview": "{\n \"_readme\": [\n \"This file locks the dependencies of your project to a known state\",\n \"Read more about"
},
{
"path": "src/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "src/Commands/MigrationCommand.php",
"chars": 4772,
"preview": "<?php \n\nnamespace Amsgames\\LaravelShop;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n *\n * "
},
{
"path": "src/Config/config.php",
"chars": 9034,
"preview": "<?php\n\n/**\n * This file is part of Amsgames\\LaravelShop,\n * Shop functionality for Laravel.\n *\n * @copyright Amsgames, L"
},
{
"path": "src/Contracts/PaymentGatewayInterface.php",
"chars": 1884,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Contracts;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Larave"
},
{
"path": "src/Contracts/ShopCartInterface.php",
"chars": 3891,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Contracts;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Larave"
},
{
"path": "src/Contracts/ShopCouponInterface.php",
"chars": 561,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Contracts;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Larave"
},
{
"path": "src/Contracts/ShopItemInterface.php",
"chars": 1832,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Contracts;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Larave"
},
{
"path": "src/Contracts/ShopOrderInterface.php",
"chars": 4296,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Contracts;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Larave"
},
{
"path": "src/Contracts/ShopTransactionInterface.php",
"chars": 621,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Contracts;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Larave"
},
{
"path": "src/Core/PaymentGateway.php",
"chars": 4325,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Core;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n *"
},
{
"path": "src/Events/CartCheckout.php",
"chars": 758,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Events;\n\nuse Illuminate\\Queue\\SerializesModels;\n\n/**\n * Event fired when an order "
},
{
"path": "src/Events/OrderCompleted.php",
"chars": 535,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Events;\n\nuse Illuminate\\Queue\\SerializesModels;\n\n/**\n * Event fired when an order "
},
{
"path": "src/Events/OrderPlaced.php",
"chars": 523,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Events;\n\nuse Illuminate\\Queue\\SerializesModels;\n\n/**\n * Event fired when an order "
},
{
"path": "src/Events/OrderStatusChanged.php",
"chars": 936,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Events;\n\nuse Illuminate\\Queue\\SerializesModels;\n\n/**\n * Event fired when an order "
},
{
"path": "src/Exceptions/CheckoutException.php",
"chars": 362,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Exceptions;\n\n/**\n * This class is the main entry point of laravel shop. Usually th"
},
{
"path": "src/Exceptions/GatewayException.php",
"chars": 361,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Exceptions;\n\n/**\n * This class is the main entry point of laravel shop. Usually th"
},
{
"path": "src/Exceptions/ShopException.php",
"chars": 358,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Exceptions;\n\n/**\n * This class is the main entry point of laravel shop. Usually th"
},
{
"path": "src/Gateways/GatewayCallback.php",
"chars": 1963,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Gateways;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel"
},
{
"path": "src/Gateways/GatewayFail.php",
"chars": 939,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Gateways;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel"
},
{
"path": "src/Gateways/GatewayPass.php",
"chars": 576,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Gateways;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel"
},
{
"path": "src/Http/Controllers/Controller.php",
"chars": 308,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Http\\Controllers;\n\nuse Illuminate\\Foundation\\Bus\\DispatchesJobs;\nuse Illuminate\\Ro"
},
{
"path": "src/Http/Controllers/Shop/CallbackController.php",
"chars": 1485,
"preview": "<?php\nnamespace Amsgames\\LaravelShop\\Http\\Controllers\\Shop;\nuse Validator;\nuse Shop;\nuse Illuminate\\Http\\Request;\nuse Am"
},
{
"path": "src/LaravelShop.php",
"chars": 9732,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop;\n\n/**\n * This class is the main entry point of laravel shop. Usually this the inte"
},
{
"path": "src/LaravelShopFacade.php",
"chars": 489,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n *\n * @"
},
{
"path": "src/LaravelShopProvider.php",
"chars": 2737,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop;\n\n/**\n * Service provider for laravel.\n *\n * @author Alejandro Mostajo\n * @copyrig"
},
{
"path": "src/Models/ShopCartModel.php",
"chars": 1088,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Models;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Models/ShopCouponModel.php",
"chars": 1084,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Models;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Models/ShopItemModel.php",
"chars": 2182,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Models;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Models/ShopOrderModel.php",
"chars": 1108,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Models;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Models/ShopTransactionModel.php",
"chars": 1099,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Models;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Traits/ShopCalculationsTrait.php",
"chars": 5524,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Traits;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Traits/ShopCartTrait.php",
"chars": 9496,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Traits;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Traits/ShopCouponTrait.php",
"chars": 741,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Traits;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Traits/ShopItemTrait.php",
"chars": 4113,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Traits;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Traits/ShopOrderTrait.php",
"chars": 6948,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Traits;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Traits/ShopTransactionTrait.php",
"chars": 1095,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Traits;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/Traits/ShopUserTrait.php",
"chars": 1313,
"preview": "<?php\n\nnamespace Amsgames\\LaravelShop\\Traits;\n\n/**\n * This file is part of LaravelShop,\n * A shop solution for Laravel.\n"
},
{
"path": "src/views/generators/migration.blade.php",
"chars": 5388,
"preview": "<?php echo '<?php' ?>\n\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\n\nclass Sh"
},
{
"path": "src/views/generators/seeder.blade.php",
"chars": 1321,
"preview": "<?php echo '<?php' ?>\n\nuse Illuminate\\Database\\Seeder;\nuse Illuminate\\Database\\Eloquent\\Model;\n\n/**\n * Seeds database wi"
},
{
"path": "tests/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "tests/README.md",
"chars": 3699,
"preview": "# Test Case Configuration\n\nIn order to run test cases you must setup your laravel package development environment and cr"
},
{
"path": "tests/ShopTest.php",
"chars": 562,
"preview": "<?php\n\nuse App;\nuse Log;\nuse Shop;\nuse Amsgames\\LaravelShop;\nuse Illuminate\\Foundation\\Testing\\WithoutMiddleware;\nuse Il"
},
{
"path": "tests/cart/CartTest.php",
"chars": 3740,
"preview": "<?php\n\nuse App;\nuse Auth;\nuse Hash;\nuse Log;\nuse Shop;\nuse Illuminate\\Foundation\\Testing\\WithoutMiddleware;\nuse Illumina"
},
{
"path": "tests/cart/ItemTest.php",
"chars": 2585,
"preview": "<?php\n\nuse App;\nuse Auth;\nuse Hash;\nuse Shop;\nuse Log;\nuse Illuminate\\Foundation\\Testing\\WithoutMiddleware;\nuse Illumina"
},
{
"path": "tests/gateway/CallbackTest.php",
"chars": 1783,
"preview": "<?php\n\nuse App;\nuse Shop;\nuse Log;\nuse Illuminate\\Foundation\\Testing\\WithoutMiddleware;\nuse Illuminate\\Foundation\\Testin"
},
{
"path": "tests/order/PurchaseTest.php",
"chars": 2892,
"preview": "<?php\n\nuse App;\nuse Auth;\nuse Hash;\nuse Log;\nuse Shop;\nuse Illuminate\\Foundation\\Testing\\WithoutMiddleware;\nuse Illumina"
}
]
About this extraction
This page contains the full source code of the amsgames/laravel-shop GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 51 files (161.9 KB), approximately 40.7k tokens, and a symbol index with 252 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.