PHP code example of enea / laravel-cashier

1. Go to this page and download the library: Download enea/laravel-cashier library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

enea / laravel-cashier example snippets


// create a shopping cart
$document = Invoice::create()->using([Taxes::IVA]);
$shoppingCart = ShoppingManager::initialize($client, $document);

// add a global discount
$discount = Discount::percentage(15)->setCode('PROMOTIONAL');
$shoppingCart->addDiscount($discount);

// add products
$keyboard = $shoppingCart->push(Product::find(1), 5);
$keyboard->addDiscount(Discount::percentage(8)->setCode('ONLY-TODAY'));

$backpack = $shoppingCart->push(Product::find(2));
$backpack->setQuantity(10);

// get totals
$shoppingCart->getSubtotal();
$shoppingCart->getTotalDiscounts();
$shoppingCart->getTotalTaxes();
$shoppingCart->getTotal();

use App\Client;
use Enea\Cashier\Documents\Invoice;
use Enea\Cashier\Facades\ShoppingManager;

$document = Invoice::create()->using([Taxes::IVA]); // or use your own model
$shoppingCart = ShoppingManager::initialize(Client::find(10), $document);

$token = $shoppingCart->getGeneratedToken();
$shoppingCart = ShoppingManager::find($token); // returns the shopping cart that matches the token

$shoppingCart->attach($quote);

$keyboard = Product::query()->where('description', 'Keyboard K530-rgb')->firstOrFail();
$productCartItem = $shoppingCart->push($keyboard, 4);

$productCartItem = $shoppingCart->pull($productID);

// set product quantity
$productCartItem->setQuantity(10);

// configure custom properties
$productCartItem->setProperty(['key' => 'value']);
$productCartItem->putProperty('key', 'value');
$productCartItem->removeProperty('key');

// manage discounts
$productCartItem->addDiscounts($discounts);
$productCartItem->addDiscount($discount);
$productCartItem->getDiscount($discountCode);
$productCartItem->removeDiscount($discountCode);

// get the totals
$cashier = $productCartItem->getCashier();
$cashier->getUnitPrice();
$cashier->getGrossUnitPrice();
$cashier->getNetUnitPrice();
$cashier->getQuantity();
$cashier->getSubtotal();
$cashier->getTotalDiscounts();
$cashier->getTotalTaxes();
$cashier->getTotal();

class ShoppingCartController extends Controller
{
  public function start(Client $client): JsonResponse
  {
    $shoppingCart = ShoppingManager::initialize($client);        
    $shoppingCart->setDocument(Invoice::create()->using([Taxes::IGV])); 

    return response()->json([
      'token' => $shoppingCart->getGeneratedToken(),
      'shoppingCart' => $shoppingCart->toArray()
    ]);
  }

  public function addGlobalDiscount(Discount $discount, Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $shoppingCart->addDiscount($discount);

    return response()->json(compact('shoppingCart'));
  }

  public function removeGlobalDiscount(Discount $discount, Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $shoppingCart->removeDiscount($discount->getDiscountCode());

    return response()->json(compact('shoppingCart'));
  }
}

class ProductManagerController extends Controller
{
  public function addProduct(Product $product, Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $added = $shoppingCart->push($product, $request->get('quantity'));

    return response()->json(compact('shoppingCart', 'added'));
  }

  public function removeProduct(string $productID, Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $shoppingCart->remove($productID);

    return response()->json(compact('shoppingCart'));
  }

  public function updateProductQuantity(string $productID, Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $product = $shoppingCart->find($productID);
    $product->setQuantity($request->get('quantity'));

    return response()->json(compact('shoppingCart', 'product'));
  }

  public function addDiscountToProduct(string $productID, Discount $discount, Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $product = $shoppingCart->find($productID);
    $product->addDiscount($discount);

    return response()->json(compact('shoppingCart'));
  }  

  public function removeDiscountToProduct(string $productID, Discount $discount, Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $product = $shoppingCart->find($productID);
    $product->removeDiscount($discount);

    return response()->json(compact('shoppingCart'));
  }
}

class PurchaseController extends Controller
{
  public function store(Request $request): JsonResponse
  {
    $shoppingCart = ShoppingManager::find($request->header('CART-TOKEN'));
    $products = $shoppingCart->collection()->map($this->toOrderProduct());

    $order = DB::Transaction($this->createOrder($shoppingCart, $products));
    $dropped = $this->destroyShoppingCart($shoppingCart->getGeneratedToken());

    return response()->json(compact('order', 'dropped'));
  }

  private function createOrder(ShoppingCart $cart, Collection $products): Closure
  {
    return function() use ($cart, $products): Order {
      $order = Order::create([
        // complete the structure of your model
        'subtotal' => $cart->getSubtotal(),
        'total' => $cart->getTotal(),
        'document_id'd => $cart->getDocument()->getUniqueIdentificationKey(),
      ]);                
      $order->detail()->saveMany($products);    
      return $order;
    };            
  }

  private function toOrderProduct(): Closure
  {
    return fn(ProductCartItem $product) => new OrderProduct([
      'product_id' => $product->getUniqueIdentificationKey(),
      'quantity' => $product->getQuantity(),
      'unit_price' => $product->getCashier()->getUnitPrice(),
      'discount' => $product->getCashier()->getTotalDiscounts(),
      'iva_pct' =>  $product->getTax('IVA')->getPercentage(),
    ]);
  }

  private function destroyShoppingCart(string $token): bool
  {
    ShoppingManager::drop($token);
    return !ShoppingManager::has($token);
  }
}

  namespace Enea\Cashier\Modifiers;
  
  use Enea\Cashier\Calculations\Percentager;
  use Enea\Cashier\Modifiers\DiscountContract;
  
  class Discount implements DiscountContract
  {
      public function getDiscountCode(): string
      {
          return $this->code;
      }
  
      public function getDescription(): string
      {
          return $this->description;
      }
  
      public function extract(float $total): float
      {
          if (! $this->percentage) {
              return $this->discount;
          }
  				// logic to calculate a percentage discount
          return Percentager::excluded($total, $this->discount)->calculate();
      }
  }
  

  namespace App\Models;
  
  use Enea\Cashier\Taxes;
  use Enea\Cashier\Contracts\DocumentContract;
  use Illuminate\Database\Eloquent\Model;
  
  class Document extends Model implements DocumentContract
  {
      public function taxesToUse(): array
      {
        	// some logic
          return [
            Taxes::IGV, // tax name
          ];
      }
  }
  

  namespace App\Models;
  
  use Enea\Cashier\Contracts\ProductContract;
  use Enea\Cashier\Modifiers\Tax;
  use Enea\Cashier\Taxes;
  
  class Product extends Model implements ProductContract
  {
      public function getUnitPrice(): float
      {
          return $this->sale_price;
      }
  
      public function getShortDescription(): string
      {
          return $this->short_description;
      }
  
      public function getTaxes(): array
      {
          return [
              Tax::