In App purchase

PHOTO EMBED

Mon Apr 08 2024 11:48:34 GMT+0000 (Coordinated Universal Time)

Saved by @Saurabh_Lodhi #swift #inapppurchase

import StoreKit

//inside viewController
let productId = "your_product_id"


//Action where you want to trigger the purchase
@IBAction func btn_OneTimeButtonClicked(_ sender: UIButton) {
	if SKPaymentQueue.canMakePayments(){
		let paymentRequest = SKMutablePayment()
		paymentRequest.productIdentifier = productId
		SKPaymentQueue.default().add(paymentRequest)
	}
}

//extension to handle the transaction states

extension your_View_Controller: SKPaymentTransactionObserver{
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        transactions.forEach { transaction in
            switch transaction.transactionState{
            case .purchasing:
                print("purchasing now ...")
            case .purchased:
                print("purchase successful !!!")
            case .failed:
                print("purchase failed !!!")
            case .restored:
                print("purchase restored !!!")
            case .deferred:
                print("purchase deferred !!!")
            @unknown default:
                print("Unknown error")
            }
        }
    }
}

// don't forgot to add storekit configuration file in your app if you are testing your app in simulator

content_copyCOPY

Apply in app purchase in the simulator