SwiftUI Auto-Renewable Subscription flow - swift

I have implemented In-App Purchase Auto-Renewable Subscription into my app but I'm not sure if I have done it correctly as the app constantly asks for iTunes login.
In the user case: I am subscribed to monthly payments and my first month is over and expect it to auto-renew.
The flow I have at the moment is as follows...
(in App Delegate) Check receipt is valid
(if receipt IS valid) check all receipts for latest expiration date
(if expired - which seems to be the case after the first month is over) call SKReceiptRefreshRequest to get latest receipts. I have put a count check on this otherwise it gets stuck in a never ending loop.
Do final check to see if latest receipt is in-fact expired.
Is this the correct way to go about this? If not could you shine some light on this?
It all seems to be working fine apart from the annoyance of iTunes login. Which I guess would only be once a month outside of the Sandbox environment which isn't too bad but just want to be sure I'm doing this correctly.
Thanks

Don't call SKReceiptRefreshRequest. This request is usually only for the "restore purchases" mechanism. This is why you're getting the sign in dialogue. StoreKit will return to you as long as you an observer to the payment queue: https://developer.apple.com/documentation/storekit/skpaymentqueue/1506042-add so you should add yourself to the payment queue on app launch. Then keep that object aline to listen for changes for the entire app lifecycle. You will receive the renewals in the updatedTransactions callback https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver/1506107-paymentqueue
Secondly, you should be doing receipt validation on your own server and not on the client as it will be susceptible to a MITM attack. You can also easily control the logic there and receive Server to server notifications which is best for managing subscriptions.

Related

What is the recommended logic to use when checking authenticity in Auto Renewal Subscriptions

I have an app where I’m offering Auto Renewal Subscriptions. Here is how it currently works, when the user subscribes, it saves a Bool in UserDefaults as true, after that I can make a receipt request to see if the subscription has expired. My issue or what I don’t fully understand is the logic on how often to make that request, checking for authenticity every time the user launches the app seems like a lot, or do I need to save the expiration date in UserDefaults and just check a couple of days after the expiration date to see if the user renewed? This way we limit the requests we make to retrieve the Apple receipt.
Can someone share the logic used when checking for authenticity in an app using Auto Renewal Subscriptions?
The "right" way to do it is to manage everything server side (with some caching on the device in case the user is offline). Refreshing the receipt on the device is insecure, slow, and could make that annoying "Login with iTunes" prompt keep popping up for the user :)
It also prevents you from ever having complete analytics of your subscriber base since you can only get data points when they are active in the app.
What you would do is store the receipt file in a database after purchase, and refresh it there to keep the subscription status up-to-date. Then your app is asking your database if the user is subscribed (and caching the value in UserDefaults).
Here is a good blog post that outlines what the setup should look like: iOS Subscriptions are Hard

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 Purchase Subscription Auto Renewal

I have implemented a couple of months ago the in app auto renewable subscription on two of my apps. I stored the old receipts of my users and contacted Apple from my server at the end of the subscription period to check if the subscription is still active.
I noticed that some of my users are being auto-renewed form the client code itself.
My app upon entry calls [[SKPaymentQueue defaultQueue] addTransactionObserver:myObserver] and when either SKPaymentTransactionStatePurchased or SKPaymentTransactionStateRestored is returned it calls my server to verify the receipt and give my users the subscription.
I have been trying for quite some time to understand the logic behind the transaction notification the client gets at the end of the renewal period. Does anyone knows why only some of the users get the notifications and the rest require the server to revalidate their receipts? I tried to think maybe it has got something to do with the call to addTransactionObserver. Maybe those users killed the app while it was in the background and entered the app again after the subscription period ended which caused the addTransactionObserver: to be fired and the notification to arrive.
If I can get all of my users to get this notification I wouldn't have to run the server calls anymore at the end of the subscription period as they would be fired from the client when needed.
Any insight would sure help understand this puzzle.
Thanks
Roi
My experience states you'll need to continue periodically verifying receipts on your server. I have noticed the same as you, that these new receipts are sent to the app inconsistently. I think Apple will send the receipt to the client if they happen to freshly launch the app within a certain time frame of the new renewal.

Auto-renewable subscriptions calling SubscriptionsUpdated

I have implemented som auto renewable subscriptions in my app and everything works well. I perform a purchase in the app, everything gets synced to a server, and the server then checks the iTunes API as soon as the subscription has expired to detect if the subscription has been renewed.
One thing confuses me though. Every once in a while I get a call to transactionsUpdated within my app with a transaction with status: Purchased. This is usually done after I restart the app.
Why do I get these calls? Has it something to do with the subscription beeing renewed? Can I safely ignore these calls? Everything seems to work fine.
Thanks in advance!
Yes, what Apple is doing is sending you a receipt for an automatic renewal of the subscription. Because all durations are drastically shortened in the sandbox, the subscription will get automatically renewed by Apple every few minutes, for a limited number of times (like 5), before they stop renewing.
Since you're already checking for new receipts at the right time on your server, you can ignore the receipts they're automatically sending to the app on occasion.

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.