また、SDK が Stripe への API コールを実行できるように、公開可能キーを設定する必要もあります。開始するには、導入中にクライアント側で公開可能キーをハードコード化できますが、本番環境ではサーバーから公開可能キーを取得します。
// Set your publishable key: remember to change this to your live publishable key in production// See your keys here: https://dashboard.stripe.com/apikeysSTPAPIClient.shared.publishableKey =
// This method handles opening custom URL schemes (for example, "your-app://stripe-redirect")funcscene(_ scene:UIScene, openURLContexts URLContexts:Set<UIOpenURLContext>){guardlet url =URLContexts.first?.url else{return}let stripeHandled =StripeAPI.handleURLCallback(with: url)if(!stripeHandled){// This was not a Stripe url – handle the URL normally as you would}}
classMyCheckoutVC:UIViewController{funcdidTapCheckoutButton(){// ...
paymentSheet.present(from:self){ result inswitch result {case.completed:// Payment completed - show a confirmation screen.case.failed(let error):print(error)// PaymentSheet encountered an unrecoverable error. You can display the error to the user, log it, etc.case.canceled:// Customer canceled - you should probably do nothing.}}}}
classMyCheckoutVC:UIViewController{// ...funchandleConfirm(_ paymentMethod:STPPaymentMethod,_ shouldSavePaymentMethod:Bool,_ intentCreationCallback: @escaping (Result<String,Error>)->Void){// Make a request to your own server, passing paymentMethod.stripeId and shouldSavePaymentMethod, and receive a client secret or an error..let myServerResponse:Result<String,Error>=...switch myServerResponse {case.success(let clientSecret):// Call the `intentCreationCallback` with the client secretintentCreationCallback(.success(clientSecret))case.failure(let error):// Call the `intentCreationCallback` with the errorintentCreationCallback(.failure(error))}}}
post '/create-intent'do
data =JSON.parse request.body.read
params ={
amount:1099,
currency:'usd',# 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},
confirm:true,
payment_method: data['payment_method_id'],# the PaymentMethod ID sent by your client
return_url:'your-app://stripe-redirect',# Use the return url you set up in the previous step
mandate_data:{
customer_acceptance:{
type:"online",
online:{
ip_address: request.ip,
user_agent: request.user_agent
},},},}if data['should_save_payment_method']
params[:setup_future_usage]="off_session"# Set setup_future_usage if should_save_payment_method is trueendbegin
intent =Stripe::PaymentIntent.create(params){client_secret: intent.client_secret}.to_json
rescueStripe::StripeError=> e
{error: e.error.message}.to_json
endend