## tl;dr
PaywallView has a new constructor that takes `performPurchase` and
`performRestore` blocks, which are called to preform purchasing/restore
directly by the customer's app when the purchase/restore buttons are
tapped on the paywall. This makes it possible to use RC Paywalls when
`Purchases` has been configured `.with(purchasesAreCompletedBy:
.myApp)`.
Example usage:
```swift
PaywallView(performPurchase: {
var userCancelled = false
var error: Error?
// use StoreKit to perform purchase
return (userCancelled: userCancelled, error: error)
}, performRestore: {
var success = false
var error: Error?
// use StoreKit to perform restore
return (success: success, error: error)
})
```
## Description
When a `PaywallView` is constructed, a new `PurchaseHandler` is created.
The `PurchaseHandler` (an internal RevenueCatUI class) is owned by the
`PaywallView`, and it is responsible for executing new purchases and
restores.
When a `PaywallView` is constructed **without** `performPurchase` and
`performRestore` blocks, the `PaywallView` creates a `PurchaseHandler`
capable of preforming purchases using RevenueCat. When a `PaywallView`
is constructed with `performPurchase` and `performRestore` blocks, it
can also make purchases using the customer-supplied closures.
The `PurchaseHandler` is invoked when the user taps the
`PurchaseButton`, calling `purchaseHandler.purchase(package:
self.selectedPackage.content)`, which branches to either the internal or
external purchase code, as defined by `purchasesAreCompletedBy`:
```swift
@MainActor
func purchase(package: Package) async throws {
switch self.purchases.purchasesAreCompletedBy {
case .revenueCat:
try await performPurchase(package: package)
case .myApp:
try await performExternalPurchaseLogic(package: package)
}
}
```
Purchase and Restore blocks can also be assigned for paywall footers:
```swift
MyAppDefinedPaywall()
.paywallFooter(myAppPurchaseLogic: MyAppPurchaseLogic(performPurchase: { packageToPurchase in
var userCancelled = false
var error: Error?
// use StoreKit to perform purchase
return (userCancelled: userCancelled, error: error)
}, performRestore: {
var success = false
var error: Error?
// use StoreKit to perform restore
return (success: success, error: error)
}))
```
and via `.presentPaywallIfNeeded`:
```swift
MyAppDefinedPaywal()
.presentPaywallIfNeeded(requiredEntitlementIdentifier: "test",
myAppPurchaseLogic: MyAppPurchaseLogic(performPurchase: {
packageToPurchase in
return (userCancelled: false, error: nil)
}, performRestore: {
return (success: true, error: nil)
}))
```
## Notes
### Testing
A lot needs to be mocked, the purchase/restore blocks that are passed in need to be assigned directly to the `PurchaseHandler`, which is then passed in as part of a `PaywallConfiguration`, both of which are normally constructed internally in the PaywallView constructor.
```swift
func testHandleExternalRestoreWithPurchaaseHandlers() throws {
var completed = false
var customRestoreCodeExecuted = false
let purchasHandler = Self.externalPurchaseHandler { _ in
return (userCancelled: true, error: nil)
} performRestore: {
customRestoreCodeExecuted = true
return (success: true, error: nil)
}
let config = PaywallViewConfiguration(purchaseHandler: purchasHandler)
try PaywallView(configuration: config).addToHierarchy()
Task {
_ = try await purchasHandler.restorePurchases()
completed = true
}
expect(completed).toEventually(beTrue())
expect(customRestoreCodeExecuted) == true
}
```
### Error Handling
For the external code blocks to be called, `purchasesAreCompletedBy` needs to be set to `.myApp` AND the blocks need to be defined. So we need to handle cases when these are not consistent:
1. If someone configures purchasesAreCompletedBy to `.myApp`, and then displays a PaywallView **without** purchase/restore handlers, the SDK will:
* Log an error when the PaywallView is constructed
* When the PaywallView is displayed, replace it with a big red banner when in debug mode, fatalError() in release mode.
* If you purchase directly via the purchase handler (which is an internal class but this is done for testing), it will throw.
2. If someone configures purchases to use `.revenueCat`, and then displays a PaywallView **with** purchase/restore handler, the SDK will:
* Log a warning when the PaywallView is constructed
Rationale:
In case 1, there could be no (acceptable) way to make a purchase, so this is very bad and it needs to be dealt with.
In case 2, they've over-specified the paywall, and while this might be confusing (why isn't my code being called??), it's not as problematic, and we want to make it easy for people to switch from using their purchase logic to our purchase logic.
These checks are made in PaywallView.swift, method `checkForConfigurationConsitency()`.
### UIKit
Not yet supported, will add in a follow-up PR, unlikely to be complicated.
### Paywall Footer and Paywall If Needed
The `performPurchase` and `performRestore` parameters for the paywall footer are contained in a struct rather than as loose parameters of closure types, because doing the latter would create a very poor experience with regards to code completion, where Xcode will always offer complete your code as a trailing closure, but will always use the first closure where the function signature matches.
The following illustrates the problem of using loose closure parameters:
The trailing closure that Xcode auto-creates here does _not_ get called for `performPurchase`, but rather `purchaseStarted`, because it also has a `package` as its input parameter, and comes first in the parameter list 😱.
https://github.com/RevenueCat/purchases-ios/assets/109382862/1f809e7c-b661-4844-89e3-fd846a029531
This is the problematic function signature:
```swift
public func paywallFooter(
offering: Offering,
condensed: Bool = false,
fonts: PaywallFontProvider = DefaultPaywallFontProvider(),
purchaseStarted: PurchaseOfPackageStartedHandler? = nil,
purchaseCompleted: PurchaseOrRestoreCompletedHandler? = nil,
purchaseCancelled: PurchaseCancelledHandler? = nil,
restoreStarted: RestoreStartedHandler? = nil,
restoreCompleted: PurchaseOrRestoreCompletedHandler? = nil,
purchaseFailure: PurchaseFailureHandler? = nil,
restoreFailure: PurchaseFailureHandler? = nil,
performPurchase: PerformPurchase? = nil,
performRestore: PerformRestore? = nil
) -> some View
```
To fix this, get rid of the two new parameters:
```swift
performPurchase: PerformPurchase? = nil,
performRestore: PerformRestore? = nil
```
and embed them in a struct:
```swift
public struct MyAppPurchaseLogic {
public let performPurchase: PerformPurchase
public let performRestore: PerformRestore
public init(performPurchase: @escaping PerformPurchase, performRestore: @escaping PerformRestore) {
self.performPurchase = performPurchase
self.performRestore = performRestore
}
}
```
which we use as a last parameter:
```swift
myAppPurchaseLogic: MyAppPurchaseLogic? = nil
```
Now the code completes as so:
https://github.com/RevenueCat/purchases-ios/assets/109382862/332ac42d-ccba-42bc-bfc3-702d7870c99c
The `MyAppPurchaseLogic` doesn't complete in perfectly, but once you
initialize one of those it goes nicely the rest of the way, including
the error messages that instruct you on what you need to return.
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Josh Holtz <me@joshholtz.com>
Co-authored-by: Cesar de la Vega <cesarvegaro@gmail.com>
Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
Co-authored-by: Toni Rico <toni.rico.diez@revenuecat.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Will Taylor <wtaylor151@gmail.com>
Co-authored-by: Andy Boedo <andresboedo@gmail.com>
This PR adds:
* `purchasesAreCompletedBy`
which replaces and deprecates public instances of:
* `observerMode`
* `finishTransactions`
Internal references to the above will be removed in a subsequent PR.
---------
Co-authored-by: Cesar de la Vega <cesarvegaro@gmail.com>
The paywalls examples weren't showing up when compiled in release mode.
Enabling it meant making a bunch of more internal things public via the
preprocessing script. `TestData` is no longer `#ifdef DEBUG`ed out, but
most of its data is still `#ifdef DEBUG`, and when it's compiled with an
`internal` modifier and thus nothing uses it, I'd expect what remains to
be stripped away during linking.
This PR allows the Paywalls Tester app to access some items internal to
purchases-ios by temporarily marking them public during complication.
Items that need to be public have been annotated with
`\\@PublicForExternalTesting`.
The Paywalls Tester project runs a script, Preprocessor.sh, as a
pre-action to add `public` to all classes/structs/enums/functions/inits
that have been annotated.
After compilation it runs a second script, Postprocessor.sh, as a
post-action to undo these changes so that they don't accidentally get
checked in.
The first script is run as a scheme pre-action rather than as a run
script build phase, because when run as a build phase the changes to the
files aren't picked up until the next compilation attempt.
<img width="669" alt="image"
src="https://github.com/RevenueCat/purchases-ios/assets/109382862/0b0bacdb-79de-441d-8d61-2a5dd03b1b53">
It also changes the archive step to be built with a release
configuration, and removes the use of `@testable import` for debug
builds.
resolves PWL-459
Similar to #3627.
This API is available in:
- `PaywallView()`
- `.presentPaywallIfNeeded`
- `.paywallFooter`
- `PaywallViewControllerDelegate`
---------
Co-authored-by: Mark Villacampa <m@markvillacampa.com>
### Motivation
Prevent `paywall_impression` and `paywall_close` be recorded multiple
times for the same session (which could happen if same `PaywallView` is
displayed multiple times)
### Description
- `PaywallView`'s `onAppear` will always create/update the session
- `PurchaseHandler`
- `trackPaywallImpression()` will store the `PaywallEvent.Data` for
cancel and close to use
- `trackPaywallClose()` will set `eventData` to `nil` so that close can
only be called once
---------
Co-authored-by: NachoSoto <ignaciosoto90@gmail.com>
Co-authored-by: NachoSoto <NachoSoto@users.noreply.github.com>
This was breaking event notifications as well as
`OnPurchaseCompletedModifier`, because there were multiple
`PurchaseHandler` instances created.
The solution is to make `PaywallView` store these as `@StateObject`. In
order to do that, the type can't be optional, so I instead encoded the
"is configured" information inside.
I've moved `PaywallViewMode` from `RevenueCatUI` to `RevenueCat`. This
uses the same approach as #2645. This method is `public` so it can be
used from `RevenueCatUI`, but the documentation stays its purpose.
The behavior is covered with integration tests and a snapshot test.
Depends on https://github.com/RevenueCat/khepri/pull/6364.
`PaywallView` and `PaywallViewController` (along with the extensions)
still require iOS 16, but this paves the way to support iOS 15 down the
road if we need to.
### Main Changes:
- Changed all `@available` annotations
- Added CI tests
- Replaced `ViewThatFits` with the "biggest" version
- Because of that, `scrollableIfNeeded` is always scrollable
- Double `Regex` implementation (keeping the modern one), so once we
drop support for iOS 15 we can just keep the modern one.
### TODO:
- [x] Add snapshots
- [x] Test paywalls
- [x] Updated APITester to verify this
Follow up to #2930.
Added `PresentIfNecessaryTests` and `PurchaseHandlerTests`.
This also removes the last source of "crashes" whenever `Purchases`
isn't configured, leading to errors instead.
This allows users to present a `PaywallView` and be notified of
purchasing events. Example:
```swift
VStack {
YourViews()
if !self.didPurchase {
PaywallView()
}
}
.onPurchaseCompleted { customerInfo in
print("Purchase completed: \(customerInfo.entitlements)")
self.didPurchase = true
}
```
Additionally, an explicit optional closure is added to
`.presentPaywallIfNecessary`:
```swift
YourApp()
.presentPaywallIfNecessary {
!$0.entitlements.active.keys.contains("entitlement_identifier")
} purchaseCompleted: { customerInfo in
print("Customer info unlocked entitlement: \(customerInfo.entitlements)")
}
```
These are now tested through new unit tests.
This allows `PaywallView` to handle state handling during a purchase:
instead of the previous behavior where only `PurchaseButton` would
disable itself, now the entire `PaywallView` is disabled.
I extracted `PackageButtonStyle` so any template with multi-package
selection can get this same behavior: the package selection also becomes
disabled, as well as any other button (like restore purchases).
I've also cleaned up the templates since we no longer needed the
"Content" inside view, and they can be simplified with a single type.
By making `PurchaseHandler` `@MainActor` we also ensure that all these
state transitions lead to UI changes happening exclusively on the main
thread.
Another small refactor, follow up to #2837.
Slowly taking implementation details from `Example1Template` to make it
easier to implement more templates.
This adds a new `PurchaseHandler` type, which can be instantiated with
`Purchases` or with a mock implementation for previews. That gets
injected, and templates can now purchase and dismiss themselves.
I've improved the `SimpleApp` setup to better work with the lifetime of
purchases. Now it only displays the paywall if the user doesn't have an
entitlement.
I've also added some basic error handling to the new `AsyncButton`:
