Stripe を単一製品の Django Python ショップに統合する
このシリーズの最初の部分では、htmx を使用して Django オンライン ショップを作成しました。
この 2 番目のパートでは、Stripe を使用して注文を処理します。
私たちがやること
支払いを安全に処理するために Stripe を統合します。これが私たちが達成したいことです:
- 購入ビューでは、まず Stripe チェックアウト セッションを作成し、顧客を対応する URL にリダイレクトします。ここで、販売する製品、その数量、購入が成功した後に顧客がリダイレクトされる場所 (success_url) を Stripe に伝えます。
- 顧客は、Stripe のチェックアウト ページに支払いの詳細を入力し、支払いを完了します。次に、Stripe は Web サイト上の Webhook エンドポイントに POST リクエストを作成し、そこでイベントをリッスンし、それに応じて処理します。支払いが成功すると、注文がデータベースに保存され、顧客 (およびスタッフ ユーザー) に購入について通知されます。
- 最後に、Webhook が 200 OK HTTP ステータス コードを含む応答を返した場合、Stripe は最初のステップで作成した success_url にリダイレクトします。
Django Python ストア用の Stripe のセットアップ
まず Stripe にジャンプして次のことを行う必要があります:
- Stripe アカウントを作成します。
- 製品を作成します (支払い ID を使用)。
- Webhook を作成します。
1: Stripe アカウントを作成する
まず、Stripe アカウントを作成します。現時点では、アカウントを有効にする必要はありません。テストモードで作業するだけで、テスト中に実際に支払いを行うことができなくなります。 API キー ページに移動し、公開可能キーと秘密キーを取得します。これらをプロジェクト環境変数 (STRIPE_PUBLISHABLE_KEY および STRIPE_SECRET_KEY) に保存します。これらのキーを使用して、Stripe リクエストを認証します。
2: 製品を作成する
製品ページで新しい製品を作成します。詳細を入力し、支払いタイプを1回限りに設定します。製品は次のようになります:
製品を追加 を押すと、製品リストに製品が表示されるはずです。それをクリックして 価格設定 セクションまで下にスクロールすると、作成した価格項目の API ID が見つかります。これは、price_3ODP5… のようなものであるはずです。これを環境変数 (STRIPE_PRICE_ID) に保存します。これは、Stripe チェックアウト セッションを作成するときに必要になります。
3: Webhook を作成する
支払いが完了したときに Stripe が呼び出す Webhook エンドポイントを作成する必要があります。 Webhook ページで、ローカル環境でのテストを選択します。これにより、リクエストを http://127.0.0.1:8000 などのローカル URL に転送できるようになります。まず、Stripe CLI をダウンロードします。次に、次のことができます:
- Stripe にログインする
stripe login
- 作成する Webhook エンドポイントにイベントを転送します。
stripe listen --forward-to http://127.0.0.1:8000/webhook > Ready! Your webhook signing secret is whsec_06531a7ba22363ac038f284ac547906b89e5c939f8d55dfd03a3619f9adc590a (^C to quit)
これにより、購入が完了すると、Stripe は Webhook 呼び出しをローカル エンドポイントに転送します。このコマンドは Webhook 署名シークレットをログに記録します。これもプロジェクト環境変数 (STRIPE_WEBHOOK_SECRET) として保存する必要があります。これは、リクエストが実際に Stripe から送信されたものであること、および正しい Webhook を処理していることを確認するのに役立ちます。
このセクションが終わるまでに、4 つの Stripe 環境変数が完成しているはずです。 ecommerce_site/settings.py:
にそれらをロードできるようになりました。
# ecommerce_site/settings.py import os from dotenv import load_dotenv load_dotenv() STRIPE_PUBLISHABLE_KEY = os.environ.get("STRIPE_PUBLISHABLE_KEY") STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY") STRIPE_PRICE_ID = os.environ.get("STRIPE_PRICE_ID") STRIPE_WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET")
注: 環境変数をロードするために python-dotenv を使用しています。
ビューを拡張する
次に、チェックアウト セッション、購入成功ビュー、Webhook ビューを作成して、ビューを拡張して Stripe を統合する必要があります。
1: Stripe チェックアウト セッションを作成する
購入フォームが有効であれば、購入ビューで Stripe チェックアウト セッションを作成します。
# ecommerce/views.py from django_htmx import HttpResponseClientRedirect from django.conf import settings import stripe @require_POST def purchase(request): form = OrderForm(request.POST) if form.is_valid(): quantity = form.cleaned_data["quantity"] # replace time.sleep(2) with the following code ⬇️ # 1 - set stripe api key stripe.api_key = settings.STRIPE_SECRET_KEY # 2 - create success url success_url = ( request.build_absolute_uri( reverse("purchase_success") ) + "?session_id={CHECKOUT_SESSION_ID}" ) # 3 - create cancel url cancel_url = request.build_absolute_uri(reverse("home")) # 4 - create checkout session checkout_session = stripe.checkout.Session.create( line_items=[ { "price": settings.STRIPE_PRICE_ID, "quantity": quantity, } ], mode="payment", success_url=success_url, cancel_url=cancel_url ) # 5 - redirect to checkout session url return HttpResponseClientRedirect(checkout_session.url) return render(request, "product.html", {"form": form})
これを詳しく見てみましょう:
- We first set the Stripe API key.
- We then create a successful purchase URL pointing to the purchase_success view (which we'll create in the next step). Stripe should automatically populate the CHECKOUT_SESSION_ID.
- We create a URL for when a purchase is canceled — for example, when the customer changes their mind. In this case, it’s just the home view.
- We create a Stripe checkout session with our price ID (the product identifier) and the quantity the customer wants to purchase.
- Stripe returns a session object from which we can extract the URL and redirect the customer. Since this request is coming from htmx, we can’t really use the standard Django redirect function. Instead, we use the django-htmx package, which provides this HttpResponseClientRedirect class.
2: Create the Successful Purchase View
After completing the purchase, Stripe will redirect the customer to our specified success_url. Here, we can handle the post-purchase logic:
from django.shortcuts import redirect def purchase_success(request): session_id = request.GET.get("session_id") if session_id is None: return redirect("home") stripe.api_key = settings.STRIPE_SECRET_KEY try: stripe.checkout.Session.retrieve(session_id) except stripe.error.InvalidRequestError: messages.error(request, "There was a problem while buying your product. Please try again.") return redirect("home") return render(request, "purchase_success.html")
In this view, we first check if the session_id query parameter is present. If it is, we retrieve the corresponding session from Stripe using the secret key and the session_id. We then render the successful purchase template, which looks like this:
# ecommerce/templates/purchase_success.html {% extends "base.html" %} {% block content %} <section> <header> <h2>Thank you for your purchase</h2> <p> Your purchase was successful. You will receive an email with the details of your purchase soon. </p> </header> </section> {% endblock %}
You should also add it to the urlpatterns:
# ecommerce_site/urls.py # ... same imports as before urlpatterns = [ # ... same urls as before path("purchase_success", views.purchase_success, name="purchase_success"), # ⬅️ new ]
3: Create the Webhook View
While the customer is in the purchase process, and before they are redirected to the success view, Stripe will call our webhook endpoint (remember to have the webhook listener running, as explained in the earlier 'Create the Webhook' section of this post):
from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY sig_header = request.headers.get('stripe-signature') payload = request.body event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except stripe.error.SignatureVerificationError: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event.type == "checkout.session.completed": # TODO: create line orders return HttpResponse(status=200) return HttpResponse(status=400)
Let’s break this down:
- We try to construct a Stripe event from the payload, the signature header, and the webhook secret: the first is used to build the actual event, and the last two variables are relevant to validate the authenticity of the request.
- If the signature verification fails, we return a 400 HTTP response. Remember that Stripe is actually calling this endpoint, not our customer, so Stripe will know what to do in this scenario.
- We check if the event type is checkout.session.completed, i.e., if a customer successfully paid for our product. For now, we don’t do much else here, but we will process the order in the next step.
Note: A Stripe event can have multiple types but we will only handle completed sessions in this post. However, you can (and should) extend a webhook by following the docs.
You should also add this view to urlpatterns:
# ecommerce_site/urls.py # ... same imports as before urlpatterns = [ # ... same urls as before path("webhook", views.webhook, name="webhook"), # ⬅️ new ]
If everything works well, once you click “buy”, you should be redirected to a Stripe payment page. Since we are in test mode, we can fill in the payment details with dummy data, like a 4242 4242 4242 4242 card:
Once you press Pay, Stripe should call the webhook view and redirect you to the purchase_success view. Congratulations, you have successfully processed a payment with Stripe!
Create the Orders and Notify Users
Once a purchase is completed, we need to do a few things in the webhook view:
- Save the order information in our database.
- Notify staff users about the recent purchase.
- Send a confirmation email to the customer.
Let’s create a LineOrder database model in ecommerce/models.py to store some of the order information:
# ecommerce/models.py from django.db import models class LineOrder(models.Model): quantity = models.IntegerField() name = models.CharField(max_length=255, null=True, blank=True) email = models.EmailField(null=True, blank=True) shipping_details = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Order {self.id} - {self.quantity} units"
Remember to create and run the migrations:
python manage.py makemigrations # ⬅️ creates the migration files python manage.py migrate # ⬅️ applies the migrations in the database
We can now create a function to process the orders and call it from the webhook view:
# ecommerce/views.py @csrf_exempt def webhook(request): # ...same code as before if event.type == "checkout.session.completed": create_line_orders(event.data.object) # ⬅️ new return HttpResponse(status=200) return HttpResponse(status=400) # new ⬇️ def create_line_orders(session: stripe.checkout.Session): line_items = stripe.checkout.Session.list_line_items(session.id) for line_item in line_items.data: LineOrder.objects.create( name=session.customer_details.name, email=session.customer_details.email, shipping_details=session.shipping_details, quantity=line_item.quantity, ) mail.send_mail( "Your order has been placed", f""" Hi {session.customer_details.name}, Your order has been placed. Thank you for shopping with us! You will receive an email with tracking information shortly. Best, The one product e-commerce Team """, "from@example.com", [session.customer_details.email], ) staff_users = User.objects.filter(is_staff=True) mail.send_mail( "You have a new order!", """ Hi team! You have a new order in your shop! go to the admin page to see it. Best, The one product e-commerce Team """, "from@example.com", [user.email for user in staff_users], )
Let’s break this down:
- We first create line order instances from the Stripe session and send a confirmation email to the customer about their purchase.
- We then send an email to all staff users telling them to check the admin panel.
You can now register the LineOrder model in the admin panel, so it’s accessible to staff users:
# ecommerce/admin.py from django.contrib import admin from ecommerce.models import LineOrder # Register your models here. admin.site.register(LineOrder)
When staff users log in to the admin page, they will now be able to check new orders and process them accordingly — in this case, pack and ship mugs to the customer!
Some Tips to Optimize Your Django Store
Here are some tips to further improve on the store you've built:
- テストの作成 - GitHub リポジトリでいくつかの例を参照できます。
- さらに販売する製品がある場合は、それらのデータベース モデルを作成し、ForeignKey を介して LineOrder を接続します。
- Django の電子メールのドキュメントに従って電子メールの設定を構成します。 django-post-office などのライブラリを使用して電子メール テンプレートとキューを管理することもできます。
- Web サイトをデプロイしたら、(ローカル リスナーではなく) 実際の Webhook を作成します。
- 埋め込みチェックアウト フォームなど、これまでに説明したチェックアウト プロセスの代替案については、Stripe ドキュメントをご覧ください。
まとめ
この 2 部構成のシリーズでは、Django、htmx、Stripe を使用して単一製品の電子商取引サイトを構築することに成功しました。このガイドでは、Django プロジェクトのセットアップ、シームレスなユーザー操作のための htmx の統合、Stripe による安全な支払いの組み込みについて説明しました。
また、データベースへの注文情報の保存、スタッフ ユーザーへの新規購入の通知、顧客への確認メールの送信など、注文処理の処理方法についても説明しました。これらの基盤を使用すると、特定のニーズに合わせて e コマース サイトをさらにカスタマイズおよび拡張できます。
コーディングを楽しんでください!
追伸Python の投稿を報道後すぐに読みたい場合は、Python Wizardry ニュースレターを購読して、投稿を 1 つも見逃さないようにしてください。
以上がStripe を単一製品の Django Python ショップに統合するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Pythonは学習と使用が簡単ですが、Cはより強力ですが複雑です。 1。Python構文は簡潔で初心者に適しています。動的なタイピングと自動メモリ管理により、使いやすくなりますが、ランタイムエラーを引き起こす可能性があります。 2.Cは、高性能アプリケーションに適した低レベルの制御と高度な機能を提供しますが、学習しきい値が高く、手動メモリとタイプの安全管理が必要です。

限られた時間でPythonの学習効率を最大化するには、PythonのDateTime、時間、およびスケジュールモジュールを使用できます。 1. DateTimeモジュールは、学習時間を記録および計画するために使用されます。 2。時間モジュールは、勉強と休息の時間を設定するのに役立ちます。 3.スケジュールモジュールは、毎週の学習タスクを自動的に配置します。

Pythonは開発効率でCよりも優れていますが、Cは実行パフォーマンスが高くなっています。 1。Pythonの簡潔な構文とリッチライブラリは、開発効率を向上させます。 2.Cのコンピレーションタイプの特性とハードウェア制御により、実行パフォーマンスが向上します。選択を行うときは、プロジェクトのニーズに基づいて開発速度と実行効率を比較検討する必要があります。

Pythonを1日2時間学ぶだけで十分ですか?それはあなたの目標と学習方法に依存します。 1)明確な学習計画を策定し、2)適切な学習リソースと方法を選択します。3)実践的な実践とレビューとレビューと統合を練習および統合し、統合すると、この期間中にPythonの基本的な知識と高度な機能を徐々に習得できます。

PythonとCにはそれぞれ独自の利点があり、選択はプロジェクトの要件に基づいている必要があります。 1)Pythonは、簡潔な構文と動的タイピングのため、迅速な開発とデータ処理に適しています。 2)Cは、静的なタイピングと手動メモリ管理により、高性能およびシステムプログラミングに適しています。

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

Pythonは、自動化、スクリプト、およびタスク管理に優れています。 1)自動化:OSやShutilなどの標準ライブラリを介してファイルバックアップが実現されます。 2)スクリプトの書き込み:Psutilライブラリを使用してシステムリソースを監視します。 3)タスク管理:スケジュールライブラリを使用してタスクをスケジュールします。 Pythonの使いやすさと豊富なライブラリサポートにより、これらの分野で優先ツールになります。

Web開発におけるPythonの主要なアプリケーションには、DjangoおよびFlaskフレームワークの使用、API開発、データ分析と視覚化、機械学習とAI、およびパフォーマンスの最適化が含まれます。 1。DjangoandFlask Framework:Djangoは、複雑な用途の迅速な発展に適しており、Flaskは小規模または高度にカスタマイズされたプロジェクトに適しています。 2。API開発:フラスコまたはdjangorestFrameworkを使用して、Restfulapiを構築します。 3。データ分析と視覚化:Pythonを使用してデータを処理し、Webインターフェイスを介して表示します。 4。機械学習とAI:Pythonは、インテリジェントWebアプリケーションを構築するために使用されます。 5。パフォーマンスの最適化:非同期プログラミング、キャッシュ、コードを通じて最適化
