StoreKit2 to validate purchase of paid-app - app-store

I have a paid-up-front app in the Mac App Store, and I want to verify that the user purchased the app legitimately by verifying the receipt. The StoreKit2 framework (introduced with iOS15/macOS12) claims to have an easy way to do this, but I can't get it to work. From the documentation I've seen, I believe the Transaction.currentEntitlements call will only return transactions for IAP and subscriptions. There is another method Transaction.all which says it "returns all transaction history", but it's not clear if it should include transactions for paid apps. I've tried running the app (with Xcode debugger attached) I get no results.
Here's how I'm calling it:
for await result in Transaction.all {
guard case .verified(let transaction) = result else { continue }
print("verified product = \(transaction.productID)")
}
But I get nothing printed in the console when I run this.
This is what the documentation says about Transaction.all:
This sequence returns the user’s transaction history current to the
moment you access the sequence. The sequence emits a finite number of
transactions. If the App Store processes new transactions for the user
while you’re accessing this sequence, the new transactions appear in
the transaction listener, updates. The transaction history doesn’t
include finished consumable products or finished non-renewing
subscriptions, repurchased non-consumable products or subscriptions,
or restored purchases.
Even after reading this, I'm not 100% sure if paid apps transactions should show up in the transaction history or not.
Can anyone clarify this? If it should show paid apps in the history, what's the best way to test this out during development (before it's actually in the App Store)?

Related

How to get purchaseHistory for IAPs with BillingClient

As the documentation says:
queryPurchaseHistoryAsync():
Returns the most recent purchase made by the user for each SKU, even if that purchase is expired, canceled, or consumed.
So lets say I would like to make an IAP for the user to remove Ads forever from my app.
How do I decide with a fresh install if that user already purchased that IAP if this function also returns the "canceled" IAPS?
I would like to query the actually purchased IAPS, not everything. Becuase that way a user could unlock the Ad free version with a cancelled IAP.
To make it worse, the Purchase class doesn't have status like "cancelled" or "consumed" I cannot decide the state of the user's purchased IAPS.
Am I missing something here?
Thanks in advance
The billing client documentation states it checks for the user.
Then we have the question: Who is the user
If you look at the steps taken for the billing api on https://developer.android.com/google/play/billing/billing_library_overview then you see that a connection to google play is needed.
What happens then is that the current user on android, the account they are signed in with on google play and their mobile device is determined to be the user.
So if they purchased it via google play in app, it will always be assigned to that user on google play and that is what's being queried by this. No matter on which device they are logged in, Their tablet, smartwatch, phone, television, etc...
How to get a list of actually bought products
Instead of using async that gives you everything included abandoned shopping carts I suggest you use https://developer.android.com/reference/com/android/billingclient/api/BillingClient#querypurchases
That way Get purchases details for all the items actually bought and paid within your app. This method uses a cache of Google Play Store app without initiating a network request.
Note: It's recommended for security purposes to go through purchases
verification on your backend (if you have one) by calling the
following API:
https://developers.google.com/android-publisher/api-ref/purchases/products/get
If you read that API link it's easy to check with the online cache if the purchase was valid with a simple GET request.
Personally I would build in a check if the phone is suspect to be rooted before doing the manual background check with the purchases API that sends a request to the store.
Phones that are not rooted have a higher trust level, as the user are probaly not very tech savvy and will not have a shimmer of a clue how to circumvent such checks, and the google play cache will be updated regularly, reflecting trustworthy data.
When a phone is suspect to be rooted(you can read protected directories/write to them), then perform the check online if they bought the stuff each time you deem it neccesary.

Removing autorenewable subscriptions from iPhone App

I have an iPhone app that also features autorenewable products as an in-app purchase. The products are subscriptions to our service for up to 1 year in the future. We wanted to remove the whole in-app-purchase and autorenewable product from our app in the next version.
To accomplish this, we removed the signup option inside our app, so no new user should be able to sign up. Now we would like to disable the automatic renewal for all existing users.
How can I accomplish this? Is it sufficient to remove the in-app-products for our app inside iTunes Connect? Do the users get notified about this?
According to Apple (see WWDC 2011 Session 510, In App Purchases for iOS and OS X, at the 48:55 mark), the only things you can do as a developer to prevent subscriptions from auto-renewing are:
Raise the price.
Remove the auto-renewing IAP product from iTunes connect.
In both cases, notification emails are sent to subscribers, though not immediately. The talk says Apple checks 10 days before a (yearly) subscription renewal and sends email at that time. It's not documented anywhere, though, so I'd treat that as an implementation detail.
I've done the latter (removing the product) several times with my own (monthly) apps, and it seems to work as advertised.
One important note: if your app is a Newsstand app, it must have at least one auto-renewing subscription available. If you remove the last one, the app will be removed form the App Store. Users who have already purchased it will still be able to use it, and will be able to download copies from the "previously purchased" section of the app store, but no new copies will show up for purchase in the App Store proper.
It will depend on how you've implemented your system. Do you check receipts (and provide data/service) from your own server, or do it all within the app directly with Apple's servers?
In iTunes Connect you can remove a product from sale, effective immediately or at a future date. I suspect that's enough to stop a renewing subscription. (Remember you can test this with shortened timescales in the Sandbox.) But if not:
If you use your own server to validate receipts, go and give it an incorrect shared secret so that the verification step fails. That means the subscription validity will return as false (although for the 'wrong' reason) so your customers won't be able to renew.
If you do it within the app, generate a new shared secret so the one within your existing structures is incorrect. Then, as above.
If you can, I suggest sending a notification to your current users notifying them of the change, suggesting that they change, and letting them know it will 'fail' in the future but that's ok.

Restoring In-App Purchase Transactions

The idea is whether rain or shine, wet or fine, user must get that he paid for all out.
From Apple:
Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions
For these transactions Apple Store Kit has good build-in tools. I want to focus on other types (consumable in particular).
One and only transaction information is an identifier and a receipt data which we receiving by Store Kit after successful purchase.
Our application uses server-side model to deliver products to it. But there still much cases of losing purchase data, such as if the server lay down while user is making purchase via App Store so its not possible to send receipt to server to complete verification process.
Current workaround is:
Server returns a list of product identifiers
User selects one; app saves its identifier on device (via SQLite or Core Data). Standart Apple Store transaction process goes right after that.
In case of success application saves receipt data in conjunction with its identifier on device and send it to server. If there were failure or cancelation the identifier is immediatelly removed from device.
If server's response is OK then app removes identifier with receipt data from device. Otherwise it will send requests to server periodically until successful response behaves.
But this approach still has leaks. For example, user can remove application from device not waiting for transaction delivering to server, so there will not any proof about his purchase at all.
Your suggestions?
The fundamental rule is that you not call finishTransaction: on the payment queue until you have successfully delivered content. That means that you make the request to your verification and content servers and they come back with valid responses. Only after those proper responses do you call finishTransaction:. Note that bad purchase receipt is valid just not good. You will get people trying to ripoff goods - don't lose sleep over it but do put in proper receipt checking.
As I understand it (from my non-consumable items), as long as you do not call finishTransaction, the store will continue to retry it on your app installation. For that reason, I do not think you need your application to save the receipt on the device. However, for consumables, the server has to store the data if you want to be able to restore it later. A non-trivial problem is what key to store it under.
BTW, your first line is absolutely correct and worth losing sleep over.

In app auto-renewable subscriptions

Sorry for the millionth question about iTunes subscriptions, but I still have a few doubts.
Basically I'm implementing auto-renewable subscriptions in my app and I want to make sure I got it right. Here's a list of steps to take that I came up with:
whenever an user buys a subscription, send the receipt to the server to validate it
if the receipt is valid, save it on the database
on application load, ask the server if a receipt for this UDID exists (this is to figure out if the user has a valid subscription)
if so, check if a new item has been added on the store in a date range from the subscription start date to the expire date
if any, notify the user about those items in some way and mark them as freely downloadable
Are these steps correct? And if so, why does the Apple doc say:
In most cases, your iOS client application should not need to change. In fact, your client application is now made simpler, as you can use the same code to recover auto-renewable subscriptions as you do to recover nonconsumable products. This is described in “Restoring Transactions.”Your application receives a separate transaction for each period of time where the subscription was renewed; your application should verify each receipt separately.
To me it looks like this needs some code to handle all the various cases I mentioned, instead. Or I'm totally wrong about it. Am I?
Plus, how do I know about the subscription expiration date? I can't find a way to get this information anywhere. Am I supposed to save this on my own database?
Update:
I've figured out a few things since I posted this question. Feel free to correct me if I'm wrong.
First of all I guess I'm supposed to store the length of the subscription somewhere on my own database, because as stated on Apple's docs, you cannot retrieve it in any way through Apple's web services. In fact, each subscription length has a different product identifier, so you should have a way to convert a product identifier to a subscription length.
Also, Sylvian has posted details about his implementation of auto-renewable subscriptions, so at least I know my thinking wasn't too much flawed.
Now the only problem is this: how do I know that an user has a valid subscription? I could store this information on my server, yeah, but how do I associate an user with a completed transaction? Should I save the device's UDID?
Here is how we implemented In App Purchases and specifically the new auto-renewable products at my company.
The application transmits the transaction receipt to our webservice, we return OK to the application if we handled it correctly and Apple could verify it. In that case we updated the user account (i.e. the database) to say "yes he has paid and his subscription is valid till the receipt expiration date".
After the OK for this webservice, the application reloads the account info through another webservice, and see there is a valid subscription. That was it... Until auto-renewable products appeared.
We now had to implement some CRON jobs which runs every day: every day we make a list of passes which are supposed to expire, and we ask Apple if the original receipt is still valid: the magic thing is that in their answer, there is a field latest-receipt which embeds the latest receipt. If it is not the same as the one we have, we understand that the subscription has been renewed automatically, we store the latest receipt for the next cron check, and we update the user account to extend the expiration date.
Hope it helps.
I think I found a solution. It doesn't require an additional username/password and it seems to be working.
Note: If you think this is inappropriate, please explain why in the comments. Thanks.
Basically, whenever an user buys a subscription, I validate the receipt against my server and store the receipt data in the user defaults. Then, when the app is opened, or whenever I need to check if the subscription is still valid, I retrieve the previously saved receipt data from the user defaults and validate it against the server.
My webservice just returns whether the subscription is still valid or has expired, plus some other related information such as the subscription length. To do this, it just queries the iTunes server as usual, and checks if the status response is nonzero. 21006 means that the subscription has expired.
If your app has some user management i.e. you use username/password to use the app, then you have to maintain a server to record the purchase/validity of the currently logged in user. This is applicable for normal subscription and non-consumable purchase. But... if you use the new auto-renewable subscription, then it's NOT possible to maintain multiple user in that app, because : this kind of purchase can not be done multiple times within the subscription period using the same Apple ID from the same application and I found it really annoying and finding a better solution for this case i.e where I have multiple child account in the app but I want to use the same Apple-Id to purchase a auto-renewable subscription for each account. And I think I have to use the old subscription model. Any new thoughts ?
as far as I have understand it the apple server will contact you (or the customer with his iPhone) and tell "look here I have a valid purchase for you". Inside your App you read this message and unlock the regarding content for use. The next step is to tell the apple server that you have responded to the receipt and the apple server will not show the message again.
So with a renewable subscription you get for each period a new message. Correct me if I'm wrong, please.

How to redownload an in-App purchase application programmatically

I am able to implement in-App purchase successfully. I am also able to purchase a product through in - App purchase.I am storing purchase information in NSUserDefaluts.So if next time user tries to purchase same product again i am able to handle it locally.My problem is if a user deletes the application from the device,How do i handle the re-downloading of the application without charging for the same product again.I know that if an application has been deleted from the device having in App purchase it has to be downloaded again.Can anybody show a sample code for the same?
Thanks
Aditya
Hi
Thanks for a prompt reply.I have implemented the same as you have suggested.What i'm wondering is if i delete my app and install it again , i am asked to purchase it again.Do i have to pay again for the upgrade or is it handled from the apple server(i.e if i upgrade the same product again am i charged again?).Is there a way to know it was upgraded without asking to upgrade again?
The StoreKit api takes care of this and gives you, on request, a list of identifiers of the purchased items. Once you got those, it's up to you to re-download the products again(if not already bundled inside the app).
Excerpt from the StoreKit API help:
-(void)restoreCompletedTransactions
Asks the payment queue to restore previously completed purchases.
Your application calls this method to restore transactions that were previously finished so that you can process them again. For example, your application would use this to allow a user to unlock previously purchased content onto a new device.
When you create a new product to be sold in your store, you choose whether that product can be restored or not. See the In App Purchase Programming Guide for more information.
The payment queue will deliver a new transaction for each previously completed transaction that can be restored. Each transaction includes a copy of the original transaction.
////Comments pseudo code////
// Reinstall App:
// Restore already purchased transactions...
// Does the NSUserDefaults have the Purchase History??? -
// YES: Load the Table View of Items remaining for sale, Else -
// NO: Get the restoreCompletedTransactions list from Apple
// and create a container to hold previous transaction purchases.
// Fresh new App install:
// When a user makes the first IAP. Add it to the container and NSUserDefaults
// This container will be added to the NSUserDefaults when at least one purchase has been made.