Search code examples
swiftxcodeapp-store-connect

In-App Purchase Payment Transaction Not Functioning


My app displays prompts when the user clicks a specific button. I'm want to have additional prompt packages for non-consumable in-app purchase available (click the package to purchase, then if purchased you can use that same button to toggle the package on and off).

Below is all the relevant code...

import UIKit
import QuartzCore
import StoreKit

class ViewController: UIViewController, SKPaymentTransactionObserver {



    let productID = "com.domain.app.purchase"


    override func viewDidLoad() {
        super.viewDidLoad()

        SKPaymentQueue.default().add(self)
    }


    var packsUnlocked = false



    @IBAction func selectPack1(_ sender: UIButton) {


        if SKPaymentQueue.canMakePayments() {
            let paymentRequest = SKMutablePayment()
            paymentRequest.productIdentifier = productID
            SKPaymentQueue.default().add(paymentRequest)
            print("Initiating Transaction")
        } else {
            print("No Purchased")
        }


        if packsUnlocked == false {
            print("It's locked, ‘Pack 1’ not enabled")
        } else {
            print(“Utilize Purchase”)
            //this is where you place code to use the purchased ‘Pack 1’
        }


    }



    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions{
            if transaction.transactionState == .purchased {
                packsUnlocked = true
                print("Transaction Successful")
                } else if transaction.transactionState == .failed {
                    print("Transaction Failed")
                    }
            }

        }

}

However whenever I run the code and click the button all I get is the below outputs in the debugger:

"
Initiating Transaction
It's locked, 'Pack 1' not enabled
Transaction Failed
"

This is my first app and I've never set up a sandbox tester before, so I'm not sure if the code is the problem or if it's something with my App Store Connect setup.

Thank you - I've been stuck on this for wayyy too long so any help is GREATLY appreciated.


Solution

  • You need to test In-App Purchases on an actual device in the sandbox environment.

    Here is the Apple Documentation on it, but I can guide you as well.

    https://developer.apple.com/documentation/storekit/in-app_purchase/testing_in-app_purchase_transactions

    Main steps are:

    1. Create a sandbox or test user account in App Store Connect.

    2. For iOS 12 or later — Don't sign out of the App Store; simply build and run your app from Xcode. Sandbox accounts are stored separately, and you can control your sandbox account directly on-device in Settings. (You must run on your attached device.)