Home >Backend Development >PHP Tutorial >Understanding Laravel Cashier&#s Core Traits: A Deep Dive

Understanding Laravel Cashier&#s Core Traits: A Deep Dive

DDD
DDDOriginal
2024-11-30 00:24:15613browse

Understanding Laravel Cashier

Laravel Cashier provides several powerful traits that handle Stripe integrations. Today, we'll explore three core traits and their public methods: ManagesSubscriptions, ManagesCustomer, and ManagesInvoices. Understanding these traits is crucial for implementing subscription-based billing in your Laravel applications.

ManagesSubscriptions Trait

Subscription Creation and Management

newSubscription($type, $prices = [])

Creates new subscription builder instance. Type defines the subscription name (e.g., 'default'), and prices can be single ID or array.

Trial Management

newSubscription($type, $prices = [])
  • No parameters: Checks ONLY generic (model-level) trial
  • With $type: Checks subscription-specific trial
  • With both: Checks if specific price is on trial
  • Returns boolean
onTrial($type = 'default', $price = null)
  • No parameters: Checks generic trial expiration
  • With $type: Checks specific subscription trial expiration
  • With both: Verifies specific price trial expiration
  • Returns boolean
hasExpiredTrial($type = 'default', $price = null)
  • Checks model-level trial status
  • Returns true if trial_ends_at exists and is future
  • No parameters needed
onGenericTrial()
  • Scope to filter customers on generic trial
  • Used in query builder
  • Requires query builder instance
scopeOnGenericTrial($query)
  • Checks if model-level trial has expired
  • Returns true if trial_ends_at exists and is past
  • No parameters needed
hasExpiredGenericTrial()
  • Scope to filter customers with expired generic trials
  • Used in query builder
  • Requires query builder instance
scopeHasExpiredGenericTrial($query)
  • No parameters: Returns generic trial end date if on generic trial
  • With $type: Returns subscription-specific trial end date
  • Returns Carbon instance or null

Subscription Status Checking

trialEndsAt($type = 'default')
  • Just $type: Checks valid subscription existence
  • With $price: Checks specific price subscription
  • Returns boolean
subscribed($type = 'default', $price = null)
  • Gets subscription by type
  • Returns Subscription model or null
subscription($type = 'default')
  • Gets all subscriptions
  • Returns HasMany relationship
  • No parameters needed
subscriptions()
  • Checks for incomplete payment on subscription
  • Returns boolean
hasIncompletePayment($type = 'default')
  • $products: Single product ID or array
  • $type: Subscription type to check
  • Returns boolean
  • Checks if subscribed to ANY of given products
subscribedToProduct($products, $type = 'default')
  • $prices: Single price ID or array
  • $type: Subscription type to check
  • Returns boolean
  • Checks if subscribed to ANY of given prices
subscribedToPrice($prices, $type = 'default')
  • Checks for valid subscription with specific product
  • Returns boolean
  • More specific than subscribedToProduct
onProduct($product)
  • Checks for valid subscription with specific price
  • Returns boolean
  • More specific than subscribedToPrice
onPrice($price)
  • Gets tax rates for subscription
  • Returns array
  • Empty by default, meant to be overridden
taxRates()
  • Gets tax rates for individual subscription items
  • Returns array
  • Empty by default, meant to be overridden

ManagesCustomer Trait

Customer Identification

newSubscription($type, $prices = [])
  • Returns Stripe customer ID or null
  • No parameters needed
  • Returns string|null
onTrial($type = 'default', $price = null)
  • Checks if customer has Stripe ID
  • Returns boolean
  • No parameters needed

Customer Creation and Management

hasExpiredTrial($type = 'default', $price = null)
  • Creates new Stripe customer
  • Options affect customer metadata, email, name, etc.
  • Throws exception if customer already exists
  • Returns Stripe Customer object
onGenericTrial()
  • Updates existing Stripe customer
  • Options determine what gets updated
  • Returns updated Stripe Customer object
  • Requires existing customer
scopeOnGenericTrial($query)
  • Gets existing customer or creates new one
  • Options affect creation if needed
  • Returns Stripe Customer object
  • More forgiving than createAsStripeCustomer
hasExpiredGenericTrial()
  • Updates existing or creates new customer
  • Options affect both update and creation
  • Returns Stripe Customer object
  • Combines update and create functionality
scopeHasExpiredGenericTrial($query)
  • Syncs local details to Stripe
  • Returns Stripe Customer object
  • Uses model attributes for sync
trialEndsAt($type = 'default')
  • Syncs if exists or creates new customer
  • Options affect creation if needed
  • Returns Stripe Customer object
subscribed($type = 'default', $price = null)
  • Gets Stripe customer object
  • Expand parameter determines related data
  • Returns Stripe Customer object
  • Requires existing customer

Customer Attributes

subscription($type = 'default')
  • Gets name for Stripe sync
  • Returns string|null
  • Default returns $this->name
subscriptions()
  • Gets email for Stripe sync
  • Returns string|null
  • Default returns $this->email
hasIncompletePayment($type = 'default')
  • Gets phone for Stripe sync
  • Returns string|null
  • Default returns $this->phone
subscribedToProduct($products, $type = 'default')
  • Gets address for Stripe sync
  • Returns array|null
  • Empty by default
