Pada kesempatan kali ini, saya akan share sedikit tips bagi kalian yang pusing dengan bagaimana cara membuat format angka dalam rupiah? maksudnya misal kita punya sebuah angka 1000000, kalau tiadak ada titiknya kan pusing juga bacanya? maka dari itu tutorial ini saya buat agar bisa membuat sebuah format uang standar. Show
Sebenarnya PHP sudah menyediakan sebuah fungsi yang benar-benar bisa memecahkan masalah ini hanya dengan 1 baris skrip saja. fungsi tersebut antara lain : <?php $angka = 1000000; echo number_format($angka, 0, '', '.'); ?> Dari skrip diatas terlihat kita akan mengubah angka 1000000 menjadi 1.000.000. Pasti pada bingung dengan fungsi number_format() tersebut? berikut ini penjelasan parameter apa saja yang dibutuhkan pada fungsi tersebut : number_format(param1, param2, param3, param4)
Oke sebagai contoh biar lebih jelas soal penjelasan mengenai parameter-parameter diatas. Kita akan coba berbagai kustom parameternya. Silakan buat sebuah folder dengan nama latihan_php, lalu simpan pada folder xampp/htdocs. Kemudian buat sebuah file dengan nama format_uang.php, lalu simpan pada folder xampp/htdocs/latihan_php/. Berikut ini kodenya : <?php $angka = 1000000; echo "<b>Contoh 1</b> (tanpa angka desimal dan tanda pemisah angka ribuan adalah titik)<br>"; echo "<h2>Rp. ".number_format($angka, 0, '', '.')."</h2>"; echo "<br>"; echo "<b>Contoh 2</b> (dengan 2 angka desimal, tanda pemisah angka desimal adalah koma, tanda pemisah angka ribuan adalah titik)<br>"; echo "<h2>Rp. ".number_format($angka, 2, ',', '.')."</h2>"; echo "<br>"; echo "<b>Contoh 3</b> (tanpa angka desimal dan tanda pemisah angka ribuan adalah koma)<br>"; echo "<h2>Rp. ".number_format($angka, 0, '', ',')."</h2>"; ?> Kemudian save file tadi. Lalu buka browser dan ketik localhost/latihan_php/format_uang.php. Berikut ini tampilan dari hasil kode diatas : Sudah cukup mengerti dengan maksud dari penjelasan saya? dari 3 contoh diatas seharusnya sudah bisa lebih paham dan mengerti bagaimana cara menggunakan fungsi number_format yang disediakan PHP. Baca Juga:
Mungkin sekian untuk catatan kali ini. Semoga bisa bermanfaat. Jika ada yang kurang dipahami, langsung tanyakan pada form komentar dibawah ini. Jangan lupa LIKE dan SHARE nya, Terimakasih banyak. Laravel Cashier Stripe provides an expressive, fluent interface to Stripe's subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs. Upgrading CashierWhen upgrading to a new version of Cashier, it's important that you carefully review the upgrade guide.
InstallationFirst, install the Cashier package for Stripe using the Composer package manager:
Database MigrationsCashier's service provider registers its own database migration directory, so remember to migrate your database after installing the package. The Cashier migrations will add several columns to your 85 table as well as create a new 86 table to hold all of your customer's subscriptions:If you need to overwrite the migrations that ship with Cashier, you can publish them using the 87 Artisan command:
If you would like to prevent Cashier's migrations from running entirely, you may use the 88 method provided by Cashier. Typically, this method should be called in the 89 method of your 90:
ConfigurationBillable ModelBefore using Cashier, add the 93 trait to your billable model definition. Typically, this will be the 94 model. This trait provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons, and updating payment method information:
Cashier assumes your billable model will be the 94 class that ships with Laravel. If you wish to change this you may specify a different model via the 96 method. This method should typically be called in the 97 method of your 90 class:
API KeysNext, you should configure your Stripe API keys in your application's 00 file. You can retrieve your Stripe API keys from the Stripe control panel:
Currency ConfigurationThe default Cashier currency is United States Dollars (USD). You can change the default currency by setting the 03 environment variable within your application's 00 file:In addition to configuring Cashier's currency, you may also specify a locale to be used when formatting money values for display on invoices. Internally, Cashier utilizes PHP's 05 class to set the currency locale:
Tax ConfigurationThanks to Stripe Tax, it's possible to automatically calculate taxes for all invoices generated by Stripe. You can enable automatic tax calculation by invoking the 08 method in the 97 method of your application's 10 class:
Once tax calculation has been enabled, any new subscriptions and any one-off invoices that are generated will receive automatic tax calculation. For this feature to work properly, your customer's billing details, such as the customer's name, address, and tax ID, need to be synced to Stripe. You may use the and methods offered by Cashier to accomplish this.
LoggingCashier allows you to specify the log channel to be used when logging fatal Stripe errors. You may specify the log channel by defining the 11 environment variable within your application's 00 file:Exceptions that are generated by API calls to Stripe will be logged through your application's default log channel. Using Custom ModelsYou are free to extend the models used internally by Cashier by defining your own model and extending the corresponding Cashier model:
After defining your model, you may instruct Cashier to use your custom model via the 13 class. Typically, you should inform Cashier about your custom models in the 97 method of your application's 10 class:
CustomersRetrieving CustomersYou can retrieve a customer by their Stripe ID using the 16 method. This method will return an instance of the billable model: 0Creating CustomersOccasionally, you may wish to create a Stripe customer without beginning a subscription. You may accomplish this using the 17 method: 1Once the customer has been created in Stripe, you may begin a subscription at a later date. You may provide an optional 18 array to pass in any additional customer creation parameters that are supported by the Stripe API: 2You may use the 19 method if you want to return the Stripe customer object for a billable model: 3The 20 method may be used if you would like to retrieve the Stripe customer object for a given billable model but are not sure whether the billable model is already a customer within Stripe. This method will create a new customer in Stripe if one does not already exist: 4Updating CustomersOccasionally, you may wish to update the Stripe customer directly with additional information. You may accomplish this using the 21 method. This method accepts an array of customer update options supported by the Stripe API: 5BalancesStripe allows you to credit or debit a customer's "balance". Later, this balance will be credited or debited on new invoices. To check the customer's total balance you may use the 22 method that is available on your billable model. The 22 method will return a formatted string representation of the balance in the customer's currency: 6To credit a customer's balance, you may provide a value to the 24 method. If you wish, you may also provide a description: 7Providing a value to the 25 method will debit the customer's balance: 8The 26 method will create new customer balance transactions for the customer. You may retrieve these transaction records using the 27 method, which may be useful in order to provide a log of credits and debits for the customer to review: 9Tax IDsCashier offers an easy way to manage a customer's tax IDs. For example, the 28 method may be used to retrieve all of the tax IDs that are assigned to a customer as a collection:You can also retrieve a specific tax ID for a customer by its identifier: 0You may create a new Tax ID by providing a valid and value to the 29 method: 1The 29 method will immediately add the VAT ID to the customer's account. ; however, this is an asynchronous process. You can be notified of verification updates by subscribing to the 31 webhook event and inspecting . For more information on handling webhooks, please consult the .You may delete a tax ID using the 33 method: 2Syncing Customer Data With StripeTypically, when your application's users update their name, email address, or other information that is also stored by Stripe, you should inform Stripe of the updates. By doing so, Stripe's copy of the information will be in sync with your application's. To automate this, you may define an event listener on your billable model that reacts to the model's 34 event. Then, within your event listener, you may invoke the 35 method on the model: 3Now, every time your customer model is updated, its information will be synced with Stripe. For convenience, Cashier will automatically sync your customer's information with Stripe on the initial creation of the customer. You may customize the columns used for syncing customer information to Stripe by overriding a variety of methods provided by Cashier. For example, you may override the 36 method to customize the attribute that should be considered the customer's "name" when Cashier syncs customer information to Stripe: 4Similarly, you may override the 37, 38, 39, and 40 methods. These methods will sync information to their corresponding customer parameters when updating the Stripe customer object. If you wish to take total control over the customer information sync process, you may override the 35 method.Billing PortalStripe offers an easy way to set up a billing portal so that your customer can manage their subscription, payment methods, and view their billing history. You can redirect your users to the billing portal by invoking the 42 method on the billable model from a controller or route: 5By default, when the user is finished managing their subscription, they will be able to return to the 43 route of your application via a link within the Stripe billing portal. You may provide a custom URL that the user should return to by passing the URL as an argument to the 42 method: 6If you would like to generate the URL to the billing portal without generating an HTTP redirect response, you may invoke the 45 method: 7Payment MethodsStoring Payment MethodsIn order to create subscriptions or perform "one-off" charges with Stripe, you will need to store a payment method and retrieve its identifier from Stripe. The approach used to accomplish this differs based on whether you plan to use the payment method for subscriptions or single charges, so we will examine both below. Payment Methods For SubscriptionsWhen storing a customer's credit card information for future use by a subscription, the Stripe "Setup Intents" API must be used to securely gather the customer's payment method details. A "Setup Intent" indicates to Stripe the intention to charge a customer's payment method. Cashier's 93 trait includes the 47 method to easily create a new Setup Intent. You should invoke this method from the route or controller that will render the form which gathers your customer's payment method details: 8After you have created the Setup Intent and passed it to the view, you should attach its secret to the element that will gather the payment method. For example, consider this "update payment method" form: 9Next, the Stripe.js library may be used to attach a Stripe Element to the form and securely gather the customer's payment details: 0Next, the card can be verified and a secure "payment method identifier" can be retrieved from Stripe using Stripe's 48 method: 1After the card has been verified by Stripe, you may pass the resulting 49 identifier to your Laravel application, where it can be attached to the customer. The payment method can either be or . You can also immediately use the payment method identifier to .
Payment Methods For Single ChargesOf course, when making a single charge against a customer's payment method, we will only need to use a payment method identifier once. Due to Stripe limitations, you may not use the stored default payment method of a customer for single charges. You must allow the customer to enter their payment method details using the Stripe.js library. For example, consider the following form: 2After defining such a form, the Stripe.js library may be used to attach a Stripe Element to the form and securely gather the customer's payment details: 0Next, the card can be verified and a secure "payment method identifier" can be retrieved from Stripe using : 4If the card is verified successfully, you may pass the 51 to your Laravel application and process a .Retrieving Payment MethodsThe 52 method on the billable model instance returns a collection of 53 instances: 5By default, this method will return payment methods of the 54 type. To retrieve payment methods of a different type, you may pass the 55 as an argument to the method: 6To retrieve the customer's default payment method, the 56 method may be used: 7You can retrieve a specific payment method that is attached to the billable model using the 57 method: 8Determining If A User Has A Payment MethodTo determine if a billable model has a default payment method attached to their account, invoke the 58 method: 9You may use the 59 method to determine if a billable model has at least one payment method attached to their account: 0This method will determine if the billable model has payment methods of the 54 type. To determine if a payment method of another type exists for the model, you may pass the 55 as an argument to the method: 1Updating The Default Payment MethodThe 62 method may be used to update a customer's default payment method information. This method accepts a Stripe payment method identifier and will assign the new payment method as the default billing payment method: 2To sync your default payment method information with the customer's default payment method information in Stripe, you may use the 63 method: 3
Adding Payment MethodsTo add a new payment method, you may call the 64 method on the billable model, passing the payment method identifier: 4
Deleting Payment MethodsTo delete a payment method, you may call the 65 method on the 53 instance you wish to delete: 5The 67 method will delete a specific payment method from the billable model: 6The 68 method will delete all of the payment method information for the billable model: 7By default, this method will delete payment methods of the 54 type. To delete payment methods of a different type you can pass the 55 as an argument to the method: 8
SubscriptionsSubscriptions provide a way to set up recurring payments for your customers. Stripe subscriptions managed by Cashier provide support for multiple subscription prices, subscription quantities, trials, and more. Creating SubscriptionsTo create a subscription, first retrieve an instance of your billable model, which typically will be an instance of 94. Once you have retrieved the model instance, you may use the 72 method to create the model's subscription: 9The first argument passed to the 72 method should be the internal name of the subscription. If your application only offers a single subscription, you might call this 74 or 75. This subscription name is only for internal application usage and is not meant to be shown to users. In addition, it should not contain spaces and it should never be changed after creating the subscription. The second argument is the specific price the user is subscribing to. This value should correspond to the price's identifier in Stripe.The 76 method, which accepts or Stripe 77 object, will begin the subscription as well as update your database with the billable model's Stripe customer ID and other relevant billing information.
Collecting Recurring Payments Via Invoice EmailsInstead of collecting a customer's recurring payments automatically, you may instruct Stripe to email an invoice to the customer each time their recurring payment is due. Then, the customer may manually pay the invoice once they receive it. The customer does not need to provide a payment method up front when collecting recurring payments via invoices: 0The amount of time a customer has to pay their invoice before their subscription is cancelled is determined by the 79 option. By default, this is 30 days; however, you may provide a specific value for this option if you wish: 1QuantitiesIf you would like to set a specific quantity for the price when creating the subscription, you should invoke the 80 method on the subscription builder before creating the subscription: 2Additional DetailsIf you would like to specify additional customer or subscription options supported by Stripe, you may do so by passing them as the second and third arguments to the 76 method: 3CouponsIf you would like to apply a coupon when creating the subscription, you may use the 82 method: 2Or, if you would like to apply a Stripe promotion code, you may use the 83 method: 5The given promotion code ID should be the Stripe API ID assigned to the promotion code and not the customer facing promotion code. If you need to find a promotion code ID based on a given customer facing promotion code, you may use the 84 method: 6In the example above, the returned 85 object is an instance of 86. This class decorates an underlying 87 object. You can retrieve the coupon related to the promotion code by invoking the 88 method: 7The coupon instance allows you to determine the discount amount and whether the coupon represents a fixed discount or percentage based discount: 8You can also retrieve the discounts that are currently applied to a customer or subscription: 9The returned 89 instances decorate an underlying 90 object instance. You may retrieve the coupon related to this discount by invoking the 88 method: 0If you would like to apply a new coupon or promotion code to a customer or subscription, you may do so via the 92 or 93 methods: 1Remember, you should use the Stripe API ID assigned to the promotion code and not the customer facing promotion code. Only one coupon or promotion code can be applied to a customer or subscription at a given time. For more info on this subject, please consult the Stripe documentation regarding coupons and promotion codes. Adding SubscriptionsIf you would like to add a subscription to a customer who already has a default payment method you may invoke the 94 method on the subscription builder: 2Creating Subscriptions From The Stripe DashboardYou may also create subscriptions from the Stripe dashboard itself. When doing so, Cashier will sync newly added subscriptions and assign them a name of 74. To customize the subscription name that is assigned to dashboard created subscriptions, and overwrite the 97 method.In addition, you may only create one type of subscription via the Stripe dashboard. If your application offers multiple subscriptions that use different names, only one type of subscription may be added through the Stripe dashboard. Finally, you should always make sure to only add one active subscription per type of subscription offered by your application. If a customer has two 74 subscriptions, only the most recently added subscription will be used by Cashier even though both would be synced with your application's database.Checking Subscription StatusOnce a customer is subscribed to your application, you may easily check their subscription status using a variety of convenient methods. First, the 99 method returns 00 if the customer has an active subscription, even if the subscription is currently within its trial period. The 99 method accepts the name of the subscription as its first argument: 3The 99 method also makes a great candidate for a route middleware, allowing you to filter access to routes and controllers based on the user's subscription status: 4If you would like to determine if a user is still within their trial period, you may use the 03 method. This method can be useful for determining if you should display a warning to the user that they are still on their trial period: 5The 04 method may be used to determine if the user is subscribed to a given product based on a given Stripe product's identifier. In Stripe, products are collections of prices. In this example, we will determine if the user's 74 subscription is actively subscribed to the application's "premium" product. The given Stripe product identifier should correspond to one of your product's identifiers in the Stripe dashboard: 6By passing an array to the 04 method, you may determine if the user's 74 subscription is actively subscribed to the application's "basic" or "premium" product: 7The 08 method may be used to determine if a customer's subscription corresponds to a given price ID: 8The 09 method may be used to determine if the user is currently subscribed and is no longer within their trial period: 9
Canceled Subscription StatusTo determine if the user was once an active subscriber but has canceled their subscription, you may use the 12 method: 0You may also determine if a user has canceled their subscription but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. Note that the 99 method still returns 00 during this time: 1To determine if the user has canceled their subscription and is no longer within their "grace period", you may use the 15 method: 2Incomplete and Past Due StatusIf a subscription requires a secondary payment action after creation the subscription will be marked as 16. Subscription statuses are stored in the 17 column of Cashier's 86 database table.Similarly, if a secondary payment action is required when swapping prices the subscription will be marked as 19. When your subscription is in either of these states it will not be active until the customer has confirmed their payment. Determining if a subscription has an incomplete payment may be accomplished using the 20 method on the billable model or a subscription instance: 3When a subscription has an incomplete payment, you should direct the user to Cashier's payment confirmation page, passing the 21 identifier. You may use the 21 method available on subscription instance to retrieve this identifier: 4If you would like the subscription to still be considered active when it's in a 19 or 16 state, you may use the 25 and 26 methods provided by Cashier. Typically, these methods should be called in the 89 method of your 10: 5
Subscription ScopesMost subscription states are also available as query scopes so that you may easily query your database for subscriptions that are in a given state: 6A complete list of available scopes is available below: 7Changing PricesAfter a customer is subscribed to your application, they may occasionally want to change to a new subscription price. To swap a customer to a new price, pass the Stripe price's identifier to the 30 method. When swapping prices, it is assumed that the user would like to re-activate their subscription if it was previously canceled. The given price identifier should correspond to a Stripe price identifier available in the Stripe dashboard: 8If the customer is on trial, the trial period will be maintained. Additionally, if a "quantity" exists for the subscription, that quantity will also be maintained. If you would like to swap prices and cancel any trial period the customer is currently on, you may invoke the 34 method: 9If you would like to swap prices and immediately invoice the customer instead of waiting for their next billing cycle, you may use the 35 method: 0ProrationsBy default, Stripe prorates charges when swapping between prices. The 36 method may be used to update the subscription's price without prorating the charges: 1For more information on subscription proration, consult the Stripe documentation.
Subscription QuantitySometimes subscriptions are affected by "quantity". For example, a project management application might charge $10 per month per project. You may use the 39 and 40 methods to easily increment or decrement your subscription quantity: 2Alternatively, you may set a specific quantity using the 31 method: 3The 36 method may be used to update the subscription's quantity without prorating the charges: 4For more information on subscription quantities, consult the Stripe documentation. Quantities For Subscriptions With Multiple ProductsIf your subscription is a , you should pass the ID of the price whose quantity you wish to increment or decrement as the second argument to the increment / decrement methods: 5Subscriptions With Multiple ProductsSubscription with multiple products allow you to assign multiple billing products to a single subscription. For example, imagine you are building a customer service "helpdesk" application that has a base subscription price of $10 per month but offers a live chat add-on product for an additional $15 per month. Information for subscriptions with multiple products is stored in Cashier's 43 database table.You may specify multiple products for a given subscription by passing an array of prices as the second argument to the 72 method: 6In the example above, the customer will have two prices attached to their 74 subscription. Both prices will be charged on their respective billing intervals. If necessary, you may use the 80 method to indicate a specific quantity for each price: 7If you would like to add another price to an existing subscription, you may invoke the subscription's 47 method: 8The example above will add the new price and the customer will be billed for it on their next billing cycle. If you would like to bill the customer immediately you may use the 48 method: 9If you would like to add a price with a specific quantity, you can pass the quantity as the second argument of the 47 or 48 methods: 0You may remove prices from subscriptions using the 51 method: 1
Swapping PricesYou may also change the prices attached to a subscription with multiple products. For example, imagine a customer has a 52 subscription with a 53 add-on product and you want to upgrade the customer from the 52 to the 55 price: 2When executing the example above, the underlying subscription item with the 52 is deleted and the one with the 53 is preserved. Additionally, a new subscription item for the 55 is created.You can also specify subscription item options by passing an array of key / value pairs to the 30 method. For example, you may need to specify the subscription price quantities: 3If you want to swap a single price on a subscription, you may do so using the 30 method on the subscription item itself. This approach is particularly useful if you would like to preserve all of the existing metadata on the subscription's other prices: 4ProrationBy default, Stripe will prorate charges when adding or removing prices from a subscription with multiple products. If you would like to make a price adjustment without proration, you should chain the 36 method onto your price operation: 5QuantitiesIf you would like to update quantities on individual subscription prices, you may do so using the by passing the name of the price as an additional argument to the method: 6
Subscription ItemsWhen a subscription has multiple prices, it will have multiple subscription "items" stored in your database's 43 table. You may access these via the 66 relationship on the subscription: 7You can also retrieve a specific price using the 70 method: 8Multiple SubscriptionsStripe allows your customers to have multiple subscriptions simultaneously. For example, you may run a gym that offers a swimming subscription and a weight-lifting subscription, and each subscription may have different pricing. Of course, customers should be able to subscribe to either or both plans. When your application creates subscriptions, you may provide the name of the subscription to the 72 method. The name may be any string that represents the type of subscription the user is initiating: 9In this example, we initiated a monthly swimming subscription for the customer. However, they may want to swap to a yearly subscription at a later time. When adjusting the customer's subscription, we can simply swap the price on the 72 subscription: 00Of course, you may also cancel the subscription entirely: 01Metered BillingMetered billing allows you to charge customers based on their product usage during a billing cycle. For example, you may charge customers based on the number of text messages or emails they send per month. To start using metered billing, you will first need to create a new product in your Stripe dashboard with a metered price. Then, use the 73 to add the metered price ID to a customer subscription: 02You may also start a metered subscription via : 03Reporting UsageAs your customer uses your application, you will report their usage to Stripe so that they can be billed accurately. To increment the usage of a metered subscription, you may use the 74 method: 04By default, a "usage quantity" of 1 is added to the billing period. Alternatively, you may pass a specific amount of "usage" to add to the customer's usage for the billing period: 05If your application offers multiple prices on a single subscription, you will need to use the 75 method to specify the metered price you want to report usage for: 06Sometimes, you may need to update usage which you have previously reported. To accomplish this, you may pass a timestamp or a 76 instance as the second parameter to 74. When doing so, Stripe will update the usage that was reported at that given time. You can continue to update previous usage records as the given date and time is still within the current billing period: 07Retrieving Usage RecordsTo retrieve a customer's past usage, you may use a subscription instance's 78 method: 08If your application offers multiple prices on a single subscription, you may use the 79 method to specify the metered price that you wish to retrieve usage records for: 09The 78 and 79 methods return a Collection instance containing an associative array of usage records. You may iterate over this array to display a customer's total usage: 10For a full reference of all usage data returned and how to use Stripe's cursor based pagination, please consult the official Stripe API documentation. Subscription Taxes
To specify the tax rates a user pays on a subscription, you should implement the 82 method on your billable model and return an array containing the Stripe tax rate IDs. You can define these tax rates in your Stripe dashboard: 11The 82 method enables you to apply a tax rate on a customer-by-customer basis, which may be helpful for a user base that spans multiple countries and tax rates.If you're offering subscriptions with multiple products, you may define different tax rates for each price by implementing a 84 method on your billable model: 12
Syncing Tax RatesWhen changing the hard-coded tax rate IDs returned by the 82 method, the tax settings on any existing subscriptions for the user will remain the same. If you wish to update the tax value for existing subscriptions with the new 82 values, you should call the 88 method on the user's subscription instance: 13This will also sync any item tax rates for a subscription with multiple products. If your application is offering subscriptions with multiple products, you should ensure that your billable model implements the 84 method .Tax ExemptionCashier also offers the 90, 91, and 92 methods to determine if the customer is tax exempt. These methods will call the Stripe API to determine a customer's tax exemption status: 14
Subscription Anchor DateBy default, the billing cycle anchor is the date the subscription was created or, if a trial period is used, the date that the trial ends. If you would like to modify the billing anchor date, you may use the 95 method: 15For more information on managing subscription billing cycles, consult the Stripe billing cycle documentation Cancelling SubscriptionsTo cancel a subscription, call the 96 method on the user's subscription: 16When a subscription is canceled, Cashier will automatically set the 97 column in your 86 database table. This column is used to know when the 99 method should begin returning 00.For example, if a customer cancels a subscription on March 1st, but the subscription was not scheduled to end until March 5th, the 99 method will continue to return 00 until March 5th. This is done because a user is typically allowed to continue using an application until the end of their billing cycle.You may determine if a user has canceled their subscription but are still on their "grace period" using the 03 method: 1If you wish to cancel a subscription immediately, call the 04 method on the user's subscription: 18If you wish to cancel a subscription immediately and invoice any remaining un-invoiced metered usage or new / pending proration invoice items, call the 05 method on the user's subscription: 19You may also choose to cancel the subscription at a specific moment in time: 20Resuming SubscriptionsIf a customer has canceled their subscription and you wish to resume it, you may invoke the 06 method on the subscription. The customer must still be within their "grace period" in order to resume a subscription: 21If the customer cancels a subscription and then resumes that subscription before the subscription has fully expired the customer will not be billed immediately. Instead, their subscription will be re-activated and they will be billed on the original billing cycle. Subscription TrialsWith Payment Method Up FrontIf you would like to offer trial periods to your customers while still collecting payment method information up front, you should use the 07 method when creating your subscriptions: 22This method will set the trial period ending date on the subscription record within the database and instruct Stripe to not begin billing the customer until after this date. When using the 07 method, Cashier will overwrite any default trial period configured for the price in Stripe.
The 09 method allows you to provide a 10 instance that specifies when the trial period should end: 23You may determine if a user is within their trial period using either the 03 method of the user instance or the 03 method of the subscription instance. The two examples below are equivalent: 24You may use the 13 method to immediately end a subscription trial: 25To determine if an existing trial has expired, you may use the 14 methods: 26Defining Trial Days In Stripe / CashierYou may choose to define how many trial days your price's receive in the Stripe dashboard or always pass them explicitly using Cashier. If you choose to define your price's trial days in Stripe you should be aware that new subscriptions, including new subscriptions for a customer that had a subscription in the past, will always receive a trial period unless you explicitly call the 15 method.Without Payment Method Up FrontIf you would like to offer trial periods without collecting the user's payment method information up front, you may set the 16 column on the user record to your desired trial ending date. This is typically done during user registration: 27
Cashier refers to this type of trial as a "generic trial", since it is not attached to any existing subscription. The 03 method on the billable model instance will return 00 if the current date is not past the value of 16: 28Once you are ready to create an actual subscription for the user, you may use the 72 method as usual: 29To retrieve the user's trial ending date, you may use the 22 method. This method will return a Carbon date instance if a user is on a trial or 65 if they aren't. You may also pass an optional subscription name parameter if you would like to get the trial ending date for a specific subscription other than the default one: 30You may also use the 24 method if you wish to know specifically that the user is within their "generic" trial period and has not yet created an actual subscription: 31Extending TrialsThe 25 method allows you to extend the trial period of a subscription after the subscription has been created. If the trial has already expired and the customer is already being billed for the subscription, you can still offer them an extended trial. The time spent within the trial period will be deducted from the customer's next invoice: 32Handling Stripe Webhooks
Stripe can notify your application of a variety of events via webhooks. By default, a route that points to Cashier's webhook controller is automatically registered by the Cashier service provider. This controller will handle all incoming webhook requests. By default, the Cashier webhook controller will automatically handle cancelling subscriptions that have too many failed charges (as defined by your Stripe settings), customer updates, customer deletions, subscription updates, and payment method changes; however, as we'll soon discover, you can extend this controller to handle any Stripe webhook event you like. To ensure your application can handle Stripe webhooks, be sure to configure the webhook URL in the Stripe control panel. By default, Cashier's webhook controller responds to the 26 URL path. The full list of all webhooks you should enable in the Stripe control panel are:
For convenience, Cashier includes a 34 Artisan command. This command will create a webhook in Stripe that listens to all of the events required by Cashier: 33By default, the created webhook will point to the URL defined by the 35 environment variable and the 36 route that is included with Cashier. You may provide the 37 option when invoking the command if you would like to use a different URL: 34The webhook that is created will use the Stripe API version that your version of Cashier is compatible with. If you would like to use a different Stripe version, you may provide the 38 option: 35After creation, the webhook will be immediately active. If you wish to create the webhook but have it disabled until you're ready, you may provide the 39 option when invoking the command: 36
Webhooks & CSRF ProtectionSince Stripe webhooks need to bypass Laravel's CSRF protection, be sure to list the URI as an exception in your application's 40 middleware or list the route outside of the 41 middleware group:Defining Webhook Event HandlersCashier automatically handles subscription cancellations for failed charges and other common Stripe webhook events. However, if you have additional webhook events you would like to handle, you may do so by listening to the following events that are dispatched by Cashier:
Both events contain the full payload of the Stripe webhook. For example, if you wish to handle the 32 webhook, you may register a that will handle the event: 37Once your listener has been defined, you may register it within your application's 45: 38Verifying Webhook SignaturesTo secure your webhooks, you may use Stripe's webhook signatures. For convenience, Cashier automatically includes a middleware which validates that the incoming Stripe webhook request is valid. To enable webhook verification, ensure that the 01 environment variable is set in your application's 00 file. The webhook 48 may be retrieved from your Stripe account dashboard.Single ChargesSimple ChargeIf you would like to make a one-time charge against a customer, you may use the 49 method on a billable model instance. You will need to as the second argument to the 49 method: 39The 49 method accepts an array as its third argument, allowing you to pass any options you wish to the underlying Stripe charge creation. More information regarding the options available to you when creating charges may be found in the Stripe documentation: 40You may also use the 49 method without an underlying customer or user. To accomplish this, invoke the 49 method on a new instance of your application's billable model: 41The 49 method will throw an exception if the charge fails. If the charge is successful, an instance of 55 will be returned from the method: 42
Charge With InvoiceSometimes you may need to make a one-time charge and offer a PDF receipt to your customer. The 57 method lets you do just that. For example, let's invoice a customer for five new shirts: 43The invoice will be immediately charged against the user's default payment method. The 57 method also accepts an array as its third argument. This array contains the billing options for the invoice item. The fourth argument accepted by the method is also an array which should contain the billing options for the invoice itself: 44Similarly to 57, you may use the 60 method to create a one-time charge for multiple items (up to 250 items per invoice) by adding them to the customer's "tab" and then invoicing the customer. For example, we may invoice a customer for five shirts and two mugs: 45Alternatively, you may use the 61 method to make a "one-off" charge against the customer's default payment method: 46Although the 61 method is available for you to use, it is recommended that you use the 57 and 60 methods with pre-defined prices. By doing so, you will have access to better analytics and data within your Stripe dashboard regarding your sales on a per-product basis.
Creating Payment IntentsYou can create a new Stripe payment intent by invoking the 68 method on a billable model instance. Calling this method will create a payment intent that is wrapped in a 55 instance: 47After creating the payment intent, you can return the client secret to your application's frontend so that the user can complete the payment in their browser. To read more about building entire payment flows using Stripe payment intents, please consult the Stripe documentation. When using the 68 method, the default payment methods that are enabled within your Stripe dashboard will be available to the customer. Alternatively, if you only want to allow for some specific payment methods to be used, you may use the 71 method: 48
Refunding ChargesIf you need to refund a Stripe charge, you may use the 74 method. This method accepts the Stripe as its first argument: 49InvoicesRetrieving InvoicesYou may easily retrieve an array of a billable model's invoices using the 75 method. The 75 method returns a collection of 93 instances: 50If you would like to include pending invoices in the results, you may use the 78 method: 51You may use the 79 method to retrieve a specific invoice by its ID: 52Displaying Invoice InformationWhen listing the invoices for the customer, you may use the invoice's methods to display the relevant invoice information. For example, you may wish to list every invoice in a table, allowing the user to easily download any of them: 53Upcoming InvoicesTo retrieve the upcoming invoice for a customer, you may use the 80 method: 54Similarly, if the customer has multiple subscriptions, you can also retrieve the upcoming invoice for a specific subscription: 55Previewing Subscription InvoicesUsing the 81 method, you can preview an invoice before making price changes. This will allow you to determine what your customer's invoice will look like when a given price change is made: 56You may pass an array of prices to the 81 method in order to preview invoices with multiple new prices: 57Generating Invoice PDFsBefore generating invoice PDFs, you should use Composer to install the Dompdf library, which is the default invoice renderer for Cashier: 58From within a route or controller, you may use the 83 method to generate a PDF download of a given invoice. This method will automatically generate the proper HTTP response needed to download the invoice: 59By default, all data on the invoice is derived from the customer and invoice data stored in Stripe. The filename is based on your 84 config value. However, you can customize some of this data by providing an array as the second argument to the 83 method. This array allows you to customize information such as your company and product details: 60The 83 method also allows for a custom filename via its third argument. This filename will automatically be suffixed with 87: 61Custom Invoice RendererCashier also makes it possible to use a custom invoice renderer. By default, Cashier uses the 88 implementation, which utilizes the dompdf PHP library to generate Cashier's invoices. However, you may use any renderer you wish by implementing the 89 interface. For example, you may wish to render an invoice PDF using an API call to a third-party PDF rendering service: 62Once you have implemented the invoice renderer contract, you should update the 90 configuration value in your application's 91 configuration file. This configuration value should be set to the class name of your custom renderer implementation.CheckoutCashier Stripe also provides support for Stripe Checkout. Stripe Checkout takes the pain out of implementing custom pages to accept payments by providing a pre-built, hosted payment page. The following documentation contains information on how to get started using Stripe Checkout with Cashier. To learn more about Stripe Checkout, you should also consider reviewing Stripe's own documentation on Checkout. Product CheckoutsYou may perform a checkout for an existing product that has been created within your Stripe dashboard using the 92 method on a billable model. The 92 method will initiate a new Stripe Checkout session. By default, you're required to pass a Stripe Price ID: 63If needed, you may also specify a product quantity: 64When a customer visits this route they will be redirected to Stripe's Checkout page. By default, when a user successfully completes or cancels a purchase they will be redirected to your 43 route location, but you may specify custom callback URLs using the 95 and 96 options: 65When defining your 95 checkout option, you may instruct Stripe to add the checkout session ID as a query string parameter when invoking your URL. To do so, add the literal string 98 to your 95 query string. Stripe will replace this placeholder with the actual checkout session ID: 66Promotion CodesBy default, Stripe Checkout does not allow user redeemable promotion codes. Luckily, there's an easy way to enable these for your Checkout page. To do so, you may invoke the 00 method: 67Single Charge CheckoutsYou can also perform a simple charge for an ad-hoc product that has not been created in your Stripe dashboard. To do so you may use the 01 method on a billable model and pass it a chargeable amount, a product name, and an optional quantity. When a customer visits this route they will be redirected to Stripe's Checkout page: 68
Subscription Checkouts
You may also use Stripe Checkout to initiate subscriptions. After defining your subscription with Cashier's subscription builder methods, you may call the 92method. When a customer visits this route they will be redirected to Stripe's Checkout page: 69Just as with product checkouts, you may customize the success and cancellation URLs: 70Of course, you can also enable promotion codes for subscription checkouts: 69
Stripe Checkout & Trial PeriodsOf course, you can define a trial period when building a subscription that will be completed using Stripe Checkout: 72However, the trial period must be at least 48 hours, which is the minimum amount of trial time supported by Stripe Checkout. Subscriptions & WebhooksRemember, Stripe and Cashier update subscription statuses via webhooks, so there's a possibility a subscription might not yet be active when the customer returns to the application after entering their payment information. To handle this scenario, you may wish to display a message informing the user that their payment or subscription is pending. Collecting Tax IDsCheckout also supports collecting a customer's Tax ID. To enable this on a checkout session, invoke the 07 method when creating the session: 73When this method is invoked, a new checkbox will be available to the customer that allows them to indicate if they're purchasing as a company. If so, they will have the opportunity to provide their Tax ID number.
Guest CheckoutsUsing the 09 method, you may initiate checkout sessions for guests of your application that do not have an "account": 74Similarly to when creating checkout sessions for existing users, you may utilize additional methods available on the 10 instance to customize the guest checkout session: 75After a guest checkout has been completed, Stripe can dispatch a 11 webhook event, so make sure to configure your Stripe webhook to actually send this event to your application. Once the webhook has been enabled within the Stripe dashboard, you may . The object contained in the webhook payload will be a 92 object that you may inspect in order to fulfill your customer's order.Handling Failed PaymentsSometimes, payments for subscriptions or single charges can fail. When this happens, Cashier will throw an 13 exception that informs you that this happened. After catching this exception, you have two options on how to proceed.First, you could redirect your customer to the dedicated payment confirmation page which is included with Cashier. This page already has an associated named route that is registered via Cashier's service provider. So, you may catch the 14 exception and redirect the user to the payment confirmation page: 76On the payment confirmation page, the customer will be prompted to enter their credit card information again and perform any additional actions required by Stripe, such as "3D Secure" confirmation. After confirming their payment, the user will be redirected to the URL provided by the 15 parameter specified above. Upon redirection, 16 (string) and 17 (integer) query string variables will be added to the URL. The payment page currently supports the following payment method types:
Alternatively, you could allow Stripe to handle the payment confirmation for you. In this case, instead of redirecting to the payment confirmation page, you may setup Stripe's automatic billing emails in your Stripe dashboard. However, if an 14 exception is caught, you should still inform the user they will receive an email with further payment confirmation instructions.Payment exceptions may be thrown for the following methods: 49, 61, and 65 on models using the 93 trait. When interacting with subscriptions, the 76 method on the 24, and the 25 and 35 methods on the 64 and 28 models may throw incomplete payment exceptions.Determining if an existing subscription has an incomplete payment may be accomplished using the 20 method on the billable model or a subscription instance: 3You can derive the specific status of an incomplete payment by inspecting the 30 property on the exception instance: 78Strong Customer AuthenticationIf your business or one of your customers is based in Europe you will need to abide by the EU's Strong Customer Authentication (SCA) regulations. These regulations were imposed in September 2019 by the European Union to prevent payment fraud. Luckily, Stripe and Cashier are prepared for building SCA compliant applications.
Payments Requiring Additional ConfirmationSCA regulations often require extra verification in order to confirm and process a payment. When this happens, Cashier will throw a 13 exception that informs you that extra verification is needed. More information on how to handle these exceptions be found can be found in the documentation on .Payment confirmation screens presented by Stripe or Cashier may be tailored to a specific bank or card issuer's payment flow and can include additional card confirmation, a temporary small charge, separate device authentication, or other forms of verification. Incomplete and Past Due StateWhen a payment needs additional confirmation, the subscription will remain in an 16 or 19 state as indicated by its 17 database column. Cashier will automatically activate the customer's subscription as soon as payment confirmation is complete and your application is notified by Stripe via webhook of its completion.For more information on 16 and 19 states, please refer to .Off-Session Payment NotificationsSince SCA regulations require customers to occasionally verify their payment details even while their subscription is active, Cashier can send a notification to the customer when off-session payment confirmation is required. For example, this may occur when a subscription is renewing. Cashier's payment notification can be enabled by setting the 37 environment variable to a notification class. By default, this notification is disabled. Of course, Cashier includes a notification class you may use for this purpose, but you are free to provide your own notification class if desired: 79To ensure that off-session payment confirmation notifications are delivered, verify that for your application and the 33 webhook is enabled in your Stripe dashboard. In addition, your 93 model should also use Laravel's 40 trait.
Stripe SDKMany of Cashier's objects are wrappers around Stripe SDK objects. If you would like to interact with the Stripe objects directly, you may conveniently retrieve them using the 41 method: 80You may also use the 42 method to update a Stripe subscription directly: 81You may invoke the 43 method on the 44 class if you would like to use the 45 client directly. For example, you could use this method to access the 46 instance and retrieve a list of prices from your Stripe account: 82TestingWhen testing an application that uses Cashier, you may mock the actual HTTP requests to the Stripe API; however, this requires you to partially re-implement Cashier's own behavior. Therefore, we recommend allowing your tests to hit the actual Stripe API. While this is slower, it provides more confidence that your application is working as expected and any slow tests may be placed within their own PHPUnit testing group. When testing, remember that Cashier itself already has a great test suite, so you should only focus on testing the subscription and payment flow of your own application and not every underlying Cashier behavior. To get started, add the testing version of your Stripe secret to your 47 file: 2Now, whenever you interact with Cashier while testing, it will send actual API requests to your Stripe testing environment. For convenience, you should pre-fill your Stripe testing account with subscriptions / prices that you may use during testing. |