frontend & backend update

This commit is contained in:
carodej
2020-06-22 16:46:02 +02:00
parent a2cab6198e
commit a2dfc627a7
35 changed files with 595 additions and 1080 deletions

View File

@@ -3,33 +3,44 @@
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Resources\InvoiceCollection;
use App\Http\Resources\InvoiceAdminCollection;
use App\Http\Resources\InvoiceResource;
use App\Invoice;
use App\Services\StripeService;
use Illuminate\Http\Request;
class InvoiceController extends Controller
{
/**
* PlanController constructor.
*/
public function __construct(StripeService $stripe)
{
$this->stripe = $stripe;
}
/**
* Get all invoices
*
* @return InvoiceCollection
* @return InvoiceAdminCollection
*/
public function index()
{
return new InvoiceCollection(
Invoice::all()
return new InvoiceAdminCollection(
$this->stripe->getInvoices()['data']
);
}
/**
* Get single invoice by $token
*
* @param $customer
* @param $token
* @return InvoiceResource
*/
public function show($token)
public function show($customer, $token)
{
$invoice = Invoice::where('token', $token)->firstOrFail();
$invoice = $this->stripe->getUserInvoice($customer, $token);
return view('vuefilemanager.invoice')
->with('invoice', $invoice);

View File

@@ -11,6 +11,7 @@ use App\Plan;
use App\Services\StripeService;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Rinvex\Subscriptions\Models\PlanFeature;
class PlanController extends Controller
@@ -30,9 +31,18 @@ class PlanController extends Controller
*/
public function index()
{
return new PlanCollection(
$this->stripe->getPlans()
);
// Store or Get plans to cache
if (Cache::has('plans')) {
$plans = Cache::get('plans');
} else {
$plans = Cache::rememberForever('plans', function () {
return $this->stripe->getPlans();
});
}
return new PlanCollection($plans);
}
/**
@@ -43,9 +53,18 @@ class PlanController extends Controller
*/
public function show($id)
{
return new PlanResource(
$this->stripe->getPlan($id)
);
// Store or Get plan to cache
if (Cache::has('plan-' . $id)) {
$plan = Cache::get('plan-' . $id);
} else {
$plan = Cache::rememberForever('plan-' . $id, function () use ($id) {
return $this->stripe->getPlan($id);
});
}
return new PlanResource($plan);
}
/**
@@ -56,9 +75,14 @@ class PlanController extends Controller
*/
public function store(Request $request)
{
return new PlanResource(
$plan = new PlanResource(
$this->stripe->createPlan($request)
);
// Clear cached plans
cache_forget_many(['plans', 'pricing']);
return $plan;
}
/**
@@ -72,6 +96,9 @@ class PlanController extends Controller
{
$this->stripe->updatePlan($request, $id);
// Clear cached plans
cache_forget_many(['plans', 'pricing', 'plan-' . $id]);
return response('Saved!', 204);
}
@@ -85,6 +112,9 @@ class PlanController extends Controller
{
$this->stripe->deletePlan($id);
// Clear cached plans
cache_forget_many(['plans', 'pricing']);
return response('Done!', 204);
}

View File

@@ -15,6 +15,7 @@ use App\Http\Resources\UserResource;
use App\Http\Resources\UserStorageResource;
use App\Http\Resources\UserSubscription;
use App\Http\Tools\Demo;
use App\Services\StripeService;
use App\Share;
use App\User;
use App\UserSettings;
@@ -29,6 +30,11 @@ use Storage;
class UserController extends Controller
{
public function __construct(StripeService $stripe)
{
$this->stripe = $stripe;
}
/**
* Get user details
*
@@ -58,13 +64,14 @@ class UserController extends Controller
/**
* Get user storage details
*
* @param $id
* @return InvoiceCollection
*/
public function invoices($id)
public function invoices()
{
$user = \Auth::user();
return new InvoiceCollection(
User::findOrFail($id)->invoices
$this->stripe->getUserInvoices($user)
);
}
@@ -77,7 +84,7 @@ class UserController extends Controller
public function subscription($id)
{
return new UserSubscription(
User::findOrFail($id)->subscription('main')
User::find($id)
);
}

View File

@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Http\Resources\PricingCollection;
use App\Services\StripeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class PricingController extends Controller
{
@@ -24,10 +25,22 @@ class PricingController extends Controller
*/
public function index()
{
$collection = new PricingCollection(
$this->stripe->getActivePlans()
);
if (Cache::has('pricing')) {
// Get pricing from cache
$pricing = Cache::get('pricing');
} else {
// Store pricing to cache
$pricing = Cache::rememberForever('pricing', function () {
return $this->stripe->getActivePlans();
});
}
// Format pricing to collection
$collection = new PricingCollection($pricing);
// Sort and return pricing
return $collection->sortBy('product.metadata.capacity')
->values()
->all();

View File

@@ -44,9 +44,14 @@ class AccountController extends Controller
);
}
/**
* Get user invoices
*
* @return InvoiceCollection
*/
public function invoices() {
return new InvoiceCollection(
Auth::user()->invoices
Auth::user()->invoices()
);
}

View File

@@ -1,107 +0,0 @@
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\PaymentCardCollection;
use App\Http\Resources\PaymentCardResource;
use App\Http\Resources\PaymentDefaultCardResource;
use App\Services\PaymentService;
use App\UserCard;
use Auth;
use Illuminate\Http\Request;
use Laravel\Cashier\PaymentMethod;
class PaymentCardsController extends Controller
{
/**
* @var PaymentService
*/
private $payment;
/**
* PaymentCardsController constructor.
*/
public function __construct(PaymentService $payment)
{
$this->payment = $payment;
}
/**
* Update card detail
*
* @param Request $request
* @param $id
*/
public function update(Request $request, $id)
{
$user = Auth::user();
// Update DefaultPayment Method
$user->updateDefaultPaymentMethod($id);
// Sync default payment method
$user->updateDefaultPaymentMethodFromStripe();
}
/**
* Delete user credit card
*
*/
public function delete($id)
{
$user = Auth::user();
// Get payment method
$paymentMethod = $user->findPaymentMethod($id);
// Delete payment method
$paymentMethod->delete();
// Sync default payment method
$user->updateDefaultPaymentMethodFromStripe();
return response('Done!', 204);
}
/**
* Get user payment methods sorted by default and others
*
* @return array
*/
public function payment_methods()
{
$user = Auth::user();
// Get default payment method
$defaultPaymentMethodObject = $user->defaultPaymentMethod();
$defaultPaymentMethod = $defaultPaymentMethodObject instanceof PaymentMethod
? $defaultPaymentMethodObject->asStripePaymentMethod()
: $defaultPaymentMethodObject;
// filter payment methods without default payment
$paymentMethods = $user->paymentMethods()->filter(function ($paymentMethod) use ($defaultPaymentMethod) {
return $paymentMethod->id !== $defaultPaymentMethod->id;
});
// Get payment methods
$paymentMethodsMapped = $paymentMethods->map(function ($paymentMethod) {
return $paymentMethod->asStripePaymentMethod();
})->values()->all();
if (is_null($paymentMethodsMapped) && is_null($paymentMethodsMapped)) {
return [
'default' => null,
'others' => [],
];
}
return [
'default' => $defaultPaymentMethod instanceof PaymentMethod
? new PaymentCardResource($defaultPaymentMethod)
: new PaymentDefaultCardResource($defaultPaymentMethod),
'others' => new PaymentCardCollection($paymentMethodsMapped),
];
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\PaymentCardCollection;
use App\Http\Resources\PaymentCardResource;
use App\Http\Resources\PaymentDefaultCardResource;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Laravel\Cashier\PaymentMethod;
class PaymentMethodsController extends Controller
{
/**
* Get user payment methods grouped by default and others
*
* @return array
*/
public function payment_methods()
{
$user = Auth::user();
$slug_payment_methods = 'payment-methods-user-' . $user->id;
$slug_default_payment_method = 'default-payment-methods-user-' . $user->id;
if (Cache::has($slug_payment_methods) && Cache::has($slug_default_payment_method)) {
$defaultPaymentMethod = Cache::get($slug_default_payment_method);
$paymentMethodsMapped = Cache::get($slug_payment_methods);
} else {
// Get default payment method
$defaultPaymentMethod = Cache::rememberForever($slug_default_payment_method, function () use ($user) {
$defaultPaymentMethodObject = $user->defaultPaymentMethod();
return $defaultPaymentMethodObject instanceof PaymentMethod
? $defaultPaymentMethodObject->asStripePaymentMethod()
: $defaultPaymentMethodObject;
});
// filter payment methods without default payment
$paymentMethodsMapped = Cache::rememberForever($slug_payment_methods, function () use ($defaultPaymentMethod, $user) {
$paymentMethods = $user->paymentMethods()->filter(function ($paymentMethod) use ($defaultPaymentMethod) {
return $paymentMethod->id !== $defaultPaymentMethod->id;
});
// Get payment methods
return $paymentMethods->map(function ($paymentMethod) {
return $paymentMethod->asStripePaymentMethod();
})->values()->all();
});
}
if (! $user->card_brand || ! $user->stripe_id || is_null($paymentMethodsMapped) && is_null($paymentMethodsMapped)) {
return [
'default' => null,
'others' => [],
];
}
return [
'default' => $defaultPaymentMethod instanceof PaymentMethod
? new PaymentCardResource($defaultPaymentMethod)
: new PaymentDefaultCardResource($defaultPaymentMethod),
'others' => new PaymentCardCollection($paymentMethodsMapped),
];
}
/**
* Update default payment method
*
* @param Request $request
* @param $id
*/
public function update(Request $request, $id)
{
$user = Auth::user();
// Update DefaultPayment Method
$user->updateDefaultPaymentMethod($id);
// Sync default payment method
$user->updateDefaultPaymentMethodFromStripe();
// Clear cached payment methods
cache_forget_many([
'payment-methods-user-' . $user->id,
'default-payment-methods-user-' . $user->id
]);
}
/**
* Delete user payment method
*
*/
public function delete($id)
{
$user = Auth::user();
// Get payment method
$paymentMethod = $user->findPaymentMethod($id);
// Delete payment method
$paymentMethod->delete();
// Sync default payment method
$user->updateDefaultPaymentMethodFromStripe();
// Clear cached payment methods
cache_forget_many([
'payment-methods-user-' . $user->id,
'default-payment-methods-user-' . $user->id
]);
return response('Done!', 204);
}
}

View File

@@ -6,12 +6,12 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\Subscription\StoreUpgradeAccountRequest;
use App\Http\Resources\UserSubscription;
use App\Invoice;
use App\Services\PaymentService;
use App\Services\StripeService;
use Auth;
use Cartalyst\Stripe\Exception\CardErrorException;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Laravel\Cashier\Exceptions\IncompletePayment;
use Symfony\Component\HttpKernel\Exception\HttpException;
@@ -35,21 +35,29 @@ class SubscriptionController extends Controller
*/
public function stripe_setup_intent()
{
// Get user
$user = Auth::user();
// Create stripe customer if not exist
$user->createOrGetStripeCustomer();
// Return setup intent
return $user->createSetupIntent();
return $this->stripe->getSetupIntent($user);
}
/**
* Get user subscription detail
*
* @return UserSubscription
*/
public function show()
{
return new UserSubscription(
Auth::user()
);
$slug_user_subscription = 'subscription-user-' . Auth::id();
if (Cache::has($slug_user_subscription)) {
return Cache::get($slug_user_subscription);
}
return Cache::rememberForever($slug_user_subscription, function () {
return new UserSubscription(
Auth::user()
);
});
}
/**
@@ -69,6 +77,9 @@ class SubscriptionController extends Controller
// Set user billing
$user->setBilling($request->input('billing'));
// Update stripe customer billing info
$this->stripe->updateCustomerDetails($user);
// Make subscription
$this->stripe->createOrReplaceSubscription($request, $user);
@@ -77,9 +88,6 @@ class SubscriptionController extends Controller
'storage_capacity' => $plan['product']['metadata']['capacity']
]);
// Store invoice
Invoice::create(get_invoice_data($user, $plan, 'stripe'));
return response('Done!', 204);
}

View File

@@ -27,55 +27,11 @@ function get_invoice_number()
}
}
/**
* Get data to render in invoice tempalte
* @param $user
* @param $plan
* @param $provider
* @return array
*/
function get_invoice_data($user, $plan, $provider)
function cache_forget_many($cache)
{
$subscription = $user->subscription('main');
$order_number = get_invoice_number();
$token = \Illuminate\Support\Str::random(22);
return [
'token' => $token,
'order' => $order_number,
'provider' => $provider,
'user_id' => $user->id,
'plan_id' => $plan['plan']['id'],
'total' => $plan['plan']['amount'],
'currency' => 'USD',
'bag' => [
[
'description' => 'Subscription - ' . $plan['product']['name'],
//'date' => format_date($subscription->starts_at, '%d. %B. %Y') . ' - ' . format_date($subscription->ends_at, '%d. %B. %Y'),
'date' => format_date(Carbon::now(),'%d. %B. %Y'),
'amount' => $plan['plan']['amount'],
]
],
'seller' => [
'billing_name' => 'VueFileManager',
'billing_address' => 'Somewhere 32',
'billing_state' => 'Washington',
'billing_city' => 'Manchester',
'billing_postal_code' => '04001',
'billing_country' => 'The USA',
'billing_phone_number' => '490321-6354774',
'billing_vat_number' => '7354724626246',
],
'client' => [
'billing_name' => $user->settings->billing_name,
'billing_address' => $user->settings->billing_address,
'billing_state' => $user->settings->billing_state,
'billing_city' => $user->settings->billing_city,
'billing_postal_code' => $user->settings->billing_postal_code,
'billing_country' => $user->settings->billing_country,
'billing_phone_number' => $user->settings->billing_phone_number,
],
];
foreach ($cache as $item) {
\Illuminate\Support\Facades\Cache::forget($item);
}
}
/**

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class InvoiceAdminCollection extends ResourceCollection
{
public $collects = InvoiceAdminResource::class;
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection,
];
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Http\Resources;
use App\User;
use Illuminate\Http\Resources\Json\JsonResource;
use Laravel\Cashier\Cashier;
class InvoiceAdminResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$user = User::where('stripe_id', $this['customer'])->first();
return [
'data' => [
'id' => $this['id'],
'type' => 'invoices',
'attributes' => [
'customer' => $this['customer'],
'total' => Cashier::formatAmount($this['total']),
'currency' => $this['currency'],
'created_at_formatted' => format_date($this['created']),
'created_at' => $this['created'],
'order' => $this['number'],
'user_id' => $user ? $user->id : null,
'client' => [
'billing_address' => $this['customer_address'],
'billing_name' => $this['customer_name'],
'billing_phone_number' => $this['customer_phone'],
],
'bag' => [
'amount' => $this['lines']['data'][0]['amount'],
'currency' => $this['lines']['data'][0]['currency'],
'type' => $this['lines']['data'][0]['type'],
'description' => $this['lines']['data'][0]['description'],
],
'seller' => null,
]
],
$this->mergeWhen($user, function () use ($user) {
return [
'relationships' => [
'user' => [
'data' => [
'id' => (string)$user->id,
'type' => 'user',
'attributes' => [
'name' => $user->name,
'avatar' => $user->avatar,
]
]
]
]
];
}),
];
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Http\Resources;
use App\User;
use Illuminate\Http\Resources\Json\JsonResource;
class InvoiceResource extends JsonResource
@@ -14,38 +15,49 @@ class InvoiceResource extends JsonResource
*/
public function toArray($request)
{
$user = User::where('stripe_id', $this->customer)->first();
$subscription = $this->subscriptions()[0];
return [
'data' => [
'id' => (string)$this->id,
'data' => [
'id' => $this->id,
'type' => 'invoices',
'attributes' => [
'token' => $this->token,
'order' => $this->order,
'user_id' => $this->user_id,
'plan_id' => $this->plan_id,
'notes' => $this->notes,
'total' => $this->total,
'customer' => $this->customer,
'total' => $this->total(),
'currency' => $this->currency,
'seller' => $this->seller,
'client' => $this->client,
'bag' => $this->bag,
'created_at_formatted' => format_date($this->created_at),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'created_at_formatted' => format_date($this->date()),
'created_at' => $this->created,
'order' => $this->number,
'user_id' => $user ? $user->id : null,
'client' => [
'billing_address' => $this->customer_address,
'billing_name' => $this->customer_name,
'billing_phone_number' => $this->customer_phone,
],
'bag' => [
'amount' => $subscription->amount,
'currency' => $subscription->currency,
'type' => $subscription->type,
'description' => $subscription->description,
],
'seller' => null,
]
],
'relationships' => [
'user' => [
'data' => [
'id' => (string)$this->user->id,
'type' => 'user',
'attributes' => [
'name' => $this->user->name,
'avatar' => $this->user->avatar,
$this->mergeWhen($user, [
'relationships' => [
'user' => [
'data' => [
'id' => (string)$user->id,
'type' => 'user',
'attributes' => [
'name' => $user->name,
'avatar' => $user->avatar,
]
]
]
]
]
]),
];
}
}

View File

@@ -26,18 +26,19 @@ class UserResource extends JsonResource
'id' => (string)$this->id,
'type' => 'user',
'attributes' => [
'subscription' => $this->subscribed('main'),
'stripe_customer' => is_null($this->stripe_id) ? false : true,
'name' => env('APP_DEMO') ? $faker->name : $this->name,
'email' => env('APP_DEMO') ? $faker->email : $this->email,
'avatar' => $this->avatar,
'role' => $this->role,
'subscription' => $this->subscribed('main'),
'created_at_formatted' => format_date($this->created_at, '%d. %B. %Y'),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]
],
'relationships' => [
'settings' => [
'settings' => [
'data' => [
'id' => (string)$this->settings->id,
'type' => 'settings',
@@ -52,14 +53,14 @@ class UserResource extends JsonResource
]
]
],
'storage' => [
'storage' => [
'data' => [
'id' => '1',
'type' => 'storage',
'attributes' => $this->storage
]
],
'favourites' => [
'favourites' => [
'data' => [
'id' => '1',
'type' => 'folders_favourite',
@@ -68,7 +69,7 @@ class UserResource extends JsonResource
],
],
],
'tree' => [
'tree' => [
'data' => [
'id' => '1',
'type' => 'folders_tree',
@@ -76,8 +77,7 @@ class UserResource extends JsonResource
'folders' => $this->folder_tree
],
],
],
'payment_methods' => new PaymentCardCollection($this->payment_cards)
]
]
];
}

View File

@@ -1,199 +0,0 @@
<?php
namespace App\Services;
use App\PaymentGateway;
use App\User;
use App\UserCard;
use App\UserSettings;
use Cartalyst\Stripe\Exception\CardErrorException;
use Stripe;
use Symfony\Component\HttpKernel\Exception\HttpException;
class PaymentService
{
/**
* PaymentService constructor.
*/
public function __construct()
{
$this->stripe = Stripe::make(config('services.stripe.secret'), '2020-03-02');
}
/**
* Get and charge customer
*
* @param $request
* @param $plan
* @param $user
*/
public function getAndChargeCustomer($request, $plan, $user)
{
// Get Stripe Customer
$customer = $this->findOrCreateStripeCustomer($user);
$paymentIntent = $this->stripe->paymentIntents()->create([
'amount' => $plan->price,
'currency' => 'USD',
'payment_method_types' => [
'card',
],
]);
dd($paymentIntent);
// Try charge customer
try {
if ($request->has('payment.meta.card_token')) {
// Register customer credit card
$created_card = $this->registerStripeCreditCard($customer, $request->input('payment.meta.card_token'));
// Charge with created credit card
/*$this->stripe->charges()->create([
'description' => 'Subscription ' . $plan->name,
'customer' => $customer['id'],
'amount' => $plan->price,
'currency' => 'USD',
'source' => $created_card->card_id
]);*/
} else {
// Charge with customer default creadit card
$this->stripe->charges()->create([
'description' => 'Subscription ' . $plan->name,
'customer' => $customer['id'],
'amount' => $plan->price,
'currency' => 'USD',
]);
}
} catch (CardErrorException $error) {
//dd($error);
// Remove previously registered card
if (in_array($error->getErrorCode(), ['rejected_card', 'card_declined'])
&& $request->has('payment.meta.card_token')
&& isset($error->getRawOutput()['error']['charge'])) {
// Get charge
$charge = $this->stripe->charges()->find($error->getRawOutput()['error']['charge']);
// Remove card from stripe
$this->deleteStripeCard($user->settings->stripe_customer_id, $charge['payment_method']);
// Get card
$error_card = UserCard::where('card_id', $charge['payment_method'])->first();
// Delete card
$error_card->delete();
}
throw new HttpException($error->getCode(), $error->getMessage());
}
// Increase payment processed column
PaymentGateway::where('slug', 'stripe')->first()->increment('payment_processed');
}
/**
* Find or create stripe customer
*
* @param $user
* @return array
*/
private function findOrCreateStripeCustomer($user)
{
// Get existing stripe customer
if ($user->settings->stripe_customer_id) {
return $this->stripe->customers()->find($user->settings->stripe_customer_id);
}
// Create new stripe costumer
if (!$user->settings->stripe_customer_id) {
$customer = $this->stripe->customers()->create([
'email' => $user->email,
'name' => $user->name,
'address' => [
'city' => $user->settings->billing_city,
'country' => $user->settings->billing_country,
'line1' => $user->settings->billing_address,
'state' => $user->settings->billing_state,
'postal_code' => $user->settings->billing_postal_code,
]
]);
// Store user stripe_customer_id
$user->settings()->update([
'stripe_customer_id' => $customer['id']
]);
return $customer;
}
}
/**
* Register stripe credit card
*
* @param $customer
* @param $card_id
* @return object
*/
private function registerStripeCreditCard($customer, $card_id)
{
// Register user card
$card = $this->stripe->cards()->create($customer['id'], $card_id);
// Get user settings
$user_settings = UserSettings::where('stripe_customer_id', $customer['id'])->first();
// Set default status
$default_card = UserCard::where('user_id', $user_settings->user_id)->get()->count() > 0 ? 0 : 1;
// Store user card
$card = UserCard::create([
'user_id' => $user_settings->user_id,
'status' => 'active',
'default' => $default_card,
'provider' => 'stripe',
'card_id' => $card['id'],
'brand' => $card['brand'],
'last4' => $card['last4'],
'exp_month' => $card['exp_month'],
'exp_year' => $card['exp_year'],
]);
return $card;
}
/**
* Set new default source from existing credit card
*
* @param $stripe_customer_id
* @param $card_id
*/
public function setDefaultStripeCard($stripe_customer_id, $card_id)
{
$this->stripe->customers()->update($stripe_customer_id, [
'default_source' => $card_id,
]);
}
/**
* Delete customer stripe credit card
*
* @param $stripe_customer_id
* @param $card_id
*/
public function deleteStripeCard($stripe_customer_id, $card_id)
{
$this->stripe->cards()->delete($stripe_customer_id, $card_id);
}
}

View File

@@ -3,6 +3,7 @@
namespace App\Services;
use App\User;
use Illuminate\Support\Str;
use Laravel\Cashier\Exceptions\IncompletePayment;
use Stripe;
@@ -18,6 +19,21 @@ class StripeService
$this->stripe = Stripe::make(env('STRIPE_SECRET'), '2020-03-02');
}
/**
* Get setup intent
*
* @param $user
* @return mixed
*/
public function getSetupIntent($user)
{
// Create stripe customer if not exist
$user->createOrGetStripeCustomer();
// Return setup intent
return $user->createSetupIntent();
}
/**
* Get default payment option or set new default payment
*
@@ -28,17 +44,24 @@ class StripeService
public function getOrSetDefaultPaymentMethod($request, $user)
{
// Check payment method
if (! $request->has('payment.meta.pm') && $user->hasDefaultPaymentMethod()) {
if (!$request->has('payment.meta.pm') && $user->hasDefaultPaymentMethod()) {
// Get default payment
return $user->defaultPaymentMethod()->paymentMethod;
}
} else if ( $request->has('payment.meta.pm') && $user->hasDefaultPaymentMethod() ) {
// Clear cached payment methods
cache_forget_many([
'payment-methods-user-' . $user->id,
'default-payment-methods-user-' . $user->id
]);
if ($request->has('payment.meta.pm') && $user->hasDefaultPaymentMethod()) {
// Set new payment
return $user->addPaymentMethod($request->input('payment.meta.pm'))->paymentMethod;
} else if ( $request->has('payment.meta.pm') && ! $user->hasDefaultPaymentMethod() ) {
} else if ($request->has('payment.meta.pm') && !$user->hasDefaultPaymentMethod()) {
// Set new payment
return $user->updateDefaultPaymentMethod($request->input('payment.meta.pm'))->paymentMethod;
@@ -82,80 +105,21 @@ class StripeService
}
/**
* Create plan
*
* @param $request
* @return mixed
* @param $user
*/
public function createPlan($request)
public function updateCustomerDetails($user)
{
$product = $this->stripe->products()->create([
'name' => $request->input('attributes.name'),
'description' => $request->input('attributes.description'),
'metadata' => [
'capacity' => $request->input('attributes.capacity')
$user->updateStripeCustomer([
'name' => $user->settings->billing_name,
'phone' => $user->settings->billing_phone_number,
'address' => [
'line1' => $user->settings->billing_address,
'city' => $user->settings->billing_city,
'country' => $user->settings->billing_country,
'postal_code' => $user->settings->billing_postal_code,
'state' => $user->settings->billing_state,
]
]);
$plan = $this->stripe->plans()->create([
'id' => Str::slug($request->input('attributes.name')),
'amount' => $request->input('attributes.price'),
'currency' => 'USD',
'interval' => 'month',
'product' => $product['id'],
]);
return compact('plan', 'product');
}
/**
* Update plan
*
* @param $request
* @param $id
*/
public function updatePlan($request, $id)
{
$plan_colls = ['is_active', 'price'];
$product_colls = ['name', 'description', 'capacity'];
$plan = $this->stripe->plans()->find($id);
// Update product
if (in_array($request->name, $product_colls)) {
if ($request->name === 'capacity') {
$this->stripe->products()->update($plan['product'], ['metadata' => ['capacity' => $request->value]]);
}
if ($request->name === 'name') {
$this->stripe->products()->update($plan['product'], ['name' => $request->value]);
}
if ($request->name === 'description') {
$this->stripe->products()->update($plan['product'], ['description' => $request->value]);
}
}
// Update plan
if (in_array($request->name, $plan_colls)) {
if ($request->name === 'is_active') {
$this->stripe->plans()->update($id, ['active' => $request->value]);
}
}
}
/**
* Get plan details
*
* @param $id
* @return mixed
*/
public function getPlan($id)
{
$plan = $this->stripe->plans()->find($id);
$product = $this->stripe->products()->find($plan['product']);
return compact('plan', 'product');
}
/**
@@ -217,6 +181,83 @@ class StripeService
return $plans;
}
/**
* Get plan details
*
* @param $id
* @return mixed
*/
public function getPlan($id)
{
$plan = $this->stripe->plans()->find($id);
$product = $this->stripe->products()->find($plan['product']);
return compact('plan', 'product');
}
/**
* Create plan
*
* @param $request
* @return mixed
*/
public function createPlan($request)
{
$product = $this->stripe->products()->create([
'name' => $request->input('attributes.name'),
'description' => $request->input('attributes.description'),
'metadata' => [
'capacity' => $request->input('attributes.capacity')
]
]);
$plan = $this->stripe->plans()->create([
'id' => Str::slug($request->input('attributes.name')),
'amount' => $request->input('attributes.price'),
'currency' => 'USD',
'interval' => 'month',
'product' => $product['id'],
]);
return compact('plan', 'product');
}
/**
* Update plan
*
* @param $request
* @param $id
*/
public function updatePlan($request, $id)
{
$plan_colls = ['is_active', 'price'];
$product_colls = ['name', 'description', 'capacity'];
$plan = $this->stripe->plans()->find($id);
// Update product
if (in_array($request->name, $product_colls)) {
if ($request->name === 'capacity') {
$this->stripe->products()->update($plan['product'], ['metadata' => ['capacity' => $request->value]]);
}
if ($request->name === 'name') {
$this->stripe->products()->update($plan['product'], ['name' => $request->value]);
}
if ($request->name === 'description') {
$this->stripe->products()->update($plan['product'], ['description' => $request->value]);
}
}
// Update plan
if (in_array($request->name, $plan_colls)) {
if ($request->name === 'is_active') {
$this->stripe->plans()->update($id, ['active' => $request->value]);
}
}
}
/**
* Delete plan
*
@@ -226,4 +267,38 @@ class StripeService
{
$this->stripe->plans()->delete($slug);
}
/**
* Get all user invoices
*
* @param $user
* @return mixed
*/
public function getUserInvoices($user)
{
return $user->invoices();
}
/**
* Get user invoice by id
*
* @param $id
* @return \Laravel\Cashier\Invoice|null
*/
public function getUserInvoice($customer, $id)
{
$user = User::where('stripe_id', $customer)->first();
return $user->findInvoice($id);
}
/**
* Get all invoices
*
* @return mixed
*/
public function getInvoices()
{
return $this->stripe->invoices()->all();
}
}

View File

@@ -65,7 +65,6 @@ use Rinvex\Subscriptions\Traits\HasSubscriptions;
* @property-read mixed $storage
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Invoice[] $invoices
* @property-read int|null $invoices_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\UserCard[] $payment_cards
* @property-read int|null $payment_cards_count
* @property-read \App\UserSettings|null $settings
* @property-read \Illuminate\Database\Eloquent\Collection|\Laravel\Cashier\Subscription[] $subscriptions
@@ -166,6 +165,7 @@ class User extends Authenticatable
* Set user billing info
*
* @param $billing
* @return UserSettings
*/
public function setBilling($billing)
{
@@ -178,6 +178,8 @@ class User extends Authenticatable
'billing_postal_code' => $billing['billing_postal_code'],
'billing_state' => $billing['billing_state'],
]);
return $this->settings;
}
/**
@@ -240,24 +242,4 @@ class User extends Authenticatable
{
return $this->hasOne(UserSettings::class);
}
/**
* Get user invoices
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function invoices()
{
return $this->hasMany(Invoice::class);
}
/**
* Get user payment cards
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function payment_cards()
{
return $this->hasMany(UserCard::class);
}
}

View File

@@ -1,48 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* App\UserCard
*
* @property int $id
* @property int $user_id
* @property string $provider
* @property int $default
* @property string $status
* @property string $card_id
* @property string $brand
* @property string $last4
* @property string $exp_month
* @property string $exp_year
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \App\User|null $user
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard query()
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereBrand($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereCardId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereDefault($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereExpMonth($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereExpYear($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereLast4($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereProvider($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereStatus($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\UserCard whereUserId($value)
* @mixin \Eloquent
*/
class UserCard extends Model
{
protected $guarded = ['id'];
public function user() {
return $this->hasOne(User::class);
}
}