Featured

Welcome to FMX (Firemonkey) Blog

I’ve been developing with Delphi for 20 years since Delphi 1 and it’s been an interesting ride, with lots learned each year. I took a break during the “dark years” of Delphi 8 through XE but since then have been using every version of Delphi.

Delphi may not be as popular a language as it used to be, mainly due to fashion changes, the trendy new developers moving away from all-in-one IDEs, and preferring Open Source, web-originating frameworks and languages. However, it’s still a powerful, modern language capable of incredible things, and well worth looking into if you’re new to the coding arena and want to try something that is genuinely cross-platform.

The Firemonkey framework has been the most interesting additions to the Delphi family, adding support for iOS, Android and MacOS, both 32bit and 64bit variants – and now even Linux Desktop and server support. It’s a bold move on Embarcadero’s part but one that will hopefully pay off for them.

Our mainstream product, MyShiftPlanner, is one of the most popular shift worker time management app on the stores and is written completely in Delphi using Firemonkey. It’s taken 5 years to get it where it is and was initially written in XE5 but now runs like a dream under Delphi Rio 10.3.3.

I’ve learned a lot along the way which I wanted to share with anyone else who wants to take advantage of the power of this truly cross-platform framework.

Each article covers a specific topic but mostly helping to extend what Firemonkey does out-of-the-box so you can take advantage of even more for your apps. The blogs will cover how to add in-app subscriptions to your apps, how to include third party frameworks, use more native controls than are supplied by Firemonkey and more. I’ll also include links to other people’s blogs which offer similar benefits so you can find what you need in one place.

I hope you enjoy this blog and find it useful. Please continue to share/ promote the benefits of Delphi and support your fellow Delphi community developers.

Happy coding!

iOS Extensions with Firemonkey

Adding extensions to an iOS app is something that Delphi doesn’t support natively, but there is a way (with a few hurdles) to get this working in your Firemonkey app.

The first part of this article is based on this excellent Grijjy Blog article which I highly recommend reading: https://blog.grijjy.com/2018/11/15/ios-and-macos-app-extensions-with-delphi/

Introduction

First of all, I want to be clear that you can’t create extensions in Delphi (Pascal) directly, so you will need to learn enough Objective C to create them natively in Xcode. You’ll do this alongside a host app (also written in Objective C through Xcode) to test your extension. How you do this is completely up to you, and there are a lot of excellent tutorials, so Google away.

I’ve successfully built Delphi apps with accompanying Today and Share extensions (written natively) but the principle should be similar for other extension types.

Once you have a native app with a working extension in Xcode, you can extract the extension from the built app, and embed that into your Delphi Project.

All of the above is covered in the Grijjy blog so I will summarise it below, but if you’d like a better explanation as to how and why this is the case, please refer to the blog post.

If you’re creating a Share Extensions to allow other apps to share into your Delphi app, I recommend this post as an explanation of how to set up bundle groups and a simple working sharing app:

https://www.technetexperts.com/mobile/share-extension-in-ios-application-overview-with-example/

The Stages

I won’t go into detail here about how to create the Extension or share data between that and your Delphi app, as this is covered in the Grijjy blog and tutorial included above. I will however go into details above what you do next which isn’t covered by the above.

The problem is that you can build and include your plugin easily in your Delphi app, but it won’t actually run on your device.

Why? because Delphi only know about the app not the extension, so only includes one provisioning profile when signing. The problem is that your extension requires a separate profile, so the app needs building with two which Delphi doesn’t support.

If you try building, you will see errors like this:

[PAClient Error] Error: E0776 error: exportArchive: “<extension-name>.appex” requires a provisioning profile with the App Groups feature.

To resolve this, you need to take over the signing process from Delphi and make the necessary calls to xcodebuild with the correct information. A little fiddly but not too difficult.

This article attempts to take you through the process.

Note: I haven’t gotten this working for development builds, only release builds at the moment as the flow is different.
This means that the only way to test your Delphi + extension is to build for the App Store in Release mode and upload to TestFlight. This isn’t too bad if you’ve already tested your extension with a test (host) app in Xcode first, so make sure you do that or you’ll waste a lot of time uploading builds to TestFlight!

If I manage to get the following process working for the development builds too, I will update this article.

Building your Extension and Host App

First, build the app. The basic sequence is as follows:

  1. Use Xcode to build a native iOS app.

    Important – it MUST be created in Objective C not Swift. Delphi apps are effectively wrapped as Objective C apps so don’t play well with Swift extensions.
    Also Important – the bundle identifier of the host app MUST be identical to your Delphi app (if it already exists at this point). The host app you’re creating here is a test app which is pretending to be your Delphi app so you can test the extension and data-sharing between the two.
  2. Add an extension in Xcode (File > New > Target, then pick the extension type). The bundle identifier should be the same as the host app (step 1 above) but with a suffix specific to the extension. E.g. for an app “com.example.myapp” the extension should be “com.example.myapp.<extension_name>”.
  3. Build and test your extension in Xcode – make sure it works as expected.

    TIP: If you want to share data between your host app and extension (very likely), the most Delphi-compatible way is to create a bundle group, then use NSUserDefaults in both your extension and Delphi app to transfer data.
    How to do this on the Delphi side is included in the Grijjy blog, and how to do this from the Extension side is explained in the Share Extensions tutorial link.
  4. At this point you need to have a working Objective C app with an extension that is working and tested.

Provisioning Profiles Setup

If your Xcode host app and extension are using Xcode Managed Signing (which is very likely) then you will need to create development and deployment profiles manually and use them instead, as Delphi can’t access the Xcode managed profiles.

To find out if you’re using Xcode managed signing:

  1. In Xcode, tap the top item in your files tree on the left to show the project details on the right
  2. In the Signing & Capabilities tab, tap on each item in the Targets list. You will see a checkbox for “Xcode managed signing”. If they’re checked you need to do the steps below to create profiles manually and use them in Xcode.

    Manually creating your profiles

    Note: You will need to follow these stages twice – once for your main app identifier (e.g. com.example.myapp) and once for the extension (e.g. com.example.myapp.shareextension) as extensions have their own app ID and therefore need their own profiles.
  1. Open developer.apple.com, sign in and go into Certificates, IDs and Profiles
  2. In the Profiles section, tap the + button.
  3. Select App Store under the Distribution area.
  4. Select your app ID
  5. Follow the remaining stages, then create and download the certificate at the end.
  6. Double-click the downloaded file to install it into Xcode.
  7. Repeat the above for the extension app ID so you have 2 provisioning profiles, once for each.

Once you have your profiles:

  1. Open Xcode (if not already open)
  2. Tap on the top item in the files tree on the left to see the profile information details.
  3. You will have 2 items in the Targets area – once for the host app and one for your extension. You need to do the following for both targets:
  4. In the Signing & Capabilities tab, click the “Release” option in the toolbar (where it says “All, Debug, Release”) and uncheck the “Automatically manage signing” option.
  5. Select your team (it may be blank) and then select the correct provisioning profile from the list. The two you created in the developer website should appear here and be shown as “eligible”.
  6. Repeat for both targets.
  7. Build and run your app in Xcode again and make sure if still works correctly.
  8. Now you need to Archive the app within Xcode via the Product > Archive option
  9. After a short while the Organiser window will open showing your archived app (most recent at the top).
  10. Select the most recent archive file, then “Distribute App” button
  11. Choose “App Store” then Export (not Upload).
  12. Complete each of the following steps to get your archive file. When asked, make sure to uncheck “include bitcode…” and choose the correct distribution profiles for your app.

At this point you’re ready to transfer your extension into Delphi.

Extracting your Plugins Folder

To extract the Plugins folder, open the folder where you exported the archive to.

Note that you will need the ExportOptions.plist file later, so don’t lose it!

  1. Rename the .ipa file to .zip and extract it.
  2. In the Payload folder will be a .app file you need.
  3. Right-click on the app file and Show Package Contents
  4. Copy the Plugins folder to your PC inside your Delphi Project folder.

The Delphi Side

Once the Plugins folder is in your Delphi project folder, you need to include all of the files from the this folder in your Deployment within Delphi.

NOTE: On a Mac, the Plugins folder looks like it only contains one file – “Extension.appex” or similar. This is really a folder, and will show as such when on Windows. You need to make sure you include every file within the “.appex” folder and its subfolders in the distribution of your Delphi app or it won’t work!

The easiest way to do this is to use the DeployMan.exe tool kindly provided by Grijjy:

https://github.com/grijjy/DelphiSocialFrameworks/tree/master/DeployMan

Run this tool, choose “Import .dproj” from the menu and select the .dproj for your Delphi app, then add the entire Plugins folder into the list.

Make sure that the Target Directory is set to “./Plugins” and Include Subdirectories is checked.

Also, tap the Configurations option in the top-right and make sure you choose Debug if the extension was build for development in Xcode, or Release if build using the Archive technique.

The reason for this is because building for Archive or for development (the play button in Xcode) uses different provisioning profiles so they are different folders.

Deployman screenshot

Now File > Save Project and .dproj.

When you go back into your Delphi app it will detect the change and ask if you want to reload the project – say Yes!

Build and run your Delphi app. The bad news is that the extension still won’t work at the moment.

The trouble with profiles…

Delphi doesn’t support extensions for iOS app, which brings with it a big problem.

Extensions require separate provisioning profiles to the main app, so your app actually needs signing against two provision profiles, but Delphi only signs it against one as it doesn’t know any different.

If you try to perform a release build (for the App Store) through Delphi, it will generate an .app file containing everything you need but will be unable to sign it to generate the archive (.ipa) you will need to upload it to the App Store.

The error you will see will be something like this:

[PAClient Error] Error: E0776 error: exportArchive: "<extension-name>.appex" requires a provisioning profile with the App Groups feature.

[PAClient Error] Error: E0776 Error Domain=IDEProvisioningErrorDomain Code=9 ""<extension-name>.appex" requires a provisioning profile with the App Groups feature." UserInfo={IDEDistributionIssueSeverity=3, NSLocalizedDescription="<extension-name>.appex" requires a provisioning profile with the App Groups feature., NSLocalizedRecoverySuggestion=Add a profile to the "provisioningProfiles" dictionary in your Export Options property list.}

This is because it can only find a provisioning profile for the main app and not the extension.

For your app to work with an embedded extension, you will need to create a folder containing all the necessary files, then run xcodebuild manually to perform the archiving and signing process yourself on the .app file that Delphi generates.

The folder you are creating will have the same structure as a .xcarchive file (i.e. a temp subfolder and a Products subfolder into which your .app will be copied)

To perform the signing and archiving you need to create a folder containing 3 things:

  1. The .app file Delphi has generated ready for release (despite the error Delphi shows when building, the .app file is correct so copy it from your scratch folder)
  2. The exportOptions.plist file from the exported archive file described above which provides all the details about your app and references to the necessary provision profiles for both the app an extension.
  3. An info.plist file which is NOT the same as the ones generated in Delphi, so I’ve given details on this below.

For more info on the export procedure we’re following, see this article from Apple:
https://developer.apple.com/library/archive/technotes/tn2339/index.html#//apple_ref/doc/uid/DTS40014588-CH1-WHAT_KEYS_CAN_I_PASS_TO_THE_EXPORTOPTIONSPLIST_FLAG

The best approach is to create a shell script on the Mac to automate this, but that won’t be covered here.

Step 1 – get the .app file:

Build your app in Delphi for Release (App Store) if you haven’t already. It will fail with the error mentioned above, but that’s fine.

Next, open the scratch-dir folder on your Mac which Delphi builds into on the Mac. It’s usually here:

~/PAServer/scratch-dir/<name of Mac>

In here you will see the .app file that Delphi generated for your project.

Wherever you prefer on your Mac, create a folder with the same name as your app file but with a .archive extension (e.g. “MyApp.archive” if your app file was MyApp.app).

Create a Products folder within it and copy the MyApp.app file into the Products folder.

Copy the exportOptions.plist from the exported archive into the root of the .archive folder.

Create a Temp folder inside the .archive folder. This is where the .ipa for upload to the App Store will be generated if all goes well.

Create a plist.info file as described below in the root of the .archive folder.

Once you’re finished, the folder will look like this:

– MyApp.archive/
– info.plist
– ExportOptions.plist
– Products/
– MyApp.app
– Temp/

Creating the info.plist file you need:

Create a file called info.plist and copy in the following template:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ApplicationProperties</key>
<dict>
<key>ApplicationPath</key>
<string>myapp.app</string>
<key>CFBundleIdentifier</key>
<string>com.example.myapp</string>
<key>SigningIdentity</key>
<string>Apple Distribution: teamname (teamID)</string>
</dict>
<key>CreationDate</key>
<date>2019-02-26T17:05:43Z</date>
<key>Name</key>
<string>myapp</string>
</dict>
</plist>

Replace the <Name> value, the <ApplicationPath> value and the <CFBundleIdentifier> values with those for your app. The CreationDate seems not to matter.

The <SigningIdentity> key value needs to be the full (common) name of the distribution certificate (not provisioning profile) the app was generated using. this will be one associated with the provisioning profile, and the name should be similar structure to what I included above.
If unsure about this, download the distribution certificate file from the developer.apple.com portal (from the Certificates section of the portal), then select it in Finder and press the Spacebar to preview it. The name you need is shown in the preview window as Common Name.

TIP: If, when generating the archive (described below) you see errors relating to badly formed or missing “method” keys, it will be due to the info.plist file being wrong.

Generating the Archive (.ipa)

In a Terminal window, run the following command, replacing <scratch-dir> and <appname> as appropriate for your Mac and project:

/usr/bin/xcodebuild -exportArchive -archivePath "<scratch-dir>/<appname>.archive" -exportPath "<scratch-dir>/<appname>.archive/Temp" -exportOptionsPlist "<scratch-dir>/<appname>.archive/ExportOptions.plist"

The archive will be generated in the Temp folder, so at this point you can upload to Test Flight using Apple’s Transporter app.

I hope this was useful for all those who wish to run the gauntlet of Delphi and iOS extensions.

Happy Developing!

QUICK TIP: Accessing files in your iOS app bundle from Delphi

If you include files in your Firemonkey project with a remote path of ./ they’re copied into the main bundle when the app is built and deployed on iOS.

To access these files, you need to get their full path as follows:

Result:=NSStrToStr(TiOSHelper.MainBundle.pathForResource(StrToNSStr(fn), StrToNSStr(ext)));

fn = the name of the file without the extension

ext = the extension without the starting period (e.g. “caf’ not “.caf”)

If the file exists in the bundle it’s full path and filename will be returned, otherwise it’ll be an empty string.

You’ll need to include these units in your uses:

iOSapi.Helpers, Macapi.Helpers;

Happy coding!

Supporting In-App Purchase Subscriptions for iOS and Android Firemonkey Apps

The In-App Purchase support in Delphi is pretty well written and supports Consumable and Non-Consumable out-of-the-box.

Unfortunately, subscriptions aren’t supported by the built-in libraries but the good new is that it isn’t difficult to change the Firemonkey source files to make it work.

This tutorial takes you through the changes needed, along with how to check your subscription status and then how to get through Apple’s rigorous App Store Review process to actually get it onto the store.


If you aren’t already familiar with how to set up in-app purchases in general within your Delphi app, read these links:

http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Using_the_iOS_In-App_Purchase_Service

http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Using_the_Google_Play_In-app_Billing_Service


Pre-requisite: This tutorial isn’t a 101-how to use in-app purchases, and assumes that you’ve followed the above docwiki tutorials (which are really easy to use!) and are familiar with the basics.

Note: This tutorial is based on editing the 10.1 Berlin version of the files. I seriously doubt Embarcadero have updated them in Tokyo 10.2, but please check before making these changes just in case. Also note that you’ll need Professional or higher editions to make these changes as Starter doesn’t include the Firemonkey source files.

Some Background Reading…


The Android Subscription IAP reference is here:

https://developer.android.com/google/play/billing/billing_subscriptions.html


The iOS IAP references are here:

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Chapters/Subscriptions.html


It iOS Receipt Validation Guides are here:

https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Introduction.html#//apple_ref/doc/uid/TP40010573

Let’s get started!

There are 2 workflows you need to add to your app in order to support subscriptions correctly:

  1. Purchase workflow
  2. Subscription status workflow (including activating or deactivating features accordingly)

The purchase workflow is fairly straightforward, but required you to make some changes to the in-built IAP classes provided with Delphi to support it.

The subscription status management workflow can be quite tricky as you’re required to check and handle everything yourself, but with some careful thought about this before starting to code, you should be able to offer a solid solution in your app which doesn’t create a jarring user experience.

Note: I’ll explain how to get access to the subscription status information but how you implement this within your own app logic is totally your choice. Some prefer to do the checking and feature expiry/activation on app load, others in different ways, so I won’t be offering any guidance around this in the tutorial as it will be different for every app.

1. Changes for the Purchase workflow

To start, we’re going to need to edit the following files:

  • FMX.InAppPurchase.pas
  • FMX.InAppPurchase.iOS.pas
  • FMX.InAppPurchase.Android.pas

These reside in the “Source\fmx” folder of your Delphi installation (on Berlin 10.1 this may be: c:\program files(x86)\embarcadero\studio\18.0\source\fmx)

Copy these files into your project folder, but don’t drag them into your project tree within the IDE. Just having them in your project folder will be enough for the compiler to find them and use them in preference to the system versions of the files.

FMX.InAppPurchase.pas:

We’re going to extend the base classes to add a few extra functions which you’ll need in order to produce a decent subscription experience for your users.

Note: in native iOS land, the calls for purchasing a subscription and consumable/non-consumable items is the same – it’s determined automatically by the bundle ID passed in. However, to provide a common interface that’s cross-platform, we added a separate call as you’ll see below that works for Android too.

In FMX.InAppPurchase.pas, make the following changes:

Within IFMXInAppPurchaseService, find:

procedure PurchaseProduct(const ProductID: string);

Add the following below it:

procedure PurchaseSubscription(const ProductID: string);
function GetProductToken(const ProductID: String): String;
function GetProductPurchaseDate(const ProductID: String): TDateTime;

Within TCustomInAppPurchase, search for the PurchaseProduct function and add the same new function headers as above.

Implement the new functions of TCustomInAppPurchase and copy the following code:

procedure TCustomInAppPurchase.PurchaseSubscription(const ProductID: string);
begin
  CheckInAppPurchaseIsSetup;
  if FInAppPurchaseService <> nil then
    FInAppPurchaseService.PurchaseSubscription(ProductID);
end;

function TCustomInAppPurchase.GetProductPurchaseDate(const ProductID: String): TDateTime;
begin
  if FInAppPurchaseService <> nil then
    Result := FInAppPurchaseService.GetProductPurchaseDate(ProductID)
  else
    Result:=EncodeDate(1970,1,1);
end;

function TCustomInAppPurchase.GetProductToken(const ProductID: String): String;
begin
  if FInAppPurchaseService <> nil then
    Result := FInAppPurchaseService.GetProductToken(ProductID)
  else
    Result:='';
end; 

FMX.InAppPurchase.iOS.pas:

Within TiOSInAppPurchaseService, find:

procedure PurchaseProduct(const ProductID: string);

Add the following below it:

procedure PurchaseSubscription(const ProductID: string);
function  GetProductToken(const ProductID: String): String;
function  GetProductPurchaseDate(const ProductID: String): TDateTime;

Implement these new functions using the code below:

procedure TiOSInAppPurchaseService.PurchaseSubscription(const ProductID: string);
begin
Self.PurchaseProduct(ProductID);
end;

function TiOSInAppPurchaseService.GetProductPurchaseDate(const ProductID: String): TDateTime;
begin
Result:=EncodeDate(1970,1,1);
end;

function TiOSInAppPurchaseService.GetProductToken(const ProductID: String): String;
begin
Result:='';
end;

As you can see, these are mostly dummy functions for iOS as this information isn’t available through the APIs, but is on Android.


So how do you get the purchase date and product token for this purchase? That’s where the receipt validation comes in! iOS doesn’t have native API calls to get this information about a subscription (unlike Android) so your app will need to cache the original purchase information at time of purchase, then rely on the receipt mechanism to update this cache at regular intervals in future.


I’ll go into this workflow later in the tutorial.

FMX.InAppPurchase.Android.pas:

Within TAndroidInAppPurchaseService, find:

procedure PurchaseProduct(const ProductID: string); 

Add the following below it:

procedure PurchaseSubscription(const ProductID: string);
function  GetProductToken(const ProductID: String): String;
function  GetProductPurchaseDate(const ProductID: String): TDateTime;

Implement these new functions using the code below:

procedure TAndroidInAppPurchaseService.PurchaseSubscription(const ProductID: string);
begin
  CheckApplicationLicenseKey;
  if IsProductPurchased(ProductID) then
    raise EIAPException.Create(SIAPAlreadyPurchased);
  //The docs say it must be called in the UI Thread, so...
  CallInUiThread(procedure
    begin
      FHelper.LaunchPurchaseFlow(ProductID, TProductKind.Subscription, InAppPurchaseRequestCode,
        DoPurchaseFinished, FTransactionPayload);
    end);
end;

function TAndroidInAppPurchaseService.GetProductPurchaseDate(const ProductID: String): TDateTime;
  var
    Purchase: TPurchase;
begin
  Result:=EncodeDate(1970,1,1);
  if FInventory.IsPurchased(ProductID) then
  begin
    Purchase:=FInventory.Purchases[ProductID];
    if Purchase <> nil then
      Result:=Purchase.PurchaseTime;
  end;
end;

function TAndroidInAppPurchaseService.GetProductToken(const ProductID: String): String;
  var
    Purchase: TPurchase;
begin
  Result:='';
  if FInventory.IsPurchased(ProductID) then
  begin
    Purchase:=FInventory.Purchases[ProductID];
    if Purchase <> nil then
      Result:=Purchase.Token;
  end;
end;

With these changes, you’ll be able to access the most recent transactionID for a product purchase (useful to display in a purchase history UI) and the last purchase date.


It’s worth mentioning how the TransactionID and PurchaseDate behave, so you can decide how best to use them:


Non-Consumable Purchases:

Both are the ORIGINAL purchase date and transactionID for the purchase.


Subscriptions:

Both are the MOST RECENT re-purchase date and transactionID for the subscription. When a subscription is automatically renewed, a new transactionID is generated and the purchase date will update to reflect when it was renewed.


For Android, you can then use the purchase date to work out the expiry date for your user experience. On iOS, you need to use the receipt to get this.



At this point, you will be able to purchase subscriptions for Android and iOS through the updated API. This is only the first part of the challenge! Now we need to check for expiry…

2. Checking Subscription Status

Subscription status checking isn’t as easy as the one-call approach to purchasing, as there aren’t any API calls to give you this information to the level of detail you’ll need.


To get details about the user’s subscription you can do 1 of 2 things depending on the level of detail you require:


1. Just call .IsProductPurchased() on the IAP class.


This will return true/false but may not be as reliable as you think. There as known cases where the store returns “yes” when the subscription has actually been cancelled or expired. This also won’t tell you when the subscription is due to expire so should only used used as a high level check.


2. Use Receipt Validation (iOS) or subscribe to Real-Time Developer Notifications (Android).


This will provide you with real up-to-date information about the subscription, when it’s expected to expire, what really happened to it, why and when.


Note: RTDN (Android) MUST be done from your server as it uses a webhook back to your server – effectively poking your server when something has changed, that you can then use to update your back-end records about the subscription.


For Receipt Validation, this CAN be done from within your app, but Apple recommend you do this from your server too.

Checking for Expiry

The Quick Way – iOS or Android


Using IsProductPurchased() may be enough if all your want to do is disable a feature if the store thinks that the user’s subscription is no longer active.

Subscriptions can be reported as inactive in the following situations:

  • The subscription has expired and isn’t auto-renewable
  • The subscription renewal payment could not be taken (and any payment grace period has expired)
  • The subscription was cancelled by the user, so wasn’t auto-renewed
  • The subscription was made on another device, or the app has been re-installed, and the user hasn’t yet done a Restore Purchases (iOS only).

Note: this isn’t the recommended way to check for subscription expiry, as there are too many ways it can report the status falsely, which can lead to you removing features from paying users – which users don’t tend to like!

The BETTER way – Android

Google offer a push-based notification system, which tells you when something changes about a subscription so you can update your records and act accordingly.


If you have a server on which you keep a record of your user’s purchases, then you can create relevant end points in your server API which can be called by Google’s servers when the status of a subscription changes. This gives you a LOT more information, especially about why it’s no longer active, but will only work if your server keeps a record or has a way to push an IAP status change to your app (e.g. using Push Notifications).


These are called Real Time Developer Notifications and there are instructions in the relevant section here:

https://developer.android.com/google/play/billing/billing_subscriptions.html#realtime-notifications

The BETTER way – iOS

For iOS, Apple offer a receipt validation REST API which you can call to get full details about the purchases made by the user.


Details of how this works is here:

https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html#//apple_ref/doc/uid/TP40010573-CH104


This requires you to send a binary-encoded version of the user’s purchase receipt to their server, along with your API key (generated in the iTunes Connect page where you created your subscription iAP). In return you’ll receive a large JSON object which is the unencrypted version of the receipt with everything you need to know about all purchases the user has made within your app.


The above link gives you an idea of the structure you can expect and what the receipt fields include (and format) so you can process these.


But what is the user purchase receipt and where can I find it?


When a user makes a purchase, a receipt of this is added to a receipt file which is encrypted with the user’s key. The receipt file is stored in the sandbox for the app, so if the app is deleted, so is the receipt file.


That’s great, but if the user re-installs the app, the receipt won’t be there!


This is where the Restore Purchases facility comes in, and why you MUST implement it in your app for iOS. When the user restores their purchases, the app is given a new receipt file, which it then stores in the app sandbox.


It’s this receipt file that is used when you query IsProductPurchased() which is why, if you don’t call Restore Purchases, your app will clam that your user doesn’t have the purchases they’ve paid for.


To find your receipt file within your app, do the following:

mainBundle:=TiOSHelper.MainBundle;
receiptUrl:=mainBundle.appStoreReceiptURL;  
urlAsString:=NSStrToStr(receiptUrl.path); 


You will need to include the following in your uses:

iOSapi.Foundation,
iOSapi.Helpers,
Macapi.Helpers;


Note: You can’t just read this file and get what you need from it, as it’s encrypted against the user’s private key, so you will need to send it to Apple’s validation server, which will decrypted and send you the ready-to-use JSON version of the receipt.


A Delphi-based example of how you may choose to read the file and send to Apple is below:

if TFile.Exists(urlAsString) then</p>
begin
  streamIn:=TFileStream.Create(urlAsString, fmOpenRead);
  streamOut:=TStringStream.Create;
  try
    TNetEncoding.Base64.Encode(streamIn, streamOut);
    receiptBase64:=streamOut.DataString.Replace(#10, '', [rfReplaceAll])
      .Replace(#13, '', [rfReplaceAll]);
    if urlAsString.Contains('sandbox') then<
      baseUrl = 'https://sandbox.itunes.apple.com/'
    else
      baseUrl = 'https://buy.itunes.apple.com/';

    RESTRequest1.Method:=TRestRequestMethod.rmPost;
    RESTClient1.BaseURL:=baseUrl;
    RESTRequest1.Resource:='verifyReceipt';
    RESTRequest1.AddBody('{"receipt-data": "'+receiptBase64+'", '+
        ' "password": "'+cSecretKey+'"}');

    RESTRequest1.Execute;
  finally
    streamIn.Free;
    streamOut.Free;
  end;
end;


NOTE: Apple suggest you don’t do this call from within your app, and instead should do it from your server –  though it’s the same process.


cSecretKey is the shared secret that you need to generate within the iTunesConnect page of your subscription IAP product. It’s only required if you have auto-renewing subscriptions within your app.


In our app’s implementation, we base64 encrypt the receipt file as shown above, but instead of sending directly to Apple, we POST it to our server instead, which then sends onto Apple, and can decode and process the purchase receipt as required in our app’s behalf.


The Resulting Receipt Data

The response you get back from Apple should be the JSON data of the receipt, which is in the “receipt” field of the JSON response.


However, if an error has occurred, the “status” field will tell you what went wrong, so you’re best to test this before assuming the receipt field is valid. A status of “0” means that all went well and your receipt field has been populated. Anything else is an error which you can look up the meaning for in here:

https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html#//apple_ref/doc/uid/TP40010573-CH104


Tip: The most common errors are 21002 which means that your receipt data couldn’t be decoded and may not have been ready correctly from the file. Occasionally it will return this even if your data is correct – maybe if you’ve run a receipt check call twice in quick succession from your app.

The other we had to begin with was 21007 which means you’ve accidentally sent a sandbox receipt file to the live URL or vice-versa.


A Note about Environments

The App Store has 2 areas which affect in-app purchases – Sandbox and Live.

When in Sandbox mode (i.e. when you’re logged into the App Store using a Sandbox User account created through the iTunesConnect portal), you won’t be charged for any purchases made, and subscriptions will have an artificially shortened lifespan so you can test expiry conditions much more easily.

The full receipt validation sandbox URL is:

https://sandbox.itunes.apple.com/verifyReceipt

Note about sandbox subscriptions: Once you’ve purchased a subscription using a specific sandbox account, it will renew 5-6 times (once per hour) then expire. Once expired, you can’t make another purchase of the same subscription under that account, so if you want to test again, you’ll need to create a new sandbox account in iTC.

It’s a bit of a pain, but just what you have to do!

When in Live mode (i.e. you’re logged in with a live AppleID – NOT recommended during testing), all purchases will be charged for, so best to do this once you’re happy your code works as a final test.

The full receipt validation live URL is:

https://buy.itunes.apple.com/verifyReceipt

3. Getting App-Store Ready

So now you should be able to offer your users the ability to purchase a subscription, and get details about it’s expiry, cancellation etc in order to manage access to your feature.

You may now think that you’re able to implement the purchase UX in your app however you choose… but sadly not!

Google seem fairly lenient on the requirements, as long as you make it clear what the user is buying and for how much. Apple on the other hand, have strict requirements for how you present your purchase facility and what details you show to the user about the subscription prior to them purchasing it.

And be under no illusions – Apple will reject your app if you don’t have EXACTLY the right things in your app they’re looking for.

However, they aren’t being deliberately awkward, they simply want to make sure the subscriber isn’t under any illusion as to what they’re buying, how and when they’ll be charged and in what capacity.

When we first submitted our app for review, it was rejected on a few points that at first baffled us. The rejection from Apple was:

We noticed that your App did not fully meet the terms and conditions for auto-renewing subscriptions, as specified in Schedule 2, Section 3.8(b).

Please revise your app to include the missing information. Adding the above information to the StoreKit modal alert is not sufficient; the information must also be listed somewhere within the app itself, and it must be displayed clearly and conspicuously.

Eventually we working it out thanks to a combination of the posts below, but to make life easier, I’ve included the specific requirements below:

https://forums.developer.apple.com/thread/74227

https://support.magplus.com/hc/en-us/articles/203808548-iOS-Tips-Tricks-Avoiding-Apple-Rejection

The key things to focus on are:

  • You need very specific wording in both your purchase page for the subscription, and also within the App details text on the store listing. The latter confused us as Apple kept saying it must be in the iAP description but that can only take a 30 characters! We eventually realised they were referring to the app store listing itself.
  • The purchase page for your subscription MUST include a link to your Privacy Policy and Terms.
  • It’s recommended that you offer a direct way to access the subscription management portal from within your app. The URLs for these are:

        For iOS:

https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/manageSubscriptions

        For Android:

https://play.google.com/store/account/

The wording you need to include against your subscription in the in-app purchase page is as follows. Note that this is just a guide and you may be asked by Apple to add extra details based on your specific subscription or content type.

1. This subscription offers ……………………………….

Make this as descriptive as possible. e.g. if you offer different subscription levels, then mention it.

2. The subscription includes a free trial period of …. which begins as soon as you purchase the subscription. You can cancel your subscription at any time during this period without being charged as long as you do so within 24 hours of the end of trial period.

3. Payment will be charged to iTunes account at confirmation of purchase

4. Your subscription will automatically renew unless auto-renew is turned off at least 24-hour prior to the end of the current period

5. Your account will be charged for renewal within 24-hours prior to the end of the current period, and identify the cost of the renewal

6. Your subscriptions can be managed by the user and auto-renewal may be turned off by going to the user’s Account Settings after purchase.

7. No cancellation of the current subscription is allowed during the active subscription period

8. Privacy Policy link goes here

And there we have it! The above should be all you need to implement support for auto-renewable subscriptions in your Firemonkey Android and iOS app.

9. Terms of Use link goes here.

We hope you found this useful. Happy coding!