subscribedToPrice($prices, $type = 'default')
  • Gets preferred locales for Stripe
  • Returns array
  • Empty by default
onProduct($product)
  • Gets metadata for Stripe
  • Returns array
  • Empty by default

Discount Management

onPrice($price)
  • Gets active customer discount
  • Returns Discount object or null
  • No parameters needed
taxRates()
  • Applies coupon to customer
  • Void return
  • Requires coupon ID
priceTaxRates()
  • Applies promotion code to customer
  • Void return
  • Requires promotion code ID
newSubscription($type, $prices = [])
  • Finds promotion code
  • Returns PromotionCode object or null
  • Options affect search
onTrial($type = 'default', $price = null)
  • Finds active promotion code
  • Returns PromotionCode object or null
  • Options affect search

Balance Management

hasExpiredTrial($type = 'default', $price = null)
  • Gets formatted customer balance
  • Returns string
  • No parameters needed
onGenericTrial()
  • Gets raw customer balance
  • Returns integer
  • No parameters needed
scopeOnGenericTrial($query)
  • Gets customer balance transactions
  • Returns Collection
  • Limit affects returned count
hasExpiredGenericTrial()
  • Credits customer balance
  • Returns CustomerBalanceTransaction
  • Amount is required
scopeHasExpiredGenericTrial($query)
  • Debits customer balance
  • Returns CustomerBalanceTransaction
  • Amount is required
trialEndsAt($type = 'default')
  • Applies balance adjustment
  • Returns CustomerBalanceTransaction
  • Amount is required

Tax Management

subscribed($type = 'default', $price = null)
  • Gets customer tax IDs
  • Returns Collection
  • Options affect retrieval
subscription($type = 'default')
  • Creates new tax ID
  • Returns Stripe TaxId
  • Both parameters required
subscriptions()
  • Deletes tax ID
  • Void return
  • Requires tax ID
hasIncompletePayment($type = 'default')
  • Finds specific tax ID
  • Returns Stripe TaxId or null
  • Requires tax ID

Tax Status Checking

subscribedToProduct($products, $type = 'default')
  • Checks if customer is not tax exempt
  • Returns boolean
  • No parameters needed
subscribedToPrice($prices, $type = 'default')
  • Checks if customer is tax exempt
  • Returns boolean
  • No parameters needed
onProduct($product)
  • Checks if reverse charge applies
  • Returns boolean
  • No parameters needed

Billing Portal

onPrice($price)
  • Gets Stripe billing portal URL
  • Returns string
  • ReturnUrl optional
taxRates()
  • Redirects to Stripe billing portal
  • Returns RedirectResponse
  • ReturnUrl optional

ManagesInvoices Trait

Invoice Items

priceTaxRates()
  • Adds invoice item
  • Returns Stripe InvoiceItem
  • Description and amount required
stripeId()
  • Adds price-based item
  • Returns Stripe InvoiceItem
  • Price ID required

Invoice Creation

hasStripeId()
  • Creates immediate invoice
  • Returns Invoice object
  • Description and amount required
createAsStripeCustomer(array $options = [])
  • Creates price-based invoice
  • Returns Invoice object
  • Price ID required
newSubscription($type, $prices = [])
  • Generates invoice
  • Returns Invoice object
  • Options affect creation
onTrial($type = 'default', $price = null)
  • Creates Stripe invoice
  • Returns Invoice object
  • Options affect creation

Invoice Retrieval

hasExpiredTrial($type = 'default', $price = null)
  • Gets upcoming invoice
  • Returns Invoice object or null
  • Options affect preview
onGenericTrial()
  • Finds specific invoice
  • Returns Invoice object or null
  • Requires invoice ID
scopeOnGenericTrial($query)
  • Finds invoice or throws exception
  • Returns Invoice object
  • Requires invoice ID
  • Throws NotFoundHttpException or AccessDeniedHttpException
hasExpiredGenericTrial()
  • Gets invoice PDF
  • Returns Response
  • ID required, filename optional
scopeHasExpiredGenericTrial($query)
  • Gets all invoices
  • Returns Collection
  • Parameters affect filtering
trialEndsAt($type = 'default')
  • Gets all invoices including pending
  • Returns Collection
  • Shorthand for invoices(true)
subscribed($type = 'default', $price = null)
  • Gets paginated invoices
  • Returns CursorPaginator
  • Multiple parameters affect pagination

Key Observations

  1. Parameter Sensitivity: Methods often have different behaviors based on parameter presence.
  2. Return Types: Methods consistently return specific types (boolean, objects, collections).
  3. Default Values: Many parameters have reasonable defaults but can be overridden.
  4. Trait Interdependence: Methods often rely on other trait methods.
  5. Stripe Integration: Most methods interact with Stripe's API either directly or indirectly.

Best Practices

  1. Always check parameter requirements for desired behavior.
  2. Handle potential exceptions, especially for *OrFail methods.
  3. Use proper type hinting when extending these traits.
  4. Test different parameter combinations thoroughly.
  5. Consider caching frequent calls to reduce API requests.

Conclusion

These traits form the backbone of Laravel Cashier's functionality. Understanding the full scope of available methods and their parameter behaviors is crucial for proper implementation. Always consult the official documentation alongside this reference for the most up-to-date information.

The above is the detailed content of Understanding Laravel Cashier&#s Core Traits: A Deep Dive. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn