Search code examples
iosswiftxcodestorekit

auto-renewable subscription renew?


there I am new to auto-renewable subscriptions. I have implemented the subscription. My problem is if the user buys the subscription for the first time app will go premium. but in any case, his second payment is not happened because of any reason. how did I know that the payment was not successful and or successful? I followed the WWDC tutorial for in-app purchases. implemented with storekit 2.

func purchase(_ product: Product) async throws -> Transaction? {
        //Begin a purchase.
        let result = try await product.purchase()
        
        switch result {
        case .success(let verification):
            let transaction = try checkVerified(verification)
            print(transaction)
            print(transaction.expirationDate as Any)
            
           
            
            //Deliver content to the user.
            await updatePurchasedIdentifiers(transaction)
            
            if !purchasedIdentifiers.isEmpty{
                IAP.premiumEndDate = transaction.expirationDate
            }
            //Always finish a transaction.
            await transaction.finish()
            
            return transaction
        case .userCancelled, .pending:
            return nil
        default:
            return nil
        }
    }

Solution

  • In IAP's apple generate a receipt against each transaction containing a lot of information like a digital signature to validate the purchase, history of transactions including successful and unsuccessful transaction, the current status of the subscription, expiry date, and much more.

    You have to validate the receipt by fetching from the Apple server to get all this information. you can check this to know how to fetch receipt data.

    for validation, we can go with 2 techniques

    1. On-device validation(validation on the device locally if you're not using server in your app)
    2. Server-side validation(Recommended)

    you can read more about choosing receipt validation technique here.

    When you fetch receipt it will give you a receiptData and you will convert it to base64EncodedString and hit API for receipt.

    For SandBox use https://sandbox.itunes.apple.com/verifyReceipt and for production use https://buy.itunes.apple.com/verifyReceipt. pass it two parameters Receipt base64String and App-Specific Shared Secret you can find App-Specific Shared Secret on App store on the top right corner of your in-app purchases list.

    You will receive a response containing all information about the subscription.

    Check this video of title Engineering Subscriptions from WWDC 2018. This video is really helpful in understanding subscriptions.