また、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 =
classMyCheckoutVC:UIViewController{overridefuncviewDidLoad(){// This is only for testing purposes:
#ifDEBUGTimer.scheduledTimer(withTimeInterval:5.0, repeats:true){[weakself]_inTask{ @MainActorinself?.embeddedPaymentElement?.testHeightChange()}}
#endif
}}
extensionMyCheckoutVC{funcupdate(){Task{ @MainActorinvar updatedIntentConfig = oldIntentConfig
// Update the amount to reflect the price after applying the discount code
updatedIntentConfig.mode =PaymentSheet.IntentConfiguration.Mode.payment(amount:999, currency:"USD")let result = await embeddedPaymentElement?.update(intentConfiguration: updatedIntentConfig)switch result {case.canceled,nil:// Do nothing; this happens when a subsequent `update` call cancels this onebreakcase.failed(let error):// Display error to user in an alert, let users retrycase.succeeded:// Update your UI in case the payment option changed}}}}
extensionMyCheckoutVC{@objcfuncdidTapConfirmButton(){Task{ @MainActoringuardlet embeddedPaymentElement else{return}self.view.isUserInteractionEnabled =false// Disable user interaction, show a spinner, and so on before calling confirmlet result = await embeddedPaymentElement.confirm()switch result {case.completed:// Payment completed - show a confirmation screen.case.failed(let error):self.view.isUserInteractionEnabled =true// Encountered an unrecoverable error. You can display the error to the user, log it, etc.case.canceled:self.view.isUserInteractionEnabled =true// Customer canceled - you should probably do nothing.break}}}}
extensionMyCheckoutVC{funchandleConfirm(_ intentCreationCallback: @escaping (Result<String,Error>)->Void){// Make a request to your own server 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},}begin
intent =Stripe::PaymentIntent.create(params){client_secret: intent.client_secret}.to_json
rescueStripe::StripeError=> e
{error: e.error.message}.to_json
endend
// 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}}