# 高度なシステムを構築する LLM の手順: Stripe は、ほとんどの組み込みで Payment Intents ではなく Payment Element とともに Checkout Sessions API を使用することを推奨します。Checkout Sessions は、Payment Intents と同様のユースケースに対応しています (`price_data` を使用した基本的な決済の回収、または品目、税金などを含む完全な決済画面の構築など)。Adaptive Pricing などの一部の機能は、Checkout Sessions でのみ利用できます。ユーザーが明示的に要求しない限り、Payment Intents API は使用しないでください。必要となるコード量が大幅に多くなるためです。Checkout Sessions API と Elements の詳細については次を参照してください。https://docs.stripe.com/payments/quickstart-checkout-sessions. Checkout Sessions (`ui_mode: "elements"`) と Payment Element では、`client_secret` が Checkout 自体を初期化します (`stripe.initCheckoutElementsSdk`、または React で CheckoutElementsProvider を使用)。そのうえで、クライアント側での決済の確定方法が異なります。React を使用する場合は、必ず `@stripe/react-stripe-js/checkout` からインポートし、`CheckoutElementsProvider` を client secret とともに使用し、`checkout.confirm` を使用して決済を確定します。HTML を使用する場合は、必ず `checkout = stripe.initCheckoutElementsSdk({clientSecret: promise}); checkout.createPaymentElement(); paymentElement = checkout.createPaymentElement(); paymentElement.mount("#payment-element");` を使用し、`loadActionsResult = await checkout.loadActions(); actions = loadActionsResult.actions; error = await actions.confirm();` で決済を確定します。 # Payment Intents API を使用して決済ページを構築する ウェブサイトまたはアプリケーションにカスタムの Stripe 決済フォームを埋め込む方法をご紹介します。クライアント側およびサーバー側のコードで Stripe の [Web](https://docs.stripe.com/payments/elements.md) または [Mobile](https://docs.stripe.com/payments/mobile.md) Elements を使用して決済フォームを構築すると、決済を受け付けることができるようになります。このクイックスタートの基本的な内容よりも高度なスタム実装を構築するには、[決済を受け付ける](https://docs.stripe.com/payments/accept-a-payment.md?&ui=elements)をご覧ください。 [サブスクリプション](https://docs.stripe.com/billing/subscriptions/build-subscriptions.md?payment-ui=elements)などのさまざまな決済シナリオやその他の Stripe 製品については、[決済連携を比較](https://docs.stripe.com/payments/online-payments.md#compare-features-and-availability)してください。 > #### Stripe Tax、割引、配送、通貨換算の使用をご希望の場合 > > Stripe には税金、割引、配送、通貨換算を管理する Payment Element の導入があります。詳細については、[決済ページの構築](https://docs.stripe.com/payments/quickstart-checkout-sessions.md) を参照してください。 // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. const stripe = require("stripe")('<>'); const calculateTax = async (items, currency) => { const taxCalculation = await stripe.tax.calculations.create({ currency, customer_details: { address: { line1: "920 5th Ave", city: "Seattle", state: "WA", postal_code: "98104", country: "US", }, address_source: "shipping", }, line_items: items.map((item) => buildLineItem(item)), }); return taxCalculation; }; const buildLineItem = (item) => { return { amount: item.amount, // Amount in cents reference: item.id, // Unique reference for the item in the scope of the calculation }; }; // Securely calculate the order amount, including tax const calculateOrderAmount = (taxCalculation) => { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.amount_total; }; const calculateOrderAmount = (items) => { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client let total = 0; items.forEach((item) => { total += item.amount; }); return total; }; const chargeCustomer = async (customerId) => { // Lookup the payment methods available for the customer const paymentMethods = await stripe.paymentMethods.list({ customer: customerId, type: "card", }); try { // Charge the customer and payment method immediately const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: "{{CURRENCY}}", customer: customerId, payment_method: paymentMethods.data[0].id, off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log("Error code is: ", err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log("PI retrieved: ", paymentIntentRetrieved.id); } }; const chargeCustomer = async (customerId) => { // Lookup the payment methods available for the customer-configured Account const paymentMethods = await stripe.paymentMethods.list({ customer_account: customerId, type: "card", }); try { // Charge the customer-configured Account and payment method immediately const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: "{{CURRENCY}}", customer_account: customerId, payment_method: paymentMethods.data[0].id, off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log("Error code is: ", err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log("PI retrieved: ", paymentIntentRetrieved.id); } }; // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer const customer = await stripe.customers.create(); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account const account = await stripe.v2.core.accounts.create({ configuration: { customer: { capabilities: { automatic_indirect_tax: {requested: true}, }, } } }); // Create a Tax Calculation for the items being sold const taxCalculation = await calculateTax(items, '{{CURRENCY}}'); const amount = await calculateOrderAmount(taxCalculation); // Create a PaymentIntent with the order amount and currency const paymentIntent = await stripe.paymentIntents.create({ customer: customer.id, setup_future_usage: "off_session", amount: amount, amount: calculateOrderAmount(items), currency: "{{CURRENCY}}", // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: taxCalculation.id } } }, }); res.send({ clientSecret: paymentIntent.client_secret, }); // Create a PaymentIntent with the order amount and currency const paymentIntent = await stripe.paymentIntents.create({ customer_account: account.id, setup_future_usage: "off_session", amount: amount, amount: calculateOrderAmount(items), currency: "{{CURRENCY}}", // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: taxCalculation.id } } }, }); res.send({ clientSecret: paymentIntent.client_secret, }); require 'stripe' \# This is a public sample test API key. # Don’t submit any personally identifiable information in requests made with this key. # Sign in to see your own test API key embedded in code samples. $CLIENT = Stripe::StripeClient.new('<>') def calculate_tax(items, currency) $CLIENT.v1.tax.calculations.create( currency: currency, customer_details: { address: { line1: '920 5th Ave', city: 'Seattle', state: 'WA', postal_code: '98104', country: 'US', }, address_source: 'shipping', }, line_items: items.map {|item| build_line_item(item) } ) end def build_line_item(item) { amount: item['amount'], \# Amount in cents reference: item['id'], # Unique reference for the item in the scope of the calculation } end # Securely calculate the order amount, including tax def calculate_order_amount(tax_calculation) # Calculate the order total with any exclusive taxes on the server to prevent # people from directly manipulating the amount on the client tax_calculation.amount_total end def calculate_tax(items, currency) $CLIENT.v1.tax.calculations.create( currency: currency, customer_details: { address: { line1: '920 5th Ave', city: 'Seattle', state: 'WA', postal_code: '98104', country: 'US', }, address_source: 'shipping', }, line_items: items.map {|item| build_line_item(item) } ) end def build_line_item(item) { amount: item['amount'], \# Amount in cents reference: item['id'], # Unique reference for the item in the scope of the calculation } end # Securely calculate the order amount, including tax def calculate_order_amount(tax_calculation) # Calculate the order total with any exclusive taxes on the server to prevent # people from directly manipulating the amount on the client tax_calculation.amount_total end \# Securely calculate the order amount def calculate_order_amount(_items) # Calculate the order total on the server to prevent # people from directly manipulating the amount on the client _items.sum {|h| h['amount']} end def charge_customer(customerId) \# Lookup the payment methods available for the customer payment_methods = $CLIENT.v1.payment_methods.list( customer: customerId, type: 'card' ) begin # Charge the customer and payment method immediately payment_intent = $CLIENT.v1.payment_intents.create( amount: 1099, currency: '{{CURRENCY}}', customer_account: customerId, payment_method: payment_methods.data[0]['id'], off_session: true, confirm: true ) rescue Stripe::CardError => e # Error code will be authentication_required if authentication is needed puts "Error is: \#{e.error.code}" payment_intent_id = e.error.payment_intent.id payment_intent = $CLIENT.v1.payment_intents.retrieve(payment_intent_id) puts payment_intent.id end end def charge_customer(customerId) \# Lookup the payment methods available for the customer-configured Account payment_methods = $CLIENT.v1.payment_methods.list( customer_account: customerId, type: 'card' ) begin # Charge the customer-configured Account and payment method immediately payment_intent = $CLIENT.v1.payment_intents.create( amount: 1099, currency: '{{CURRENCY}}', customer_account: customerId, payment_method: payment_methods.data[0]['id'], off_session: true, confirm: true ) rescue Stripe::CardError => e # Error code will be authentication_required if authentication is needed puts "Error is: \#{e.error.code}" payment_intent_id = e.error.payment_intent.id payment_intent = $CLIENT.v1.payment_intents.retrieve(payment_intent_id) puts payment_intent.id end end \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new Customer customer = $CLIENT.v1.customers.create \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new customer-configured Account account = $CLIENT.v2.core.accounts.create({ configuration: { customer: { capabilities: {automatic_indirect_tax: {requested: true}} } } }) \# Create a Tax Calculation for the items being sold tax_calculation = calculate_tax(data['items'], '{{CURRENCY}}') \# Create a PaymentIntent with amount and currency payment_intent = $CLIENT.v1.payment_intents.create( customer: customer['id'], setup_future_usage: 'off_session', amount: calculate_order_amount(tax_calculation), amount: calculate_order_amount(data['items']), currency: '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: tax_calculation.id } } }, ) { clientSecret: payment_intent.client_secret, }.to_json \# Create a PaymentIntent with amount and currency payment_intent = $CLIENT.v1.payment_intents.create( customer_account: account['id'], setup_future_usage: 'off_session', amount: calculate_order_amount(tax_calculation), amount: calculate_order_amount(data['items']), currency: '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, hooks: { inputs: { tax: { calculation: tax_calculation.id } } }, ) { clientSecret: payment_intent.client_secret, }.to_json import stripe \# This is a public sample test API key. # Don’t submit any personally identifiable information in requests made with this key. # Sign in to see your own test API key embedded in code samples. client = stripe.StripeClient('<>') import stripe \# This is a public sample test API key. # Don’t submit any personally identifiable information in requests made with this key. # Sign in to see your own test API key embedded in code samples. client = stripe.StripeClient('<>') def calculate_tax(items, currency): tax_calculation = client.v1.tax.calculations.create(params={ 'currency': currency, 'customer_details': { "address": { "line1": "920 5th Ave", "city": "Seattle", "state": "WA", "postal_code": "98104", "country": "US", }, "address_source": "shipping", }, 'line_items': list(map(build_line_item, items)), }) return tax_calculation def build_line_item(item): return { "amount": item["amount"], \# Amount in cents "reference": item["id"], # Unique reference for the item in the scope of the calculation } def calculate_tax(items, currency): tax_calculation = client.v1.tax.calculations.create({ "currency": currency, "customer_details": { "address": { "line1": "920 5th Ave", "city": "Seattle", "state": "WA", "postal_code": "98104", "country": "US", }, "address_source": "shipping", }, "line_items": list(map(build_line_item, items)), }) return tax_calculation def build_line_item(item): return { "amount": item["amount"], \# Amount in cents "reference": item["id"], # Unique reference for the item in the scope of the calculation } \# Securely calculate the order amount, including tax def calculate_order_amount(items, tax_calculation): # Replace this constant with a calculation of the order's amount # Calculate the order total with any exclusive taxes on the server to prevent # people from directly manipulating the amount on the client order_amount = 1400 order_amount += tax_calculation['tax_amount_exclusive'] return order_amount def calculate_order_amount(items): \# Replace this constant with a calculation of the order's amount # Calculate the order total on the server to prevent # people from directly manipulating the amount on the client return 1400 def charge_customer(customer_id): \# Lookup the payment methods available for the customer payment_methods = client.v1.payment_methods.list(params={ 'customer': customer_id, 'type': 'card', }) # Charge the customer and payment method immediately try: client.v1.payment_intents.create(params={ 'amount': 1099, 'currency': '{{CURRENCY}}', 'customer': customer_id, 'payment_method': payment_methods.data[0].id, 'off_session': True, 'confirm': True, }) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print('Code is: %s' % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = client.v1.payment_intents.retrieve(payment_intent_id) def charge_customer(customer_id): \# Lookup the payment methods available for the customer-configured Account payment_methods = stripe.PaymentMethod.list( customer_account=customer_id, type='card' ) # Charge the customer-configured Account and payment method immediately try: stripe.PaymentIntent.create( amount=1099, currency='{{CURRENCY}}', customer_account=customer_id, payment_method=payment_methods.data[0].id, off_session=True, confirm=True ) except stripe.error.CardError as e: err = e.error # Error code will be authentication_required if authentication is needed print('Code is: %s' % err.code) payment_intent_id = err.payment_intent['id'] payment_intent = client.v1.payment_intents.retrieve(payment_intent_id) \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new Customer customer = client.v1.customers.create() \# Alternatively, set up a webhook to listen for the payment_intent.succeeded event # and attach the PaymentMethod to a new customer-configured Account account = client.v2.core.accounts.create({ "configuration": { "customer": { "capabilities": {"automatic_indirect_tax": {"requested": True}} }, }, }) try: data = json.loads(request.data) \# Create a Tax Calculation for the items being sold tax_calculation = calculate_tax(data['items'], '{{CURRENCY}}') \# Create a PaymentIntent with the order amount and currency intent = client.v1.payment_intents.create(params={ 'customer': customer['id'], 'setup_future_usage': 'off_session', 'amount': calculate_order_amount(data['items'], tax_calculation), 'amount': calculate_order_amount(data['items']), 'currency': '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. 'automatic_payment_methods': { 'enabled': True, }, 'hooks': { 'inputs': { 'tax': { 'calculation': tax_calculation['id'] } } }, }) return jsonify({ 'clientSecret': intent['client_secret'] }) except Exception as e: return jsonify(error=str(e)), 403 try: data = json.loads(request.data) \# Create a Tax Calculation for the items being sold tax_calculation = calculate_tax(data['items'], '{{CURRENCY}}') \# Create a PaymentIntent with the order amount and currency intent = client.v1.payment_intents.create({ "customer_account": account['id'], "setup_future_usage": 'off_session', "amount": calculate_order_amount(data['items'], tax_calculation), "amount": calculate_order_amount(data['items']), "currency": '{{CURRENCY}}', \# In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. "automatic_payment_methods": { 'enabled': True, }, "hooks": { 'inputs': { 'tax': { 'calculation': tax_calculation['id'] } } }, }) return jsonify({ 'clientSecret': intent['client_secret'] }) except Exception as e: return jsonify(error=str(e)), 403 $stripe = new \Stripe\StripeClient($stripeSecretKey); function calculateTax($stripe, $items, $currency) { $taxCalculation = $stripe->tax->calculations->create([ 'currency' => $currency, 'customer_details' => [ 'address' => [ 'line1' => '920 5th Ave', 'city' => 'Seattle', 'state' => 'WA', 'postal_code' => '98104', 'country' => 'US', ], 'address_source' => 'shipping', ], 'line_items' => array_map('buildLineItem', $items), ]); return $taxCalculation; } function buildLineItem($item) { return [ 'amount' => $item->amount, // Amount in cents 'reference' => $item->id, // Unique reference for the item in the scope of the calculation ]; } // Securely calculate the order amount, including tax function calculateOrderAmount($taxCalculation) { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return $taxCalculation->amount_total; } function calculateOrderAmount(array $items): int { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client $total = 0; foreach($items as $item) { $total += $item->amount; } return $total; } // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer $customer = $stripe->customers->create(); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account $account = $stripe->v2->core->accounts->create([ 'configuration' => [ 'customer' => [ 'capabilities' => [ 'automatic_indirect_tax' => [ 'requested' => true, ], ], ], ] ]); // Create a Tax Calculation for the items being sold $taxCalculation = calculateTax($stripe, $jsonObj->items, '{{CURRENCY}}'); // Create a PaymentIntent with amount and currency $paymentIntent = $stripe->paymentIntents->create([ 'customer' => $customer->id, 'setup_future_usage' => 'off_session', 'amount' => calculateOrderAmount($jsonObj->items, $taxCalculation), 'amount' => calculateOrderAmount($jsonObj->items), 'currency' => '{{CURRENCY}}', // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. 'automatic_payment_methods' => [ 'enabled' => true, ], 'hooks' => [ 'inputs' => [ 'tax' => [ 'calculation' => $taxCalculation->id ] ] ], ]); $output = [ 'clientSecret' => $paymentIntent->client_secret, ]; // Create a PaymentIntent with amount and currency $paymentIntent = $stripe->paymentIntents->create([ 'customer_account' => $account->id, 'setup_future_usage' => 'off_session', 'amount' => calculateOrderAmount($jsonObj->items, $taxCalculation), 'amount' => calculateOrderAmount($jsonObj->items), 'currency' => '{{CURRENCY}}', // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. 'automatic_payment_methods' => [ 'enabled' => true, ], 'hooks' => [ 'inputs' => [ 'tax' => [ 'calculation' => $taxCalculation->id ] ] ], ]); $output = [ 'clientSecret' => $paymentIntent->client_secret, ]; $stripe = new \Stripe\StripeClient($'<>'); // Lookup the payment methods available for the customer $paymentMethods = $stripe->paymentMethods->all([ 'customer' => $jsonObj->customer, 'type' => 'card' ]); // Charge the customer and payment method immediately $paymentIntent = $stripe->paymentIntents->create([ 'amount' => 1099, 'currency' => '{{CURRENCY}}', 'customer' => $jsonObj->customer, 'payment_method' => $paymentMethods->data[0]->id, 'off_session' => true, 'confirm' => true, ]); // Lookup the payment methods available for the customer-configured Account $paymentMethods = $stripe->paymentMethods->all([ 'customer_account' => $jsonObj->customer, 'type' => 'card' ]); // Charge the customer-configured Account and payment method immediately $paymentIntent = $stripe->paymentIntents->create([ 'amount' => 1099, 'currency' => '{{CURRENCY}}', 'customer_account' => $jsonObj->customer, 'payment_method' => $paymentMethods->data[0]->id, 'off_session' => true, 'confirm' => true, ]); $stripeSecretKey = '<>'; "github.com/stripe/stripe-go/v85" // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. sc = stripe.NewClient("<>") func calculateTax(items []item, currency stripe.Currency) *stripe.TaxCalculation { var lineItems []*stripe.TaxCalculationCreateLineItemParams for _, item := range items { lineItems = append(lineItems, buildLineItem(item)) } taxCalculationParams := &stripe.TaxCalculationCreateParams{ Currency: stripe.String(string(currency)), CustomerDetails: &stripe.TaxCalculationCreateCustomerDetailsParams{ Address: &stripe.AddressParams{ Line1: stripe.String("920 5th Ave"), City: stripe.String("Seattle"), State: stripe.String("WA"), PostalCode: stripe.String("98104"), Country: stripe.String("US"), }, AddressSource: stripe.String("shipping"), }, LineItems: lineItems, } taxCalculation, _ := sc.V1TaxCalculations.Create(context.TODO(), taxCalculationParams) return taxCalculation } func buildLineItem(i item) *stripe.TaxCalculationCreateLineItemParams { return &stripe.TaxCalculationCreateLineItemParams{ Amount: stripe.Int64(i.Amount), // Amount in cents Reference: stripe.String(i.Id), // Unique reference for the item in the scope of the calculation } } func calculateTax(items []item, currency stripe.Currency) *stripe.TaxCalculation { var lineItems []*stripe.TaxCalculationCreateLineItemParams for _, item := range items { lineItems = append(lineItems, buildLineItem(item)) } taxCalculationParams := &stripe.TaxCalculationCreateParams{ Currency: stripe.String(string(currency)), CustomerDetails: &stripe.TaxCalculationCreateCustomerDetailsParams{ Address: &stripe.AddressParams{ Line1: stripe.String("920 5th Ave"), City: stripe.String("Seattle"), State: stripe.String("WA"), PostalCode: stripe.String("98104"), Country: stripe.String("US"), }, AddressSource: stripe.String("shipping"), }, LineItems: lineItems, } taxCalculation, _ := sc.V1TaxCalculations.Create(context.TODO(), taxCalculationParams) return taxCalculation } func buildLineItem(i item) *stripe.TaxCalculationCreateLineItemParams { return &stripe.TaxCalculationCreateLineItemParams{ Amount: stripe.Int64(i.Amount), // Amount in cents Reference: stripe.String(i.Id), // Unique reference for the item in the scope of the calculation } } // Securely calculate the order amount, including tax func calculateOrderAmount(taxCalculation *stripe.TaxCalculation) int64 { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.AmountTotal } func calculateOrderAmount(items []item) int64 { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client total := int64(0) for _, item := range items { total += item.Amount } return total; } func chargeCustomer(CustomerID string) { // Look up the payment methods available for the customer params := &stripe.PaymentMethodListParams{ Customer: stripe.String(CustomerID), Type: stripe.String(stripe.PaymentMethodTypeCard), } var pm *stripe.PaymentMethod for p, err := range sc.V1PaymentMethods.List(context.TODO(), params).All(context.TODO()) { if err != nil { log.Printf("sc.V1Prices.List: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } pm = p break } paymentIntentParams := &stripe.PaymentIntentCreateParams{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), Customer: stripe.String(CustomerID), PaymentMethod: stripe.String(pm.ID), Confirm: stripe.Bool(true), OffSession: stripe.Bool(true), } // Charge the customer and payment method immediately _, err := sc.V1PaymentIntents.Create(context.TODO(), paymentIntentParams) if err != nil { if stripeErr, ok := err.(*stripe.Error); ok { // Error code will be authentication_required if authentication is needed fmt.Printf("Error code: %v", stripeErr.Code) paymentIntentID := stripeErr.PaymentIntent.ID paymentIntent, _ := sc.V1PaymentIntents.Retrieve(context.TODO(), paymentIntentID, nil) fmt.Printf("PI: %v", paymentIntent.ID) } } } func chargeCustomer(CustomerID string) { // Look up the payment methods available for the customer-configured Account params := &stripe.PaymentMethodListParams{ CustomerAccount: stripe.String(CustomerID), Type: stripe.String(stripe.PaymentMethodTypeCard), } var pm *stripe.PaymentMethod for p, err := range sc.V1PaymentMethods.List(context.TODO(), params).All(context.TODO()) { if err != nil { log.Printf("sc.V1Prices.List: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } pm = p break } paymentIntentParams := &stripe.PaymentIntentCreateParams{ Amount: stripe.Int64(1099), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), CustomerAccount: stripe.String(CustomerID), PaymentMethod: stripe.String(pm.ID), Confirm: stripe.Bool(true), OffSession: stripe.Bool(true), } // Charge the customer-configured Account and payment method immediately _, err := sc.V1PaymentIntents.Create(context.TODO(), paymentIntentParams) if err != nil { if stripeErr, ok := err.(*stripe.Error); ok { // Error code will be authentication_required if authentication is needed fmt.Printf("Error code: %v", stripeErr.Code) paymentIntentID := stripeErr.PaymentIntent.ID paymentIntent, _ := sc.V1PaymentIntents.Retrieve(context.TODO(), paymentIntentID, nil) fmt.Printf("PI: %v", paymentIntent.ID) } } } // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer custParams := &stripe.CustomerCreateParams{} cust, _ := sc.V1Customers.Create(context.TODO(), custParams) // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account acctParams := &stripe.V2CoreAccountCreateParams{ Configuration: &stripe.V2CoreAccountCreateConfigurationParams{ Customer: &stripe.V2CoreAccountCreateConfigurationCustomerParams{ Capabilities: &stripe.V2CoreAccountCreateConfigurationCustomerCapabilitiesParams{ AutomaticIndirectTax: &stripe.V2CoreAccountCreateConfigurationCustomerCapabilitiesAutomaticIndirectTaxParams{ Requested: stripe.Bool(true), }, }, }, }, } acct, _ := sc.V2CoreAccounts.Create(context.TODO(), acctParams) // Create a Tax Calculation for the items being sold taxCalculation := calculateTax(req.Items, "{{CURRENCY}}") // Create a PaymentIntent with amount and currency params := &stripe.PaymentIntentCreateParams{ Customer: stripe.String(cust.ID), SetupFutureUsage: stripe.String("off_session"), Amount: stripe.Int64(calculateOrderAmount(taxCalculation)), Amount: stripe.Int64(calculateOrderAmount(req.Items)), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. AutomaticPaymentMethods: &stripe.PaymentIntentCreateAutomaticPaymentMethodsParams{ Enabled: stripe.Bool(true), }, } params.Hooks = &stripe.PaymentIntentCreateHooksParams{ Inputs: &stripe.PaymentIntentCreateHooksInputsParams{ Tax: &stripe.PaymentIntentCreateHooksInputsTaxParams{ Calculation: stripe.String(taxCalculation.ID), }, }, } pi, err := sc.V1PaymentIntents.Create(context.TODO(), params) if err != nil { log.Printf("sc.V1PaymentIntents.Create: %v", pi.ClientSecret) http.Error(w, err.Error(), http.StatusInternalServerError) log.Printf("sc.V1PaymentIntents.Create: %v", err) return } writeJSON(w, struct { ClientSecret string `json:"clientSecret"` }{ ClientSecret: pi.ClientSecret, }) // Create a PaymentIntent with amount and currency params := &stripe.PaymentIntentCreateParams{ CustomerAccount: stripe.String(acct.ID), SetupFutureUsage: stripe.String("off_session"), Amount: stripe.Int64(calculateOrderAmount(taxCalculation)), Amount: stripe.Int64(calculateOrderAmount(req.Items)), Currency: stripe.String(string(stripe.Currency{{CURRENCY}})), // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. AutomaticPaymentMethods: &stripe.PaymentIntentCreateAutomaticPaymentMethodsParams{ Enabled: stripe.Bool(true), }, } params.Hooks = &stripe.PaymentIntentCreateHooksParams{ Inputs: &stripe.PaymentIntentCreateHooksInputsParams{ Tax: &stripe.PaymentIntentCreateHooksInputsTaxParams{ Calculation: stripe.String(taxCalculation.ID), }, }, } pi, err := sc.V1PaymentIntents.Create(context.TODO(), params) log.Printf("pi.Create: %v", pi.ClientSecret) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) log.Printf("pi.Create: %v", err) return } writeJSON(w, struct { ClientSecret string `json:"clientSecret"` }{ ClientSecret: pi.ClientSecret, }) using Stripe.Tax; using System.Linq; // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. services.AddSingleton(new StripeClient("<>")); private readonly StripeClient _client; public PaymentIntentApiController(StripeClient client) { _client = client; } // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer var customer = _client.V1.Customers.Create(new CustomerCreateOptions()); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account var customerOptions = new Stripe.V2.Core.AccountCreateOptions { Configuration = new Stripe.V2.Core.AccountCreateConfigurationOptions { Customer = new Stripe.V2.Core.AccountCreateConfigurationCustomerOptions { Capabilities = new Stripe.V2.Core.AccountCreateConfigurationCustomerCapabilitiesOptions { AutomaticIndirectTax = new Stripe.V2.Core.AccountCreateConfigurationCustomerCapabilitiesAutomaticIndirectTaxOptions { Requested = true, }, }, } }, }; var account = _client.V2.Core.Accounts.Create(customerOptions); // Create a Tax Calculation for the items being sold var taxCalculation = CalculateTax(request.Items, "{{CURRENCY}}"); var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions { Customer = customer.Id, SetupFutureUsage = "off_session", CustomerAccount = account.Id, SetupFutureUsage = "off_session", Amount = CalculateOrderAmount(taxCalculation), Amount = CalculateOrderAmount(request.Items), Currency = "{{CURRENCY}}", // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. AutomaticPaymentMethods = new PaymentIntentAutomaticPaymentMethodsOptions { Enabled = true, }, Hooks = new PaymentIntentHooksOptions { Inputs = new PaymentIntentHooksInputsOptions { Tax = new PaymentIntentHooksInputsTaxOptions { Calculation = taxCalculation.Id, }, }, }, Metadata = new Dictionary { { "tax_calculation", taxCalculation.Id }, }, }); return Json(new { clientSecret = paymentIntent.ClientSecret }); // Securely calculate the order amount, including tax [NonAction] public long CalculateOrderAmount(Calculation taxCalculation) { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.AmountTotal; } private long CalculateOrderAmount(Item[] items) { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client long total = 0; foreach (Item item in items) { total += item.Amount; } return total; } [NonAction] public Calculation CalculateTax(Item[] items, string currency) { var lineItems = items.Select(item => BuildLineItem(item)).ToList(); var calculationCreateOptions = new CalculationCreateOptions { Currency = currency, CustomerDetails = new CalculationCustomerDetailsOptions { Address = new AddressOptions { Line1 = "920 5th Ave", City = "Seattle", State = "WA", PostalCode = "98104", Country = "US", }, AddressSource = "shipping", }, LineItems = lineItems, }; var calculation = _client.V1.Tax.Calculations.Create(calculationCreateOptions); return calculation; } [NonAction] public CalculationLineItemOptions BuildLineItem(Item item) { return new CalculationLineItemOptions { Amount = item.Amount, // Amount in cents Reference = item.Id, // Unique reference for the item in the scope of the calculation }; } public void ChargeCustomer(string customerId) { // Lookup the payment methods available for the customer var availableMethods = _client.V1.PaymentMethods.List(new PaymentMethodListOptions { Customer = customerId, Type = "card", }); try { // Charge the customer and payment method immediately var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions { Amount = 1099, Currency = "{{CURRENCY}}", Customer = customerId, PaymentMethod = availableMethods.Data[0].Id, OffSession = true, Confirm = true }); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": // Error code will be authentication_required if authentication is needed Console.WriteLine("Error code: " + e.StripeError.Code); var paymentIntentId = e.StripeError.PaymentIntent.Id; var paymentIntent = _client.V1.PaymentIntents.Get(paymentIntentId); Console.WriteLine(paymentIntent.Id); break; default: break; } } } public void ChargeCustomer(string customerId) { // Lookup the payment methods available for the customer-configured Account var availableMethods = _client.V1.PaymentMethods.List(new PaymentMethodListOptions { CustomerAccount = customerId, Type = "card", }); try { // Charge the customer-configured Account and payment method immediately var paymentIntent = _client.V1.PaymentIntents.Create(new PaymentIntentCreateOptions { Amount = 1099, Currency = "{{CURRENCY}}", CustomerAccount = customerId, PaymentMethod = availableMethods.Data[0].Id, OffSession = true, Confirm = true }); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": // Error code will be authentication_required if authentication is needed Console.WriteLine("Error code: " + e.StripeError.Code); var paymentIntentId = e.StripeError.PaymentIntent.Id; var paymentIntent = _client.V1.PaymentIntents.Get(paymentIntentId); Console.WriteLine(paymentIntent.Id); break; default: break; } } } import com.stripe.model.Customer; import com.stripe.param.CustomerCreateParams; import com.stripe.model.v2.core.Account; import com.stripe.param.v2.core.AccountCreateParams; import com.stripe.model.PaymentMethod; import com.stripe.model.StripeCollection; import com.stripe.param.PaymentMethodListParams; import java.util.Arrays; import com.stripe.model.tax.Calculation; import com.stripe.param.tax.CalculationCreateParams; import com.stripe.param.tax.CalculationCreateParams.CustomerDetails; import com.stripe.param.tax.CalculationCreateParams.CustomerDetails.Address; import com.stripe.param.tax.CalculationCreateParams.CustomerDetails.AddressSource; import com.stripe.param.tax.CalculationCreateParams.LineItem; static Calculation calculateTax(List items, String currency) throws StripeException { List lineItems = items.stream() .map(Server::buildLineItem) .collect(Collectors.toList()); CalculationCreateParams.Builder createParamsBuilder = CalculationCreateParams.builder() .setCurrency(currency) .setCustomerDetails(CustomerDetails.builder() .setAddress(Address.builder() .setLine1("920 5th Ave") .setCity("Seattle") .setState("WA") .setPostalCode("98104") .setCountry("US") .build()) .setAddressSource(AddressSource.SHIPPING) .build()) .addAllLineItem(lineItems); return client.v1().tax().calculations().create(createParamsBuilder.build()); } static LineItem buildLineItem(CreatePaymentItem item) { return LineItem.builder() .setAmount(item.getAmount()) // Amount in cents .setReference(item.getId()) // Unique reference for the item in the scope of the calculation .build(); } // Securely calculate the order amount, including tax static long calculateOrderAmount(Calculation taxCalculation) { // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client return taxCalculation.getAmountTotal(); } static int calculateOrderAmount(CreatePaymentItem[] items) { // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client int total = 0; for (CreatePaymentItem item : items) { total += item.getAmount(); } return total; } // Call this function with the ID of the Customer you want to charge static void chargeCustomer(String customerId) throws StripeException { // Lookup the payment methods available for the customer PaymentMethodListParams listParams = new PaymentMethodListParams.Builder().setCustomer(customerId) .setType(PaymentMethodListParams.Type.CARD).build(); StripeCollection paymentMethods = client.v1().paymentMethods().list(listParams); PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder().setCurrency("{{CURRENCY}}") .setAmount(new Long(1099)) .setPaymentMethod(paymentMethods.getData().get(0).getId()) .setCustomer(customerId) .setConfirm(true) .setOffSession(true) .build(); try { // Charge the customer and payment method immediately PaymentIntent paymentIntent = client.v1().paymentIntents().create(createParams); } catch (CardException e) { // Error code will be authentication_required if authentication is needed System.out.println("Error code is : " + e.getCode()); String paymentIntentId = e.getStripeError().getPaymentIntent().getId(); PaymentIntent paymentIntent = client.v1().paymentIntents().retrieve(paymentIntentId); System.out.println(paymentIntent.getId()); } } // Call this function with the ID of the customer-configured Account you want to charge static void chargeCustomer(String customerId) throws StripeException { // Lookup the payment methods available for the customer-configured Account PaymentMethodListParams listParams = new PaymentMethodListParams.Builder().setCustomerAccount(customerId) .setType(PaymentMethodListParams.Type.CARD).build(); StripeCollection paymentMethods = client.v1().paymentMethods().list(listParams); PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder().setCurrency("{{CURRENCY}}") .setAmount(new Long(1099)) .setPaymentMethod(paymentMethods.getData().get(0).getId()) .setCustomerAccount(customerId) .setConfirm(true) .setOffSession(true) .build(); try { // Charge the customer-configured Account and payment method immediately PaymentIntent paymentIntent = client.v1().paymentIntents().create(createParams); } catch (CardException e) { // Error code will be authentication_required if authentication is needed System.out.println("Error code is : " + e.getCode()); String paymentIntentId = e.getStripeError().getPaymentIntent().getId(); PaymentIntent paymentIntent = client.v1().paymentIntents().retrieve(paymentIntentId); System.out.println(paymentIntent.getId()); } } // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. public static StripeClient client = new StripeClient("<>"); public static void main(String[] args) { port(4242); staticFiles.externalLocation(Paths.get("public").toAbsolutePath().toString()); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer CustomerCreateParams customerParams = new CustomerCreateParams.Builder().build(); Customer customer = client.v1().customers().create(customerParams); // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new customer-configured Account AccountCreateParams accountParams = AccountCreateParams .builder() .setConfiguration( AccountCreateParams.Configuration.builder() .setCustomer( AccountCreateParams.Configuration.Customer.builder() .setCapabilities( AccountCreateParams.Configuration.Customer.Capabilities.builder() .setAutomaticIndirectTax( AccountCreateParams.Configuration.Customer.Capabilities.AutomaticIndirectTax.builder() .setRequested(true) .build() ) .build() ) .build() ) .build() ) .build(); Account account = client.v2().core().accounts().create(accountParams); CreatePayment postBody = gson.fromJson(request.body(), CreatePayment.class); // Create a Tax Calculation for the items being sold Calculation taxCalculation = calculateTax(Arrays.asList(postBody.getItems()), "{{CURRENCY}}"); PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setCustomerAccount(account.getId()) .setSetupFutureUsage(PaymentIntentCreateParams.SetupFutureUsage.OFF_SESSION) .setAmount(calculateOrderAmount(taxCalculation)) .setAmount(new Long(calculateOrderAmount(postBody.getItems()))) .setCurrency("{{CURRENCY}}") // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. .setAutomaticPaymentMethods( PaymentIntentCreateParams.AutomaticPaymentMethods .builder() .setEnabled(true) .build() ) .setHooks( PaymentIntentCreateParams.Hooks .builder() .setInputs( PaymentIntentCreateParams.Hooks.Inputs .builder() .setTax( PaymentIntentCreateParams.Hooks.Inputs.Tax .builder() .setCalculation(taxCalculation.getId()) .build() ) .build() ) .build() ) .build(); // Create a PaymentIntent with the order amount and currency PaymentIntent paymentIntent = client.v1().paymentIntents().create(params); CreatePaymentResponse paymentResponse = new CreatePaymentResponse(paymentIntent.getClientSecret(), paymentIntent.getId()); return gson.toJson(paymentResponse); CreatePayment postBody = gson.fromJson(request.body(), CreatePayment.class); // Create a Tax Calculation for the items being sold Calculation taxCalculation = calculateTax(Arrays.asList(postBody.getItems()), "{{CURRENCY}}"); PaymentIntentCreateParams params = PaymentIntentCreateParams.builder() .setCustomerAccount(customer.getId()) .setSetupFutureUsage(PaymentIntentCreateParams.SetupFutureUsage.OFF_SESSION) .setAmount(calculateOrderAmount(taxCalculation)) .setAmount(new Long(calculateOrderAmount(postBody.getItems()))) .setCurrency("{{CURRENCY}}") // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. .setAutomaticPaymentMethods( PaymentIntentCreateParams.AutomaticPaymentMethods .builder() .setEnabled(true) .build() ) .setHooks( PaymentIntentCreateParams.Hooks .builder() .setInputs( PaymentIntentCreateParams.Hooks.Inputs .builder() .setTax( PaymentIntentCreateParams.Hooks.Inputs.Tax .builder() .setCalculation(taxCalculation.getId()) .build() ) .build() ) .build() ) .build(); // Create a PaymentIntent with the order amount and currency PaymentIntent paymentIntent = client.v1().paymentIntents().create(params); CreatePaymentResponse paymentResponse = new CreatePaymentResponse(paymentIntent.getClientSecret(), paymentIntent.getId()); return gson.toJson(paymentResponse); import React, { useState, useEffect } from "react"; import { loadStripe } from "@stripe/stripe-js"; import { Elements } from "@stripe/react-stripe-js"; // Make sure to call loadStripe outside of a component’s render to avoid // recreating the Stripe object on every render. // This is a public sample test API key. // Don’t submit any personally identifiable information in requests made with this key. // Sign in to see your own test API key embedded in code samples. const stripePromise = loadStripe("<>"); useEffect(() => { // Create PaymentIntent as soon as the page loads fetch("/create-payment-intent", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items: [{ id: "xl-tshirt", amount: 1000 }] }), }) .then((res) => res.json()) .then((data) => setClientSecret(data.clientSecret)); }, []); useEffect(() => { // Create PaymentIntent as soon as the page loads fetch("/create.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items: [{ id: "xl-tshirt", amount: 1000 }] }), }) .then((res) => res.json()) .then((data) => setClientSecret(data.clientSecret)); }, []); const appearance = { {{APPEARANCE}} }; {clientSecret && ( } /> } /> )} const clientSecret = new URLSearchParams(window.location.search).get( "payment_intent_client_secret" ); if (!clientSecret) { return; } stripe.retrievePaymentIntent(clientSecret).then(({paymentIntent}) => { if (!paymentIntent) { return; } setStatus(paymentIntent.status); setIntentId(paymentIntent.id); }); const stripe = useStripe(); const elements = useElements(); const [email, setEmail] = useState(''); const [message, setMessage] = useState(null); const [isLoading, setIsLoading] = useState(false); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:3000/complete", receipt_email: email, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { setMessage(error.message); } else { setMessage("An unexpected error occurred."); } setIsLoading(false); setEmail(e.target.value)} placeholder="Enter email address" /> #email { border-radius: 6px; margin-bottom: 16px; padding: 12px; border: 1px solid rgba(50, 50, 93, 0.1); max-height: 44px; font-size: 16px; width: 100%; background: white; box-sizing: border-box; }
const stripe = Stripe("<>"); // Fetches a payment intent and captures the client secret async function initialize() { const response = await fetch("/create-payment-intent", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items }), }); const { clientSecret } = await response.json(); const appearance = { {{APPEARANCE}} }; elements = stripe.elements({ appearance, clientSecret }); const paymentElementOptions = { layout: "accordion", }; const paymentElement = elements.create("payment", paymentElementOptions); paymentElement.mount("#payment-element"); } // Fetches a payment intent and captures the client secret async function initialize() { const { clientSecret } = await fetch("/create.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items }), }).then((r) => r.json()); elements = stripe.elements({ clientSecret }); const paymentElementOptions = { layout: "accordion", }; const paymentElement = elements.create("payment", paymentElementOptions); paymentElement.mount("#payment-element"); } async function handleSubmit(e) { e.preventDefault(); setLoading(true); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:4242/complete.html", receipt_email: document.getElementById("email").value, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { showMessage(error.message); } else { showMessage("An unexpected error occurred."); } setLoading(false); } async function handleSubmit(e) { e.preventDefault(); setLoading(true); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:4242/complete.html", receipt_email: document.getElementById("email").value, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { showMessage(error.message); } else { showMessage("An unexpected error occurred."); } setLoading(false); } #email { border-radius: 6px; margin-bottom: 16px; padding: 12px; border: 1px solid rgba(50, 50, 93, 0.1); max-height: 44px; font-size: 16px; width: 100%; background: white; box-sizing: border-box; } const stripe = Stripe("<>"); // Fetches the payment intent status after payment submission async function checkStatus() { const clientSecret = new URLSearchParams(window.location.search).get( "payment_intent_client_secret" ); if (!clientSecret) { setErrorState(); return; } const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret); setPaymentDetails(paymentIntent); } import { PaymentElement, useStripe, useElements, Elements } from '@stripe/react-stripe-js' import { loadStripe } from '@stripe/stripe-js' // Make sure to call loadStripe outside of a component’s render to avoid // recreating the Stripe object on every render. // This is your test publishable API key. const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) const stripe = useStripe(); const elements = useElements(); const [email, setEmail] = useState(''); const [message, setMessage] = useState(null); const [isLoading, setIsLoading] = useState(false); const { error } = await stripe.confirmPayment({ elements, confirmParams: { // Make sure to change this to your payment completion page return_url: "http://localhost:3000/success", receipt_email: email, }, }); // This point will only be reached if there is an immediate error when // confirming the payment. Otherwise, your customer will be redirected to // your `return_url`. For some payment methods like iDEAL, your customer will // be redirected to an intermediate site first to authorize the payment, then // redirected to the `return_url`. if (error.type === "card_error" || error.type === "validation_error") { setMessage(error.message); } else { setMessage("An unexpected error occurred."); } setIsLoading(false); setEmail(e.target.value)} placeholder="Enter email address" /> const appearance = { {{APPEARANCE}} }; const { payment_intent: paymentIntentId } = await searchParams if (!paymentIntentId) redirect('/') const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId) if (!paymentIntent) redirect('/') const { status } = paymentIntent \# https://dashboard.stripe.com/apikeys NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=<> STRIPE_SECRET_KEY=<> \# Set this environment variable to support webhooks — https://stripe.com/docs/webhooks#verify-events # STRIPE_WEBHOOK_SECRET=whsec_12345 const calculateTax = async (items, currency) => { const taxCalculation = await stripe.tax.calculations.create({ currency, customer_details: { address: { line1: "920 5th Ave", city: "Seattle", state: "WA", postal_code: "98104", country: "US", }, address_source: "shipping", }, line_items: items.map((item) => buildLineItem(item)), }); return taxCalculation; }; const buildLineItem = (item) => { return { amount: item.amount, // Amount in cents reference: item.id, // Unique reference for the item in the scope of the calculation }; }; // Securely calculate the order amount, including tax const calculateOrderAmount = (items, taxCalculation) => { // Replace this constant with a calculation of the order's amount // Calculate the order total with any exclusive taxes on the server to prevent // people from directly manipulating the amount on the client let orderAmount = 1400; orderAmount += taxCalculation.tax_amount_exclusive; return orderAmount; }; const calculateOrderAmount = (items) => { // Replace this constant with a calculation of the order's amount // Calculate the order total on the server to prevent // people from directly manipulating the amount on the client return 1400; }; const chargeCustomer = async (customerId) => { // Lookup the payment methods available for the customer const paymentMethods = await stripe.paymentMethods.list({ customer: customerId, type: "card", }); try { // Charge the customer and payment method immediately const paymentIntent = await stripe.paymentIntents.create({ amount: 1099, currency: "eur", customer: customerId, payment_method: paymentMethods.data[0].id, off_session: true, confirm: true, }); } catch (err) { // Error code will be authentication_required if authentication is needed console.log("Error code is: ", err.code); const paymentIntentRetrieved = await stripe.paymentIntents.retrieve(err.raw.payment_intent.id); console.log("PI retrieved: ", paymentIntentRetrieved.id); } }; // Alternatively, set up a webhook to listen for the payment_intent.succeeded event // and attach the PaymentMethod to a new Customer const customer = await stripe.customers.create(); const items = [{ id: 'xl-tshirt', amount: 1000 }] const taxCalculation = await calculateTax(items, "eur"); const amount = await calculateOrderAmount(items, taxCalculation); // Create PaymentIntent as soon as the page loads const { client_secret: clientSecret } = await stripe.paymentIntents.create({ customer: customer.id, setup_future_usage: "off_session", amount, amount: calculateOrderAmount([{ id: 'xl-tshirt' }]), currency: 'eur', // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default. automatic_payment_methods: { enabled: true, }, metadata: { tax_calculation: taxCalculation.id }, }) import 'server-only'; import Stripe from 'stripe'; export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY); export async function POST(req) { import StripePaymentSheet private lazy var addressViewController: AddressViewController? = { return AddressViewController(configuration: self.addressConfiguration, delegate: self) }() private var addressDetails: AddressViewController.AddressDetails? private var addressConfiguration: AddressViewController.Configuration { return AddressViewController.Configuration(additionalFields: .init(phone: .optional)) } private lazy var addressButton: UIButton = { let button = UIButton(type: .custom) button.setTitle("Add shipping address", for: .normal) button.backgroundColor = .systemIndigo button.layer.cornerRadius = 5 button.contentEdgeInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) button.addTarget(self, action: #selector(didTapShippingAddressButton), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() StripeAPI.defaultPublishableKey = "<>" view.addSubview(addressButton) NSLayoutConstraint.activate([ addressButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16), addressButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), addressButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -80) ]) func fetchPaymentIntent() { let url = Self.backendURL.appendingPathComponent("/create-payment-intent") let shoppingCartContent: [String: Any] = [ "items": [ ["id": "xl-shirt"] ["id": "xl-shirt", "amount": 1000] ] ] var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try? JSONSerialization.data(withJSONObject: shoppingCartContent) let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in guard let response = response as? HTTPURLResponse, response.statusCode == 200, let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any], let clientSecret = json["clientSecret"] as? String else { let message = error?.localizedDescription ?? "Failed to decode response from server." self?.displayAlert(title: "Error loading page", message: message) return } print("Created PaymentIntent") self?.paymentIntentClientSecret = clientSecret DispatchQueue.main.async { self?.payButton.isEnabled = true } }) task.resume() } var configuration = PaymentSheet.Configuration() configuration.merchantDisplayName = "Example, Inc." configuration.allowsDelayedPaymentMethods = true configuration.primaryButtonColor = UIColor(red: 1.0, green: 0.82, blue: 0.04, alpha: 1.0) configuration.applePay = .init( merchantId: "com.example.appname", merchantCountryCode: "US" ) configuration.shippingDetails = { [weak self] in return self?.addressDetails } let paymentSheet = PaymentSheet( paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration) paymentSheet.present(from: self) { [weak self] (paymentResult) in switch paymentResult { case .completed: self?.displayAlert(title: "Payment complete!") case .canceled: print("Payment canceled!") case .failed(let error): self?.displayAlert(title: "Payment failed", message: error.localizedDescription) } @objc func didTapShippingAddressButton() { present(UINavigationController(rootViewController: addressViewController!), animated: true) } // MARK: - AddressViewControllerDelegate extension CheckoutViewController: AddressViewControllerDelegate { func addressViewControllerDidFinish(_ addressViewController: AddressViewController, with address: AddressViewController.AddressDetails?) { addressViewController.dismiss(animated: true) self.addressDetails = address } } NSCameraUsageDescription Allow the app to scan cards. PaymentConfiguration.init( applicationContext, "<>" ) import androidx.compose.foundation.layout.Column import androidx.compose.ui.platform.LocalContext import com.stripe.android.PaymentConfiguration import com.stripe.android.paymentsheet.addresselement.AddressDetails import com.stripe.android.paymentsheet.addresselement.AddressLauncher import com.stripe.android.paymentsheet.addresselement.AddressLauncher.AdditionalFieldsConfiguration import com.stripe.android.paymentsheet.addresselement.AddressLauncherResult import com.stripe.android.paymentsheet.addresselement.rememberAddressLauncher private val addressConfiguration = AddressLauncher.Configuration.Builder() .additionalFields( AdditionalFieldsConfiguration( AdditionalFieldsConfiguration.FieldConfiguration.REQUIRED ) ) .allowedCountries(setOf("US", "CA", "GB")) .title("Shipping Address") .googlePlacesApiKey("(optional) YOUR KEY HERE") .build() when (paymentResult) { is PaymentSheetResult.Completed -> showToast("Payment complete!") is PaymentSheetResult.Canceled -> showToast("Payment canceled!") is PaymentSheetResult.Failed -> { error = paymentResult.error.localizedMessage ?: paymentResult.error.message } } val context = LocalContext.current var shippingDetails by remember { mutableStateOf(null) } val addressLauncher = rememberAddressLauncher { result -> when (result) { is AddressLauncherResult.Succeeded -> { shippingDetails = result.address showToast("Address selection complete!") } is AddressLauncherResult.Canceled -> showToast("Address selection canceled!") } } Column( modifier = Modifier.fillMaxWidth() ) { AddressButton { addressLauncher.present( publishableKey = PaymentConfiguration.getInstance(context).publishableKey, configuration = addressConfiguration ) } PayButton( enabled = paymentIntentClientSecret != null, onClick = { paymentIntentClientSecret?.let { onPayClicked( paymentSheet = paymentSheet, paymentIntentClientSecret = it, shippingDetails = shippingDetails, ) } } ) } PayButton( enabled = paymentIntentClientSecret != null, onClick = { paymentIntentClientSecret?.let { onPayClicked( paymentSheet = paymentSheet, paymentIntentClientSecret = it, ) } } ) @Composable private fun AddressButton( onClick: () -> Unit ) { Button( modifier = Modifier.fillMaxWidth(), onClick = onClick ) { Text("Add shipping address") } } private suspend fun fetchPaymentIntent(): Result = suspendCoroutine { continuation -> val url = "$BACKEND_URL/create-payment-intent" val shoppingCartContent = """ { "items": [ {"id":"xl-tshirt"} {"id":"xl-tshirt", "amount":1000} ] } """ val mediaType = "application/json; charset=utf-8".toMediaType() val body = shoppingCartContent.toRequestBody(mediaType) val request = Request.Builder() .url(url) .post(body) .build() OkHttpClient() .newCall(request) .enqueue(object: Callback { override fun onFailure(call: Call, e: IOException) { continuation.resume(Result.failure(e)) } override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) { continuation.resume(Result.failure(Exception(response.message))) } else { val clientSecret = extractClientSecretFromResponse(response) clientSecret?.let { secret -> continuation.resume(Result.success(secret)) } ?: run { val error = Exception("Could not find payment intent client secret in response!") continuation.resume(Result.failure(error)) } } } }) } private fun extractClientSecretFromResponse(response: Response): String? { return try { val responseData = response.body?.string() val responseJson = responseData?.let { JSONObject(it) } ?: JSONObject() responseJson.getString("clientSecret") } catch (exception: JSONException) { null } } shippingDetails: AddressDetails?, val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Example, Inc.") .shippingDetails(shippingDetails) .allowsDelayedPaymentMethods(true) .appearance( PaymentSheet.Appearance( primaryButton = PaymentSheet.PrimaryButton( colorsLight = PaymentSheet.PrimaryButtonColors( background = Color(red = 248, green = 72, blue = 94), onBackground = Color.White, border = Color.Unspecified ) ) ) ) .googlePay( PaymentSheet.GooglePayConfiguration( environment = PaymentSheet.GooglePayConfiguration.Environment.Test, countryCode = "US" ) ) .build() // Present Payment Sheet paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, configuration) PaymentConfiguration.init( getApplicationContext(), "<>" ); import com.stripe.android.paymentsheet.addresselement.AddressDetails; import com.stripe.android.paymentsheet.addresselement.AddressLauncher; import com.stripe.android.paymentsheet.addresselement.AddressLauncherResult; private AddressLauncher addressLauncher; private AddressDetails shippingDetails; private Button addressButton; private final AddressLauncher.Configuration configuration = new AddressLauncher.Configuration.Builder() .additionalFields( new AddressLauncher.AdditionalFieldsConfiguration( AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.REQUIRED ) ) .allowedCountries(new HashSet<>(Arrays.asList("US", "CA", "GB"))) .title("Shipping Address") .googlePlacesApiKey("(optional) YOUR KEY HERE") .build(); // Hook up the address button addressButton = findViewById(R.id.address_button); addressButton.setOnClickListener(this::onAddressClicked); addressLauncher = new AddressLauncher(this, this::onAddressLauncherResult); private void fetchPaymentIntent() { final String shoppingCartContent = "{\"items\": [ {\"id\":\"xl-tshirt\"}]}"; final String shoppingCartContent = "{\"items\": [ {\"id\":\"xl-tshirt\", \"amount\":1000}]}"; final RequestBody requestBody = RequestBody.create( shoppingCartContent, MediaType.get("application/json; charset=utf-8") ); Request request = new Request.Builder() .url(BACKEND_URL + "/create-payment-intent") .post(requestBody) .build(); new OkHttpClient() .newCall(request) .enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { showAlert("Failed to load data", "Error: " + e.toString()); } @Override public void onResponse( @NonNull Call call, @NonNull Response response ) throws IOException { if (!response.isSuccessful()) { showAlert( "Failed to load page", "Error: " + response.toString() ); } else { final JSONObject responseJson = parseResponse(response.body()); paymentIntentClientSecret = responseJson.optString("clientSecret"); runOnUiThread(() -> payButton.setEnabled(true)); Log.i(TAG, "Retrieved PaymentIntent"); } } }); } PaymentSheet.Configuration configuration = new PaymentSheet.Configuration.Builder("Example, Inc.") .allowsDelayedPaymentMethods(true) .primaryButtonColor(ColorStateList.valueOf(Color.rgb(248, 72, 94))) .googlePay(new PaymentSheet.GooglePayConfiguration( PaymentSheet.GooglePayConfiguration.Environment.Test, "US")) .build(); // Present Payment Sheet paymentSheet.presentWithPaymentIntent(paymentIntentClientSecret, configuration); private void onAddressClicked(View view) { AddressLauncher.Configuration addressConfiguration = new AddressLauncher.Configuration.Builder().address(shippingDetails).build(); String publishableKey = PaymentConfiguration.getInstance(this.getApplicationContext()).getPublishableKey(); addressLauncher.present( publishableKey, addressConfiguration ); } if (paymentSheetResult instanceof PaymentSheetResult.Completed) { showToast("Payment complete!"); } else if (paymentSheetResult instanceof PaymentSheetResult.Canceled) { Log.i(TAG, "Payment canceled!"); } else if (paymentSheetResult instanceof PaymentSheetResult.Failed) { Throwable error = ((PaymentSheetResult.Failed) paymentSheetResult).getError(); showAlert("Payment failed", error.getLocalizedMessage()); } private void onAddressLauncherResult(AddressLauncherResult result) { // TODO: Handle result and update your UI if (result instanceof AddressLauncherResult.Succeeded) { shippingDetails = ((AddressLauncherResult.Succeeded) result).getAddress(); } else if (result instanceof AddressLauncherResult.Canceled) { // TODO: Handle cancel } } { "name": "stripe-sample", "version": "1.0.0", "description": "A sample Stripe implementation", "main": "server.js", "scripts": { "start": "node server.js" }, "author": "stripe-samples", "license": "ISC", "dependencies": { "express": "^4.17.1", "stripe": "^21.0.1" } } { "name": "stripe-sample", "version": "0.1.0", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.17.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "^3.4.0", "stripe": "21.0.1" }, "devDependencies": { "concurrently": "4.1.2" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } require github.com/stripe/stripe-go/v85 v85.0.0 certifi==2026.1.4 chardet==5.2.0 click==8.3.1 Flask==3.1.2 idna==3.11 itsdangerous==2.2.0 Jinja2==3.1.6 MarkupSafe==3.0.3 requests==2.32.5 stripe==15.0.0 toml==0.10.2 Werkzeug==3.1.5 { "name": "stripe-sample", "version": "0.2.0", "license": "ISC", "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "express": "^4.21.0", "react": "^18.3.1", "react-dom": "^18.3.1", "react-router-dom": "^6.26.2", "react-scripts": "^5.0.1", "stripe": "^16.12.0" }, "devDependencies": { "@babel/plugin-transform-private-property-in-object": "^7.25.7", "concurrently": "^9.0.1" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start-client": "react-scripts start", "start-server": "node server.js", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "start": "concurrently \"yarn start-client\" \"yarn start-server\"" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@stripe/react-stripe-js": "^3.7.0", "@stripe/stripe-js": "^7.3.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.26.1", "react-scripts": "^5.0.1" }, "homepage": "http://localhost:3000/checkout", "proxy": "http://localhost:4242", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } 1. Build the server ~~~ pip3 install -r requirements.txt ~~~ 1. Build the server ~~~ bundle install ~~~ 1. Build the server ~~~ composer install ~~~ 1. Build the server ~~~ dotnet restore ~~~ 1. Build the server ~~~ mvn package ~~~ 2. Run the server ~~~ export FLASK_APP=server.py python3 -m flask run --port=4242 ~~~ 2. Run the server ~~~ ruby server.rb -o 0.0.0.0 ~~~ 2. Run the server ~~~ php -S 127.0.0.1:4242 --docroot=public ~~~ 2. Run the server ~~~ dotnet run ~~~ 2. Run the server ~~~ java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ~~~ 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 3. Build the client app ~~~ npm install ~~~ 4. Run the client app ~~~ npm start ~~~ 5. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Run the server ~~~ go run server.go ~~~ 2. Build the client app ~~~ npm install ~~~ 3. Run the client app ~~~ npm start ~~~ 4. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) 1. Run the server ~~~ go run server.go ~~~ 2. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) 1. Build the application ~~~ npm install ~~~ 2. Run the application ~~~ npm start ~~~ 3. Go to [http://localhost:3000/checkout](http://localhost:3000/checkout) \## API Keys This code sample uses a public sample test API key. Don’t submit any personally identifiable information in requests made with this key. The "View details" link to see the PaymentIntent details in the Dashboard won't work until you use your own test [API key](https://docs.stripe.com/keys). 1. Build the server ~~~ npm install ~~~ 2. Run the server ~~~ npm start ~~~ 3. Go to [http://localhost:4242/checkout.html](http://localhost:4242/checkout.html) \### Development 1. Build the application ~~~shell $ npm install ~~~ 2. Download and run the [Stripe CLI](https://stripe.com/docs/stripe-cli). The Stripe CLI is a developer tool that helps you build, test, and manage your integration with Stripe directly from the command line. ~~~shell $ stripe listen --forward-to localhost:3000/api/webhooks ~~~ 3. Run the application ~~~shell $ STRIPE_WEBHOOK_SECRET=$(stripe listen --print-secret) npm run dev ~~~ 4. Go to [localhost:3000](http://localhost:3000) ### Production 1. Build the application ~~~shell $ npm install $ npm build ~~~ 2. Run the application ~~~shell $ npm start ~~~ ### Stripe Node ライブラリーをインストールする パッケージをインストールし、それをコードにインポートします。また、まったくゼロから開始していて package.json ファイルが必要な場合には、コードエディターのダウンロードリンクを使用してプロジェクトファイルをダウンロードします。 #### npm ライブラリーをインストールします。 ```bash npm install --save stripe ``` #### GitHub または、stripe-node ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-node)ダウンロードします。 ### Stripe Ruby ライブラリーをインストールする Stripe ruby gem をインストールし、require を指定してコードに読み込みます。または、まったくゼロから開始していて Gemfile が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Terminal gem をインストールします。 ```bash gem install stripe ``` #### Bundler この行を Gemfile に追加します。 ```bash gem 'stripe' ``` #### GitHub または、stripe-ruby gem のソースコードを直接 [GitHub から](https://github.com/stripe/stripe-ruby)ダウンロードします。 ### Stripe Java ライブラリーをインストールする ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していてサンプルの pom.xml ファイル (Maven 用) が必要な場合は、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Maven POM に以下の依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle build.gradle ファイルに依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub JAR を直接 [GitHub から](https://github.com/stripe/stripe-java/releases/latest)ダウンロードします。 ### Stripe Python パッケージをインストールする Stripe パッケージをインストールし、コードにインポートします。まったくゼロから開始していて requirements.txt が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### pip pip を使用してパッケージをインストールします。 ```bash pip3 install stripe ``` #### GitHub stripe-python ライブラリのソースコードを [GitHub から](https://github.com/stripe/stripe-python)直接ダウンロードします。 ### Stripe PHP ライブラリーをインストールする Composer を使用してライブラリーをインストールし、シークレット API キーで初期化します。まったくゼロから開始していて composer.json ファイルが必要な場合には、コードエディターのリンクを使用してファイルをダウンロードします。 #### Composer ライブラリーをインストールします。 ```bash composer require stripe/stripe-php ``` #### GitHub または、stripe-php ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-php)ダウンロードします。 ### サーバーを設定する ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していて go.mod ファイルが必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Go 必ず Go モジュールを使用してを初期化してください。 ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub または、stripe-go モジュールのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-go)ダウンロードします。 ### Stripe.net ライブラリーをインストールする .NET または NuGet でパッケージをインストールします。まったくゼロから開始する場合には、設定済みの .csproj ファイルが含まれるファイルをダウンロードします。 #### dotnet ライブラリーをインストールします。 ```bash dotnet add package Stripe.net ``` #### NuGet ライブラリーをインストールします。 ```bash Install-Package Stripe.net ``` #### GitHub または、Stripe.net ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-dotnet)ダウンロードします。 ### Stripe ライブラリーをインストールする パッケージをインストールし、コードにインポートします。まったくゼロから開始していて `package.json` が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 ライブラリーをインストールします。 ```bash npm install --save stripe @stripe/stripe-js next ``` ### PaymentIntent を作成する [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md) を作成するエンドポイントをサーバーに追加します。PaymentIntent は、顧客の支払いライフサイクルを追跡し、支払いの試行失敗があった場合にはその記録を残して顧客への請求に重複が発生しないようにします。レスポンスで PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) を返して、クライアントで支払いを完了します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### React アプリに Stripe を追加する *PCI 準拠* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business)を維持するには、*Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) と [Stripe Elements UI ライブラリ](https://docs.stripe.com/sdks/stripejs-react.md)を使用し、支払い情報がサーバーを介することなく Stripe に直接送信されるようにします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### React アプリに Stripe を追加する *PCI 準拠* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business)を維持するには、*Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) と [Stripe Elements UI ライブラリ](https://docs.stripe.com/sdks/stripejs-react.md)を使用し、支払い情報がサーバーを介することなく Stripe に直接送信されるようにします。 ```bash npm install --save @stripe/react-stripe-js @stripe/stripe-js ``` ### Stripe.js を読み込む Stripe の[公開可能 API キー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用して `loadStripe()` を呼び出し、Stripe ライブラリを設定します。 ### Stripe.js を読み込む Stripe の[公開可能 API キー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用して `loadStripe()` を呼び出し、Stripe ライブラリを設定します。 ### Stripe.js を読み込む *PCI 準拠* (Any party involved in processing, transmitting, or storing credit card data must comply with the rules specified in the Payment Card Industry (PCI) Data Security Standards. PCI compliance is a shared responsibility and applies to both Stripe and your business)を維持するには、*Stripe.js* (Use Stripe.js’ APIs to tokenize customer information, collect sensitive card data, and accept payments with browser payment APIs) を使用して、支払い詳細がお客様のサーバーを経由せずに直接 Stripe に送られるようにします。Stripe.js を常に js.stripe.com から読み込むことにより、PCI 準拠が維持されます。このスクリプトをバンドルに含めたり、自分でホストしたりしないでください。 ### 支払いフォームを定義する マウントする Element ごとに空のプレースホルダー `div` を 1 つ、決済フォームに追加します。Stripe は、それぞれの `div` に iframe を挿入して、顧客のメールアドレスと支払い情報を安全に収集します。 ### Stripe.js を初期化する [公開可能 API キー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用して Stripe.js を初期化します。Stripe.js を使用して Payment Element を作成し、クライアントで決済を完了します。 ### PaymentIntent を取得する 決済ページが読み込まれたらすぐに、サーバーのエンドポイントにリクエストを行い、新しい PaymentIntent を作成します。支払いは、エンドポイントから返された `clientSecret` を使用して完了します。 ### Stripe Elements を初期化する `loadStripe` の結果として生成されたプロミスを Elements プロバイダーに渡します。これにより、子コンポーネントが、Elements コンシューマーを使用して Stripe サービスにアクセスできるようになります。さらに、オプションとして client secret を Elements プロバイダーに渡します。 ### Stripe Elements を初期化する `loadStripe` の結果として生成されたプロミスを Elements プロバイダーに渡します。これにより、子コンポーネントが、Elements コンシューマーを介して Stripe サービスにアクセスできるようになります。さらに、オプションとして client secret を Elements プロバイダーに渡します。 ### Stripe Elements を初期化する client secret を使用して [Stripe Elements UI ライブラリ](https://docs.stripe.com/js/elements_object/create)を初期化します。Elements はカード詳細の収集に必要な UI コンポーネントを管理します。 ### 状態を設定する 一部の状態を初期化すると、支払いの記録、エラーの表示、ユーザーインターフェイスの管理を行うことができます。 ### 状態を設定する 一部の状態を初期化すると、支払いの記録、エラーの表示、ユーザーインターフェイスの管理を行うことができます。 ### Stripe への参照を保存する `useStripe()` フックと `useElements()` フックを使用して、CheckoutForm コンポーネント内の Stripe ライブラリにアクセスします。クラスコンポーネントを介して Elements にアクセスする必要がある場合は、代わりに [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) を使用します。 ### Stripe への参照を保存する `useStripe()` フックと `useElements()` フックを使用して、CheckoutForm コンポーネント内の Stripe ライブラリにアクセスします。クラスコンポーネントを介して Elements にアクセスする必要がある場合は、代わりに [ElementsConsumer](https://docs.stripe.com/sdks/stripejs-react.md#elements-consumer) を使用します。 ### PaymentElement を追加する [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) を決済フォームに追加します。これにより、さまざまな支払い方法の支払いの詳細を収集する動的なフォームを備えた iframe が埋め込まれます。顧客は支払い方法のタイプを選択でき、フォームでは顧客の選択に応じて必要なすべての支払いの詳細が自動的に収集されます。 ### PaymentElement を追加する [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) を決済フォームに追加します。これにより、さまざまな支払い方法の支払いの詳細を収集する動的なフォームを備えた iframe が埋め込まれます。顧客は支払い方法のタイプを選択でき、フォームでは顧客の選択に応じて必要なすべての支払いの詳細が自動的に収集されます。 ### PaymentElement を作成する [PaymentElement](https://docs.stripe.com/js/elements_object/create_payment_element) を作成して、決済フォームのプレースホルダー `
` にマウントします。これにより、PaymentIntent から利用できる設定済みの支払い方法のタイプを表示する動的フォームを備えた iframe が埋め込まれ、顧客が支払い方法を選択できます。このフォームでは、選択された支払い方法のタイプに関連付けられた支払いの詳細が自動的に収集されます。 ### (オプション) Payment Element のスタイルを設定する [Appearanceオブジェクト](https://docs.stripe.com/elements/appearance-api.md)を作成し、それをElementsプロバイダーへのオプションとして渡すことで、Payment Element UIをカスタマイズします。会社のカラースキームとフォントを使用して、決済ページの残りの部分と一致させます。[フォントセット](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts)で Elements を初期化することで、カスタムフォント (例:Google Fonts) を使用します。 右のプレビューを開き、変更内容が有効であることを確認してください。 > プレビューデモの一部は、実際の決済ページと一致しない場合があります。上記の設定は、[Appearanceオブジェクト](https://docs.stripe.com/elements/appearance-api.md)の変数のサブセットのみを表しており、[Appearanceオブジェクト](https://docs.stripe.com/elements/appearance-api.md) はStripe Elementsの特定の属性のみを制御します。決済ページの残りの部分のスタイリングはお客様の責任です。 ### (オプション) Payment Element のスタイルを設定する [Appearanceオブジェクト](https://docs.stripe.com/elements/appearance-api.md)を作成し、それをElementsプロバイダーへのオプションとして渡すことで、Payment Element UIをカスタマイズします。会社のカラースキームとフォントを使用して、決済ページの残りの部分と一致させます。[フォントセット](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts)で Elements を初期化することで、カスタムフォント (例:Google Fonts) を使用します。 右のプレビューを開き、変更内容が有効であることを確認してください。 > このプレビューデモの一部は、実際の決済ページとは一致しない場合があります。上記の設定は、Appearance オブジェクトの変数のサブセットのみを表し、また Appearance オブジェクトは Stripe Elements の特定の属性のみを制御しています。決済ページの残りの部分のスタイル設定はお客様の責任で行ってください。 ### (オプション) Payment Element のスタイルを設定する [Appearanceオブジェクト](https://docs.stripe.com/elements/appearance-api.md) を作成し、それで Elements を初期化することで Payment Element UI をカスタマイズします。会社のカラースキームとフォントを使用して、決済ページの残りの部分と一致させます。[フォントセット](https://docs.stripe.com/js/elements_object/create#stripe_elements-options-fonts)で Elements を初期化することで、カスタムフォント (例:Google Fonts) を使用します。 右のプレビューを開き、変更内容が有効であることを確認してください。 > プレビューデモの一部は、実際の決済ページと一致しない場合があります。上記の設定は、[Appearanceオブジェクト](https://docs.stripe.com/elements/appearance-api.md)の変数のサブセットのみを表しており、[Appearanceオブジェクト](https://docs.stripe.com/elements/appearance-api.md) はStripe Elementsの特定の属性のみを制御します。決済ページの残りの部分のスタイリングはお客様の責任です。 ### 送信イベントを処理する フォームの送信イベントをリッスンし、Stripe API を通じて支払いを確定するタイミングを認識できるようにします。 ### 支払いを完了する 顧客が支払いボタンをクリックすると、PaymentElement で[confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を呼び出し、[return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を渡して、顧客が支払いの完了後にStripeがリダイレクトする場所を指定します。認証が必要な支払いの場合、Stripe は支払い方法に応じて、*3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments)のモーダルを表示するか、顧客を認証ページにリダイレクトします。顧客が認証プロセスを完了すると、`return_url` にリダイレクトされます。 ### 支払いを完了する 顧客が支払いボタンをクリックすると、PaymentElement で[confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を呼び出し、[return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) を渡して、顧客が支払いの完了後にStripeがリダイレクトする場所を指定します。認証が必要な支払いの場合、Stripe は支払い方法に応じて、*3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments)のモーダルを表示するか、顧客を認証ページにリダイレクトします。顧客が認証プロセスを完了すると、`return_url` にリダイレクトされます。 ### 支払いを完了する [confirmPayment](https://docs.stripe.com/js/payment_intents/confirm_payment) を Element インスタンスと[return_url](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-return_url) で呼び出し、Stripe が支払いの完了後に顧客をリダイレクトする場所を指定します。認証が必要な支払いの場合、Stripe は支払い方法に応じて、*3D Secure* (3D Secure (3DS) provides an additional layer of authentication for credit card transactions that protects businesses from liability for fraudulent card payments)のモーダルを表示するか、顧客を認証ページにリダイレクトします。顧客が認証プロセスを完了すると、`return_url` にリダイレクトされます。 ### エラーを処理する 即時[エラー](https://docs.stripe.com/error-codes.md)が発生した場合 (顧客のカードが拒否された場合など)、Stripe.js はエラーを返します。そのエラーメッセージを顧客に表示して、顧客が再試行できるようにします。 ### 支払いステータスメッセージを表示する Stripe が顧客を `return_url` にリダイレクトする際、Stripe.js によって `payment_intent_client_secret` クエリパラメーターが含められます。これを使用して [PaymentIntent ステータスコード](https://docs.stripe.com/payments/payment-intents/verifying-status.md) を取得し、顧客に表示する内容を決定します。 ### 支払いステータスメッセージを表示する Stripe が顧客を `return_url` にリダイレクトする際、Stripe.js によって `payment_intent` クエリパラメーターが追加されます。これを使用して [PaymentIntent のステータス更新](https://docs.stripe.com/payments/payment-intents/verifying-status.md)を取得し、顧客に表示する内容を決定します。 ### Webhook を使用する Stripe は、支払いの処理中および完了後に複数のイベントを送信します。[Webhook エンドポイント](https://docs.stripe.com/webhooks/quickstart.md)の[イベントの送信先](https://docs.stripe.com/event-destinations.md)を作成して、これらのイベントを受信し、顧客への注文確認メールの送信、データベースへの売上の記録、配送ワークフローの開始などのアクションを実行します。[payment_intent.succeeded](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.succeeded)、[payment_intent.processing](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.processing)、[payment_intent.payment_failed](https://docs.stripe.com/api/events/types.md?lang=php#event_types-payment_intent.payment_failed) イベントを処理することをお勧めします。 クライアントからのコールバックを待つのではなく、これらのイベントをリッスンします。クライアントでは、コールバックが実行される前に顧客がブラウザーのウィンドウを閉じたり、アプリを終了する場合があります。悪意を持つクライアントがレスポンスを不正操作する場合もあります。非同期型のイベントをリッスンするよう実装を設定すると、一度の導入で[複数の異なるタイプの支払い方法](https://stripe.com/payments/payment-methods-guide)を受け付けることができます。 ### アプリケーションを実行する React アプリとサーバーを実行します。[localhost:3000/checkout](http://localhost:3000/checkout) に移動し、決済ページを確認します。 ```bash npm start ``` ### アプリケーションを実行する Next.js アプリを実行します。[localhost:3000](http://localhost:3000) に移動し、決済ページを確認します。 ```bash npm run dev ``` ### アプリケーションを実行する Node サーバーを実行し、[localhost:4242/checkout.html](http://localhost:4242/checkout.html) に移動します。 ```bash npm start ``` ### サーバーアプリケーションを実行する React アプリとサーバーを実行します。[localhost:3000/checkout](http://localhost:3000/checkout) に移動し、決済ページを確認します。 ```bash ruby server.rb ``` ### アプリケーションを実行する Ruby サーバーを実行し、[localhost:4242/checkout.html](http://localhost:4242/checkout.html) に移動します。 ```bash ruby server.rb ``` ### サーバーアプリケーションを実行する React アプリとサーバーを実行します。[localhost:3000/checkout](http://localhost:3000/checkout) に移動し、決済ページを確認します。 ```bash python3 -m flask run --port=4242 ``` ### アプリケーションを実行する Python サーバーを実行し、[localhost:4242/checkout.html](http://localhost:4242/checkout.html) に移動します。 ```bash python3 -m flask run --port=4242 ``` ### サーバーアプリケーションを実行する React アプリとサーバーを実行します。[localhost:3000/checkout](http://localhost:3000/checkout) に移動し、決済ページを確認します。 ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### アプリケーションを実行する サーバーを実行し、[localhost:4242/checkout.html](http://localhost:4242/checkout.html) に移動します。 ```bash php -S 127.0.0.1:4242 --docroot=public ``` ### サーバーアプリケーションを実行する React アプリとサーバーを実行します。[localhost:3000/checkout](http://localhost:3000/checkout) に移動し、決済ページを確認します。 ```bash go run server.go ``` ### アプリケーションを実行する Go サーバーを実行し、[localhost:4242/checkout.html](http://localhost:4242/checkout.html) に移動します。 ```bash go run server.go ``` ### サーバーアプリケーションを実行する React アプリとサーバーを実行します。[localhost:3000/checkout](http://localhost:3000/checkout) に移動し、決済ページを確認します。 ```bash dotnet run ``` ### アプリケーションを実行する ASP.NET MVC サーバーを実行し、[localhost:4242/checkout.html](http://localhost:4242/checkout.html) に移動します。 ```bash dotnet run ``` ### アプリケーションを実行する サーバーを実行し、[localhost:4242/checkout.html](http://localhost:4242/checkout.html) に移動します。 ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### サーバーアプリケーションを実行する React アプリとサーバーを実行します。[localhost:3000/checkout](http://localhost:3000/checkout) に移動し、決済ページを確認します。 ```bash java -cp target/sample-jar-with-dependencies.jar com.stripe.sample.Server ``` ### アプリケーションを実行する React アプリを実行し、[localhost:3000/checkout](http://localhost:3000/checkout) に移動します。 ```bash npm start ``` ### テスト支払いを行う 連携機能が作動することを確認するには、[テスト決済の詳細](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=elements&api-integration=paymentintents#web-test-the-integration)を使用してテスト支払いを行います。 ### ダッシュボードで決済を確認する テスト支払いを確認するには、[Stripe ダッシュボード](https://dashboard.stripe.com/test/payments)にアクセスします。 ## 決済機能を導入して構築済みのシステムを強化する Stripe で支払いを受け付ける準備が整いました。以下のステップに進み、さらに機能を追加します。 ### 税金の徴収を自動化する Stripe 取引の適切な税額を計算して徴収します。Stripe Tax を使用するには、事前に[ダッシュボード](https://dashboard.stripe.com/tax)で有効にする必要があります。[Stripe Tax](https://docs.stripe.com/tax.md) と、[決済機能への追加方法](https://docs.stripe.com/tax/custom.md)の詳細をご確認ください。 ### Stripe Tax API を使用して税金を計算する [Stripe Tax API](https://docs.stripe.com/api/tax/calculations/create.md) を使用して取引の税金を計算します。リクエスト本文で注文の `currency`、`customer_details`、`line_items` を指定します。 結果として生成される Tax Calculation の `tax_amount_exclusive` 属性を使用して、注文の合計額に外税を追加します。 ### 支払いの成功時に税取引を記録する `hook s[inputs][tax][calculation]` を使い、 PaymentIntent にリンクします。 これにより徴収済みの税金が Stripe アカウントに記録され、後で会計処理用にエクスポートでき、他の [Stripe アクション](https://docs.stripe.com/tax/payment-intent.md#automatic-actions)がトリガーされます。 ### メールの領収書を送信する お客様のブランドロゴとカラーテーマを使用してメールの領収書を顧客に送信できます。これは、[ダッシュボード](https://dashboard.stripe.com/settings/branding)で設定できます。 ### 顧客のメールアドレスを収集する 支払いフォームに入力フィールドを追加してメールアドレスを収集します。 ### 状態にメールを追加する 顧客が入力するメールアドレスを記録する変数を追加します。 ### 状態にメールを追加する 顧客が入力するメールアドレスを記録する変数を追加します。 ### Stripe にメールアドレスを提供する 提供されたメールアドレスを `receipt_email` 値として渡します。本番環境で支払いが成功すると、Stripe はメール領収書を送信します (*サンドボックス* (A sandbox is an isolated test environment that allows you to test Stripe functionality in your account without affecting your live integration. Use sandboxes to safely experiment with new features and changes)では送信しません)。 ### 支払い後に支払い情報を保存する リピーター顧客に利用される SaaS や E-コマースのビジネスでよく使用されています。 ### その他の Stripe リソースをインポートする Stripe の `customer` パッケージと `paymentmethod` パッケージをインポートします。これらのパッケージを使用して、顧客に関する情報を格納します。 ### その他の Stripe リソースをインポートする Stripe PaymentMethod モデルと Customer モデルをインポートします。これらのモデルを使用して、顧客に関する情報を格納します。 ### 顧客を作成する カード情報は *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) オブジェクトに保存されます。PaymentIntent を作成する前に、新しい Customer を作成してください。Customer には、名前、メールアドレス、配送先住所などの詳細も保存できます。 ### 顧客を作成する Stripe はクレジットカードを[顧客](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer)を表す [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) オブジェクトに保存します。PaymentIntent を作成する前に、新しい Account を作成してください。Account には、名前、メールアドレス、配送先住所などの詳細も保存できます。 ### PaymentIntent に顧客を追加する Customer ID を PaymentIntent に渡し、`setup_future_usage` を `off_session` に設定します。`setup_future_usage` は、Stripe にどの決済手段を使用する予定であるかを伝えるためのパラメーターです。ヨーロッパやインドなどの一部の地域では、支払い情報の再利用に関する要件が設けられています。`setup_future_usage` の効果的な適用方法については、[こちらの記事](https://docs.stripe.com/payments/payment-intents.md#future-usage)を参照してください。[サポートされている決済手段のリスト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability)も合わせてご確認ください。PaymentIntent が成功すると、Stripe は自動的に (*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) オブジェクトの) 支払い情報を Customer に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。 ### PaymentIntent に顧客を追加する PaymentIntent にアカウント ID を渡し、`setup_future_usage` を `off_session` に設定します。`setup_future_usage` は、決済手段の使用方法を Stripe に伝えます。ヨーロッパやインドなど、特定の地域では、決済の詳細の再利用に関する要件があります。`setup_future_usage` を適用する最も効果的な方法について[詳細をご覧ください](https://docs.stripe.com/payments/payment-intents.md#future-usage)。[サポートされている決済手段のリスト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability)を確認することもできます。PaymentIntent が成功すると、Stripe は決済の詳細 (*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) オブジェクト) を、顧客設定の Account に自動的に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。 ### 保存された PaymentMethod に請求する PaymentMethod に再度請求する準備ができたら、Customer ID と請求先のカードの PaymentMethod ID を使用して新しい PaymentIntent を作成し、`off_session` および `confirm` のフラグを true に設定します。 ### Stripe Node ライブラリーをインストールする パッケージをインストールし、それをコードにインポートします。また、まったくゼロから開始していて package.json ファイルが必要な場合には、コードエディターのダウンロードリンクを使用してプロジェクトファイルをダウンロードします。 #### npm ライブラリーをインストールします。 ```bash npm install --save stripe ``` #### GitHub または、stripe-node ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-node)ダウンロードします。 ### Stripe Ruby ライブラリーをインストールする Stripe ruby gem をインストールし、require を指定してコードに読み込みます。または、まったくゼロから開始していて Gemfile が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Terminal gem をインストールします。 ```bash gem install stripe ``` #### Bundler この行を Gemfile に追加します。 ```bash gem 'stripe' ``` #### GitHub または、stripe-ruby gem のソースコードを直接 [GitHub から](https://github.com/stripe/stripe-ruby)ダウンロードします。 ### Stripe Java ライブラリーをインストールする ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していてサンプルの pom.xml ファイル (Maven 用) が必要な場合は、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Maven POM に以下の依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle build.gradle ファイルに依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub JAR を直接 [GitHub から](https://github.com/stripe/stripe-java/releases/latest)ダウンロードします。 ### Stripe Python パッケージをインストールする Stripe パッケージをインストールし、コードにインポートします。まったくゼロから開始していて requirements.txt が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### pip pip を使用してパッケージをインストールします。 ```bash pip3 install stripe ``` #### GitHub stripe-python ライブラリのソースコードを [GitHub から](https://github.com/stripe/stripe-python)直接ダウンロードします。 ### Stripe PHP ライブラリーをインストールする Composer を使用してライブラリーをインストールし、シークレット API キーで初期化します。まったくゼロから開始していて composer.json ファイルが必要な場合には、コードエディターのリンクを使用してファイルをダウンロードします。 #### Composer ライブラリーをインストールします。 ```bash composer require stripe/stripe-php ``` #### GitHub または、stripe-php ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-php)ダウンロードします。 ### サーバーを設定する ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していて go.mod ファイルが必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Go 必ず Go モジュールを使用してを初期化してください。 ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub または、stripe-go モジュールのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-go)ダウンロードします。 ### Stripe.net ライブラリーをインストールする .NET または NuGet でパッケージをインストールします。まったくゼロから開始する場合には、設定済みの .csproj ファイルが含まれるファイルをダウンロードします。 #### dotnet ライブラリーをインストールします。 ```bash dotnet add package Stripe.net ``` #### NuGet ライブラリーをインストールします。 ```bash Install-Package Stripe.net ``` #### GitHub または、Stripe.net ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-dotnet)ダウンロードします。 ### Stripe ライブラリーをインストールする パッケージをインストールし、コードにインポートします。まったくゼロから開始していて `package.json` が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 ライブラリーをインストールします。 ```bash npm install --save stripe @stripe/stripe-js next ``` ### PaymentIntent を作成する [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md) を作成するエンドポイントをサーバーに追加します。PaymentIntent は、顧客の支払いライフサイクルを追跡し、支払いの試行失敗があった場合にはその記録を残して顧客への請求に重複が発生しないようにします。レスポンスで PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) を返して、クライアントで支払いを完了します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### SDK をインストールする Stripe iOS SDK は[オープンソース](https://github.com/stripe/stripe-ios)であり、[詳細なドキュメントが提供されています](https://stripe.dev/stripe-ios/)。また、iOS 13 以降をサポートするアプリと互換性があります。Stripe SDK を決済画面のビューコントローラーにインポートしてください。 #### Swift Package Manager Xcode で、**File (ファイル)** > **Add Package Dependencies (パッケージ依存関係を追加)…** を選択し、リポジトリー URL として `https://github.com/stripe/stripe-ios-spm` を入力します。[リリースページ](https://github.com/stripe/stripe-ios/releases)から最新のバージョン番号を選択し、`StripePaymentSheet` モジュールをアプリのターゲットに追加します。 #### CocoaPods この行を Podfile に追加します。これ以降は、Xcode でプロジェクトを開く際に、.xcodeproj ファイルではなく、.xcworkspace ファイルを使用してください。 ```bash pod 'StripePaymentSheet' ``` #### Carthage この行を Cartfile に追加します。 ```bash github "stripe/stripe-ios" ``` #### 手動のフレームワーク プロジェクトに Stripe を追加するには、[GitHub のリリース](https://github.com/stripe/stripe-ios/releases)から Stripe.xcframework.zip をダウンロードして解凍します。必要な xcframework ファイルを Xcode プロジェクトの「Embedded Binaries (埋め込みバイナリ)」設定にドラッグします。「Copy items if needed (必要に応じてアイテムをコピーする)」を必ず選択してください。 ### SDK を設定する Stripeの[公開可能 API キー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用して Stripe SDK を設定します。デモンストレーションの目的で、SDK で公開可能 API キーをハードコード化します。本番環境のアプリでは、サーバーから API キーを取得する必要があります。 ### PaymentIntent を取得する ビューが読み込まれたらすぐに、サーバーに対して PaymentIntent をリクエストします。サーバーによって返される PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) への参照を保存します。Payment Sheet では、後で支払いを完了するときにこの secret を使用します。 ### 支払い画面を設定して表示する 以前に取得した client secret を使用して `PaymentSheet` インスタンスを作成し、ビューコントローラから提示します。 決済画面を[カスタマイズ](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html)するために、`PaymentSheet.Configuration` 構造を使用します。 ### 支払い結果を処理する 支払い結果を処理するために完了ブロックを使用します。 支払いが[エラー](https://docs.stripe.com/error-codes.md)で失敗する場合は、顧客が対処して再試行できるように適切なメッセージを提示します。エラーが発生しなかった場合は、支払いが成功したことを顧客に通知します。 ### テスト支払いを行う #### iOS 連携機能が作動することを確認するには、[テスト決済の詳細](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration)を使用してテスト支払いを行います。 #### Android 連携機能が作動することを確認するには、[テスト決済の詳細](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration)を使用してテスト支払いを行います。 ### ダッシュボードで決済を確認する [Stripe ダッシュボード](https://dashboard.stripe.com/test/payments)に移動して、テスト支払いを確認します。 ## 決済機能を導入して構築済みのシステムを強化する Stripe で支払いを受け付ける準備が整いました。以下のステップに進み、さらに機能を追加します。 ### 税金の徴収を自動化する Stripe 取引の適切な税額を計算して徴収します。Stripe Tax を使用するには、事前に[ダッシュボード](https://dashboard.stripe.com/tax)で有効にする必要があります。[Stripe Tax](https://docs.stripe.com/tax.md) と、[決済機能への追加方法](https://docs.stripe.com/tax/custom.md)の詳細をご確認ください。 ### Stripe Tax API を使用して税金を計算する [Stripe Tax API](https://docs.stripe.com/api/tax/calculations/create.md) を使用して取引の税金を計算します。リクエスト本文で注文の `currency`、`customer_details`、`line_items` を指定します。 結果として生成される Tax Calculation の `tax_amount_exclusive` 属性を使用して、注文の合計額に外税を追加します。 ### 支払いの成功時に税取引を記録する `hook s[inputs][tax][calculation]` を使い、 PaymentIntent にリンクします。 これにより徴収済みの税金が Stripe アカウントに記録され、後で会計処理用にエクスポートでき、他の [Stripe アクション](https://docs.stripe.com/tax/payment-intent.md#automatic-actions)がトリガーされます。 ### 遅延型の支払い方法を許可する 一部の支払い方法では、決済フローの終了時に顧客から売上を受け取ることが保証されません。その理由として、決済に時間がかかる (SEPA や ACH のような大半の銀行口座引き落としなど)、完了するために顧客の対応が必要になる (OXXO、コンビニ決済、Boleto など) などが挙げられます。遅延型の支払い方法を有効にするには、このフラグを使用してください。 この機能を有効にする場合、支払いが成功したかどうかの通知を受け取るためにサーバー実装が [Webhook](https://docs.stripe.com/payments/payment-methods.md#payment-notification) をリッスンしていることを確認してください。 ### Apple Pay サポートを追加する Apple Pay を有効にするには、[Apple Pay 加盟店 ID](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) と Stripe アカウントの[国コード](https://dashboard.stripe.com/settings/account)を指定します。 ### Google Pay サポートを追加する Google Pay を使用するには、まず、AndroidManifest.xml で Google Pay API を有効化します。 Google Pay を有効にするには、[PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html) を初期化する際に、Google Pay 環境 (本番またはテスト) と[ビジネスの国コード](https://dashboard.stripe.com/settings/account)を指定して [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) オブジェクトを渡します。 ### ボタンの主な色をカスタマイズする ブランドやアプリケーションの外観に合わせて、主なボタンにカスタムの色を使用することをお勧めします。 ### カードのスキャンを有効化する カードスキャンを使用すると、手動でカードを入力する手間が省け、コンバージョン率の上昇につながります。カードスキャンを有効にするには、アプリケーションの `Info.plist` で `NSCameraUsageDescription` を設定し、カメラにアクセスする理由を入力します (「カードのスキャンのため」など)。 > カードスキャンは、iOS 13 以上を実行しているデバイスでのみ使用できます。 ### カードのスキャンを有効化する カードスキャンを使用すると、手動でカードを入力する手間が省け、購入完了率を高められます。カードスキャンを有効にするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの `dependencies` ブロックに `stripecardscan` を追加します。 #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### 支払い後に支払い情報を保存する リピーター顧客に利用される SaaS や E-コマースのビジネスでよく使用されています。 ### その他の Stripe リソースをインポートする Stripe の `customer` パッケージと `paymentmethod` パッケージをインポートします。これらのパッケージを使用して、顧客に関する情報を格納します。 ### その他の Stripe リソースをインポートする Stripe PaymentMethod モデルと Customer モデルをインポートします。これらのモデルを使用して、顧客に関する情報を格納します。 ### 顧客を作成する カード情報は *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) オブジェクトに保存されます。PaymentIntent を作成する前に、新しい Customer を作成してください。Customer には、名前、メールアドレス、配送先住所などの詳細も保存できます。 ### 顧客を作成する Stripe はクレジットカードを[顧客](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer)を表す [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) オブジェクトに保存します。PaymentIntent を作成する前に、新しい Account を作成してください。Account には、名前、メールアドレス、配送先住所などの詳細も保存できます。 ### PaymentIntent に顧客を追加する Customer ID を PaymentIntent に渡し、`setup_future_usage` を `off_session` に設定します。`setup_future_usage` は、Stripe にどの決済手段を使用する予定であるかを伝えるためのパラメーターです。ヨーロッパやインドなどの一部の地域では、支払い情報の再利用に関する要件が設けられています。`setup_future_usage` の効果的な適用方法については、[こちらの記事](https://docs.stripe.com/payments/payment-intents.md#future-usage)を参照してください。[サポートされている決済手段のリスト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability)も合わせてご確認ください。PaymentIntent が成功すると、Stripe は自動的に (*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) オブジェクトの) 支払い情報を Customer に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。 ### PaymentIntent に顧客を追加する PaymentIntent にアカウント ID を渡し、`setup_future_usage` を `off_session` に設定します。`setup_future_usage` は、決済手段の使用方法を Stripe に伝えます。ヨーロッパやインドなど、特定の地域では、決済の詳細の再利用に関する要件があります。`setup_future_usage` を適用する最も効果的な方法について[詳細をご覧ください](https://docs.stripe.com/payments/payment-intents.md#future-usage)。[サポートされている決済手段のリスト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability)を確認することもできます。PaymentIntent が成功すると、Stripe は決済の詳細 (*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) オブジェクト) を、顧客設定の Account に自動的に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。 ### 保存された PaymentMethod に請求する PaymentMethod に再度請求する準備ができたら、Customer ID と請求先のカードの PaymentMethod ID を使用して新しい PaymentIntent を作成し、`off_session` および `confirm` のフラグを true に設定します。 ### Address Element を使用して住所を収集する 国内と国外の配送先住所または請求先住所を顧客から収集します。 ### Address Element を使用して住所を収集する 国内と国外の配送先住所または請求先住所を顧客から収集します。 Address Element を使用している場合は、必要に応じて [Google Places SDK](https://developers.google.com/maps/documentation/places/android-sdk/overview) を使用して、住所のオートコンプリートの入力候補を取得できます。オートコンプリートの入力候補を有効にするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの dependency ブロックに `places` を追加します。 #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ### Stripe Node ライブラリーをインストールする パッケージをインストールし、それをコードにインポートします。また、まったくゼロから開始していて package.json ファイルが必要な場合には、コードエディターのダウンロードリンクを使用してプロジェクトファイルをダウンロードします。 #### npm ライブラリーをインストールします。 ```bash npm install --save stripe ``` #### GitHub または、stripe-node ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-node)ダウンロードします。 ### Stripe Ruby ライブラリーをインストールする Stripe ruby gem をインストールし、require を指定してコードに読み込みます。または、まったくゼロから開始していて Gemfile が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Terminal gem をインストールします。 ```bash gem install stripe ``` #### Bundler この行を Gemfile に追加します。 ```bash gem 'stripe' ``` #### GitHub または、stripe-ruby gem のソースコードを直接 [GitHub から](https://github.com/stripe/stripe-ruby)ダウンロードします。 ### Stripe Java ライブラリーをインストールする ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していてサンプルの pom.xml ファイル (Maven 用) が必要な場合は、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Maven POM に以下の依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash \ncom.stripe\nstripe-java\n{VERSION}\n ``` #### Gradle build.gradle ファイルに依存関係を追加し、{VERSION} を使用するバージョン番号に置き換えます。 ```bash implementation "com.stripe:stripe-java:{VERSION}" ``` #### GitHub JAR を直接 [GitHub から](https://github.com/stripe/stripe-java/releases/latest)ダウンロードします。 ### Stripe Python パッケージをインストールする Stripe パッケージをインストールし、コードにインポートします。まったくゼロから開始していて requirements.txt が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### pip pip を使用してパッケージをインストールします。 ```bash pip3 install stripe ``` #### GitHub stripe-python ライブラリのソースコードを [GitHub から](https://github.com/stripe/stripe-python)直接ダウンロードします。 ### Stripe PHP ライブラリーをインストールする Composer を使用してライブラリーをインストールし、シークレット API キーで初期化します。まったくゼロから開始していて composer.json ファイルが必要な場合には、コードエディターのリンクを使用してファイルをダウンロードします。 #### Composer ライブラリーをインストールします。 ```bash composer require stripe/stripe-php ``` #### GitHub または、stripe-php ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-php)ダウンロードします。 ### サーバーを設定する ビルドに依存関係を追加し、ライブラリーをインポートします。まったくゼロから開始していて go.mod ファイルが必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 #### Go 必ず Go モジュールを使用してを初期化してください。 ```bash go get -u github.com/stripe/stripe-go/v85 ``` #### GitHub または、stripe-go モジュールのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-go)ダウンロードします。 ### Stripe.net ライブラリーをインストールする .NET または NuGet でパッケージをインストールします。まったくゼロから開始する場合には、設定済みの .csproj ファイルが含まれるファイルをダウンロードします。 #### dotnet ライブラリーをインストールします。 ```bash dotnet add package Stripe.net ``` #### NuGet ライブラリーをインストールします。 ```bash Install-Package Stripe.net ``` #### GitHub または、Stripe.net ライブラリーのソースコードを直接 [GitHub から](https://github.com/stripe/stripe-dotnet)ダウンロードします。 ### Stripe ライブラリーをインストールする パッケージをインストールし、コードにインポートします。まったくゼロから開始していて `package.json` が必要な場合には、コードエディターのリンクを使用してプロジェクトファイルをダウンロードします。 ライブラリーをインストールします。 ```bash npm install --save stripe @stripe/stripe-js next ``` ### PaymentIntent を作成する [PaymentIntent (支払いインテント)](https://docs.stripe.com/api/payment_intents.md) を作成するエンドポイントをサーバーに追加します。PaymentIntent は、顧客の支払いライフサイクルを追跡し、支払いの試行失敗があった場合にはその記録を残して顧客への請求に重複が発生しないようにします。レスポンスで PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) を返して、クライアントで支払いを完了します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### 支払い方法を設定する [動的な決済手段](https://docs.stripe.com/payments/payment-methods/dynamic-payment-methods.md)を使用すると、Stripe ではデフォルトで、カードとその他の一般的な決済手段が有効になります。[ダッシュボード](https://dashboard.stripe.com/settings/payment_methods)から、ノーコードで決済手段の更新や設定を行うことができます。Stripe は、利用資格と決済手段の設定に基づいて決済手段をフィルタリングし、金額、通貨、買い手の所在地などの要素から確立の高い決済手段の順に並べて表示します。 ### SDK をインストールする Stripe Android SDK は[オープンソース](https://github.com/stripe/stripe-android)であり、[詳細なドキュメントが提供されています](https://stripe.dev/stripe-android/)。Android 5.0 (API レベル 21) 以降を実行するデバイスと互換性があります。 SDK をインストールするには、`build.gradle` ファイルの dependencies ブロックに `stripe-android` を追加します。 #### Groovy ```groovy implementation 'com.stripe:stripe-android:23.3.0' ``` > 最新の SDK リリースと過去のバージョンの詳細については、GitHub の[リリースページ](https://github.com/stripe/stripe-android/releases)をご覧ください。 ### SDK を設定する Stripeの[公開可能 API キー](https://docs.stripe.com/keys.md#obtain-api-keys)を使用して Stripe SDK を設定します。デモンストレーションの目的で、SDK で公開可能 API キーをハードコード化します。本番環境のアプリでは、サーバーから API キーを取得する必要があります。 ### PaymentIntent を取得する ビューが読み込まれたらすぐに、サーバーに対して PaymentIntent をリクエストします。サーバーによって返される PaymentIntent の *client secret* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer)) への参照を保存します。Payment Sheet では、後で支払いを完了するときにこの secret を使用します。 ### 支払い画面を設定して表示する 以前に取得した client secret を使用して `PaymentSheet` インスタンスを作成し、ビューコントローラから提示します。 決済画面を[カスタマイズ](https://stripe.dev/stripe-ios/stripe-paymentsheet/Classes/PaymentSheet/Configuration.html)するために、`PaymentSheet.Configuration` 構造を使用します。 ### 支払い結果を処理する 支払い結果を処理するために完了ブロックを使用します。 支払いが[エラー](https://docs.stripe.com/error-codes.md)で失敗する場合は、顧客が対処して再試行できるように適切なメッセージを提示します。エラーが発生しなかった場合は、支払いが成功したことを顧客に通知します。 ### テスト支払いを行う #### iOS 連携機能が作動することを確認するには、[テスト決済の詳細](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=ios#ios-test-the-integration)を使用してテスト支払いを行います。 #### Android 連携機能が作動することを確認するには、[テスト決済の詳細](https://docs.stripe.com/payments/accept-a-payment.md?payment-ui=mobile&platform=android#android-test-the-integration)を使用してテスト支払いを行います。 ### ダッシュボードで決済を確認する [Stripe ダッシュボード](https://dashboard.stripe.com/test/payments)に移動して、テスト支払いを確認します。 ## 決済機能を導入して構築済みのシステムを強化する Stripe で支払いを受け付ける準備が整いました。以下のステップに進み、さらに機能を追加します。 ### 税金の徴収を自動化する Stripe 取引の適切な税額を計算して徴収します。Stripe Tax を使用するには、事前に[ダッシュボード](https://dashboard.stripe.com/tax)で有効にする必要があります。[Stripe Tax](https://docs.stripe.com/tax.md) と、[決済機能への追加方法](https://docs.stripe.com/tax/custom.md)の詳細をご確認ください。 ### Stripe Tax API を使用して税金を計算する [Stripe Tax API](https://docs.stripe.com/api/tax/calculations/create.md) を使用して取引の税金を計算します。リクエスト本文で注文の `currency`、`customer_details`、`line_items` を指定します。 結果として生成される Tax Calculation の `tax_amount_exclusive` 属性を使用して、注文の合計額に外税を追加します。 ### 支払いの成功時に税取引を記録する `hook s[inputs][tax][calculation]` を使い、 PaymentIntent にリンクします。 これにより徴収済みの税金が Stripe アカウントに記録され、後で会計処理用にエクスポートでき、他の [Stripe アクション](https://docs.stripe.com/tax/payment-intent.md#automatic-actions)がトリガーされます。 ### 遅延型の支払い方法を許可する 一部の支払い方法では、決済フローの終了時に顧客から売上を受け取ることが保証されません。その理由として、決済に時間がかかる (SEPA や ACH のような大半の銀行口座引き落としなど)、完了するために顧客の対応が必要になる (OXXO、コンビニ決済、Boleto など) などが挙げられます。遅延型の支払い方法を有効にするには、このフラグを使用してください。 この機能を有効にする場合、支払いが成功したかどうかの通知を受け取るためにサーバー実装が [Webhook](https://docs.stripe.com/payments/payment-methods.md#payment-notification) をリッスンしていることを確認してください。 ### Apple Pay サポートを追加する Apple Pay を有効にするには、[Apple Pay 加盟店 ID](https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account) と Stripe アカウントの[国コード](https://dashboard.stripe.com/settings/account)を指定します。 ### Google Pay サポートを追加する Google Pay を使用するには、まず、AndroidManifest.xml で Google Pay API を有効化します。 Google Pay を有効にするには、[PaymentSheet.Configuration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html) を初期化する際に、Google Pay 環境 (本番またはテスト) と[ビジネスの国コード](https://dashboard.stripe.com/settings/account)を指定して [PaymentSheet.GooglePayConfiguration](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-google-pay-configuration/index.html) オブジェクトを渡します。 ### ボタンの主な色をカスタマイズする ブランドやアプリケーションの外観に合わせて、主なボタンにカスタムの色を使用することをお勧めします。 ### カードのスキャンを有効化する カードスキャンを使用すると、手動でカードを入力する手間が省け、コンバージョン率の上昇につながります。カードスキャンを有効にするには、アプリケーションの `Info.plist` で `NSCameraUsageDescription` を設定し、カメラにアクセスする理由を入力します (「カードのスキャンのため」など)。 > カードスキャンは、iOS 13 以上を実行しているデバイスでのみ使用できます。 ### カードのスキャンを有効化する カードスキャンを使用すると、手動でカードを入力する手間が省け、購入完了率を高められます。カードスキャンを有効にするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの `dependencies` ブロックに `stripecardscan` を追加します。 #### Groovy ```groovy implementation 'com.stripe:stripecardscan:23.3.0' ``` ### 支払い後に支払い情報を保存する リピーター顧客に利用される SaaS や E-コマースのビジネスでよく使用されています。 ### その他の Stripe リソースをインポートする Stripe の `customer` パッケージと `paymentmethod` パッケージをインポートします。これらのパッケージを使用して、顧客に関する情報を格納します。 ### その他の Stripe リソースをインポートする Stripe PaymentMethod モデルと Customer モデルをインポートします。これらのモデルを使用して、顧客に関する情報を格納します。 ### 顧客を作成する カード情報は *Customer* (Customer objects represent customers of your business. They let you reuse payment methods and give you the ability to track multiple payments) オブジェクトに保存されます。PaymentIntent を作成する前に、新しい Customer を作成してください。Customer には、名前、メールアドレス、配送先住所などの詳細も保存できます。 ### 顧客を作成する Stripe はクレジットカードを[顧客](https://docs.stripe.com/connect/account-capabilities.md?accounts-namespace=v2#customer)を表す [Account](https://docs.stripe.com/api/v2/core/accounts/object.md) オブジェクトに保存します。PaymentIntent を作成する前に、新しい Account を作成してください。Account には、名前、メールアドレス、配送先住所などの詳細も保存できます。 ### PaymentIntent に顧客を追加する Customer ID を PaymentIntent に渡し、`setup_future_usage` を `off_session` に設定します。`setup_future_usage` は、Stripe にどの決済手段を使用する予定であるかを伝えるためのパラメーターです。ヨーロッパやインドなどの一部の地域では、支払い情報の再利用に関する要件が設けられています。`setup_future_usage` の効果的な適用方法については、[こちらの記事](https://docs.stripe.com/payments/payment-intents.md#future-usage)を参照してください。[サポートされている決済手段のリスト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability)も合わせてご確認ください。PaymentIntent が成功すると、Stripe は自動的に (*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) オブジェクトの) 支払い情報を Customer に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。 ### PaymentIntent に顧客を追加する PaymentIntent にアカウント ID を渡し、`setup_future_usage` を `off_session` に設定します。`setup_future_usage` は、決済手段の使用方法を Stripe に伝えます。ヨーロッパやインドなど、特定の地域では、決済の詳細の再利用に関する要件があります。`setup_future_usage` を適用する最も効果的な方法について[詳細をご覧ください](https://docs.stripe.com/payments/payment-intents.md#future-usage)。[サポートされている決済手段のリスト](https://docs.stripe.com/payments/payment-methods/payment-method-support.md#additional-api-supportability)を確認することもできます。PaymentIntent が成功すると、Stripe は決済の詳細 (*PaymentMethod* (PaymentMethods represent your customer's payment instruments, used with the Payment Intents or Setup Intents APIs) オブジェクト) を、顧客設定の Account に自動的に[関連付けます](https://docs.stripe.com/api/payment_methods/attach.md)。 ### 保存された PaymentMethod に請求する PaymentMethod に再度請求する準備ができたら、Customer ID と請求先のカードの PaymentMethod ID を使用して新しい PaymentIntent を作成し、`off_session` および `confirm` のフラグを true に設定します。 ### Address Element を使用して住所を収集する 国内と国外の配送先住所または請求先住所を顧客から収集します。 ### Address Element を使用して住所を収集する 国内と国外の配送先住所または請求先住所を顧客から収集します。 Address Element を使用している場合は、必要に応じて [Google Places SDK](https://developers.google.com/maps/documentation/places/android-sdk/overview) を使用して、住所のオートコンプリートの入力候補を取得できます。オートコンプリートの入力候補を有効にするには、[app/build.gradle](https://developer.android.com/studio/build/dependencies) ファイルの dependency ブロックに `places` を追加します。 #### Groovy ```groovy implementation 'com.google.android.libraries.places:places:2.6.0' ``` ## 次のステップ #### ウェブ #### [請求先住所の詳細を収集する](https://docs.stripe.com/elements/address-element.md) デフォルトでは、Payment Element は必要な請求先住所情報のみを収集します。(デジタルの商品やサービスの税金の計算に使用するなどの目的で) 顧客の詳細な請求先住所または配送先住所を収集するには、Address Element を使用します。 #### iOS #### Android #### [入金](https://docs.stripe.com/payouts.md) Stripe アカウントから銀行口座に売上を移動する方法をご紹介します。 #### [返金](https://docs.stripe.com/refunds.md) Stripe API またはダッシュボードを使用し、返金のリクエストを処理します。 #### [フルフィルメント](https://docs.stripe.com/webhooks/quickstart.md) 支払いの成功後に注文のフルフィルメントを実行して、その他のの重要なイベントを処理するために、Webhook エンドポイントにイベントを送信するイベントの送信先を作成します。