使用 Stripe 和 PHP 輕鬆接收付款
介紹
很多時候,我們的應用程式需要提供一種簡單的方式來支付購買產品或服務的費用。 Stripe 是接收付款的好選擇。在這篇文章中,我們將學習如何建立條紋付款鏈接,以便您可以將用戶重新導向到這些連結以發送付款。
什麼是條紋?
Stripe 是一家提供線上支付處理服務的科技公司,允許企業透過網路接受付款。它提供了一套工具和 API,使公司能夠管理線上交易、訂閱和其他與付款相關的任務。
開始寫程式碼之前,我們必須先了解以下Stripe元件:
- 產品:產品代表您想要銷售的商品或服務。其中包括名稱、描述和定價詳細資訊等。
-
價格:價格是產品的特定定價配置。它定義了客戶為產品支付的金額,以及任何其他定價詳細信息,例如貨幣、計費週期和定價等級。例如,對於名為「社區會員」的服務,您可以有兩個價格:
- 按年付費,用戶每年支付 50 美元。
- 按月付費,用戶每月支付 3.5 美元。
付款連結:付款連結是允許客戶以特定價格付款的 URL。當客戶點擊付款連結時,他們會被重定向到 Stripe 託管的付款頁面,可以在其中輸入付款資訊並完成交易。付款連結可以透過電子郵件、訊息應用程式分享,或嵌入您的網站。
價格也允許我們定義付款類型,可以是「定期」或「一次性」。對於“社區會員資格範例”,年度付款可以是 one_type,每月付款可以是經常性的。每年,用戶都會續訂(或不續訂)會員資格,並重新選擇付款方式。
安裝 Stripe PHP 元件
stripe php 庫可以使用 Composer 安裝,因此,要安裝它,您只需在專案根資料夾中執行以下命令:
composer require stripe/stripe-php
檢索開發者 API 金鑰
在檢索 API 金鑰之前,您必須在 Stripe 上註冊。註冊後,您可以按照以下步驟操作:
- 登入您的 Stripe 帳號。
- 點擊螢幕右上角的齒輪圖標,然後選擇「開發者」。
- 點擊“API 金鑰”,您就可以建立它們。
建立條紋價格
我們可以先建立產品,然後建立價格,或將產品名稱嵌入價格選項中來建立 Stripe Price。讓我們使用第一種方式進行編碼,這樣我們就可以看到所有的過程。
$stripe = new \Stripe\StripeClient(<your_stripe_api_key>); $product = $stripe->products->create([ 'name' => 'Community Subscription', 'description' => 'A Subscription to our community', ]); $price = $stripe->prices->create([ 'currency' => 'usd', 'unit_amount' => 5025, 'product': $product->id, 'type' => 'one_time' ]);
我們一步一步解釋一下上面的程式碼:
- 我們建立一個新的 StripeClient 並傳遞我們的 stripe api 金鑰。
- 然後,我們建立一個名為「社群訂閱」的新產品。
- 最後,我們為最近創建的產品創建一個價格,具有以下功能:
- 它使用美元貨幣。
- 它透過 ID 引用所建立的產品。
- 付款不會重複進行。
unit_amount 參數值得特別注意。 Stripe 文件對unit_amount 進行瞭如下描述:「以美分為單位的正整數(或免費價格為0),表示收費金額。」這意味著我們必須將價格乘以100 以將其轉換為美分,然後再傳遞給unit_amount 參數。例如,如果價格為 10.99 美元,我們會將 unit_amount 設定為 1099。這是一個常見問題,因此請務必仔細檢查您的程式碼,以避免任何意外的定價問題。
例如,如果您有一個「$amount」變量,它會保存一個浮點值作為金額,您可以編寫以下程式碼:
$formattedAmount = (int)($amount * 100);
建立付款連結
到目前為止,我們已經創建了一個格式正確的金額的價格。現在是時候建立付款連結了。
$stripe = new \Stripe\StripeClient(<your_stripe_api_key>); $paymentLink = $stripe->paymentLinks->create([ 'line_items' => [ [ 'price' => $price->id, 'quantity' => 1, ] ], 'after_completion' => [ 'type' => 'redirect', 'redirect' => [ 'url' => <your redirect link> ] ] ]);
讓我們一步一步解釋一下:
- We create the StripeClient object as before.
- Then, we create the payment link by using the following options:
- line_items: Here you can include all the items we want to add for selling. In this case we only add the created price and we only sell one unit.
- after_completion: We instruct Stripe to redirect to an url after the payment is completed.
We could redirect to an intermediate url which could perform some stuff such as updating our database register payment. The following code shows a simple Symfony controller which would perform the required tasks and then would redirect to the final url where the user will see that the payment has been completed.
class StripeController extends AbstractController { #[Route('/confirm-payment', name: 'confirm-payment', methods: ['GET'])] public function confirmPayment(Request $request): Response { // Here you perform the necessary stuff $succeedUrl = '...'; return new RedirectResponse($succeedUrl); } }
After we have created the PaymentLink object, we can access the string payment url by the url property:
$paymentUrl = $paymentLink->url;
Conclusion
In this post we have learned how to configure our php backend to easily accept payments with stripe using the stripe-php component.
Processing the payments in your php backend offers some advantages such as:
- Keep sensitive payment information, such as the API keys, secure.
- Gives more control over the payment flow and allows for greater flexibility in handling different payment scenarios.
If you like my content and enjoy reading it and you are interested in learning more about PHP, you can read my ebook about how to create an operation-oriented API using PHP and the Symfony Framework. You can find it here: Building an Operation-Oriented Api using PHP and the Symfony Framework: A step-by-step guide
以上是使用 Stripe 和 PHP 輕鬆接收付款的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP變量作用域常見問題及解決方法包括:1.函數內部無法訪問全局變量,需使用global關鍵字或參數傳入;2.靜態變量用static聲明,只初始化一次並在多次調用間保持值;3.超全局變量如$_GET、$_POST可在任何作用域直接使用,但需注意安全過濾;4.匿名函數需通過use關鍵字引入父作用域變量,修改外部變量則需傳遞引用。掌握這些規則有助於避免錯誤並提升代碼穩定性。

PHP註釋代碼常用方法有三種:1.單行註釋用//或#屏蔽一行代碼,推薦使用//;2.多行註釋用/.../包裹代碼塊,不可嵌套但可跨行;3.組合技巧註釋如用/if(){}/控制邏輯塊,或配合編輯器快捷鍵提升效率,使用時需注意閉合符號和避免嵌套。

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

寫好PHP註釋的關鍵在於明確目的與規範,註釋應解釋“為什麼”而非“做了什麼”,避免冗餘或過於簡單。 1.使用統一格式,如docblock(/*/)用於類、方法說明,提升可讀性與工具兼容性;2.強調邏輯背後的原因,如說明為何需手動輸出JS跳轉;3.在復雜代碼前添加總覽性說明,分步驟描述流程,幫助理解整體思路;4.合理使用TODO和FIXME標記待辦事項與問題,便於後續追踪與協作。好的註釋能降低溝通成本,提升代碼維護效率。

易於效率,啟動啟動tingupalocalserverenverenvirestoolslikexamppandacodeeditorlikevscode.1)installxamppforapache,mysql,andphp.2)uscodeeditorforsyntaxssupport.3)

在PHP中獲取字符串特定索引字符可用方括號或花括號,但推薦方括號;索引從0開始,超出範圍訪問返回空值,不可賦值;處理多字節字符需用mb_substr。例如:$str="hello";echo$str[0];輸出h;而中文等字符需用mb_substr($str,1,1)獲取正確結果;實際應用中循環訪問前應檢查字符串長度,動態字符串需驗證有效性,多語言項目建議統一使用多字節安全函數。

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

在PHP中取字符串前N個字符可用substr()或mb_substr(),具體步驟如下:1.使用substr($string,0,N)截取前N個字符,適用於ASCII字符且簡單高效;2.處理多字節字符(如中文)時應使用mb_substr($string,0,N,'UTF-8'),並確保啟用mbstring擴展;3.若字符串含HTML或空白字符,應先用strip_tags()去除標籤、trim()清理空格,再截取以保證結果乾淨。
