Commit Graph
36 Commits
Author SHA1 Message Date
Cesar de la VegaandAndy Boedo 658782b68d Adds subscriptions to CustomerInfo (#4508)
* adds SubscriptionInfo

* fix nullabilities

* purchaseDate is not nullable

* add isActive

* add store

* add the product identifier

* add willRenew

* private extension

* made storeTransactionId nil

* fix tests and docs

* fix tests

* fix more tests

* fix compilation

* fix test

* API tests and other fixes

* Update Sources/Purchasing/NonSubscriptionTransaction.swift

Co-authored-by: Andy Boedo <andresboedo@gmail.com>

* use ProductIdentifier and subscriptionsByProductIdentifier

* fix lint

* disable file_length

---------

Co-authored-by: Andy Boedo <andresboedo@gmail.com>
2024-12-04 12:00:27 +01:00
NachoSoto 2bcd0ce328 5.0.0 changes: support SK2 by default 2024-07-01 14:37:21 -05:00
Josh HoltzandRevenueCat Git Bot a9737aa7fc Add targeting to PresentedOfferingContext (#3730)
### Motivation

Get more context with targeting information 

### Description

- Parse targeting information into `Offerings`
- Add targeting context into `Offerings.current`
- Add targeting context into `getCurrentOffering(forPlacement: String)`
- Post targeting context in post receipts

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2024-02-28 16:10:52 -06:00
61d66bbc32 Add currentOffering(forPlacement: String) to Offerings (#3707)
### Motivation

New function to get `Offering` by a placement identifier

### Description

New `currentOffering(forPlacement: String): Offering?` method on
`Offerings`
- Added demo button for this in purchase tester app

```swift
// Example usage
if let offering = offerings.currentOffering(forPlacement: "onboarding") {
  showPaywall(offering)
}
```

#### Logic flow

- If a placement identifier explicitly exists within the
`placements.offeringIdsByPlacement` dictionary, the method attempts to
fetch the corresponding `Offering` without resorting to a fallback
- Example: when there is a `nil` / null value for a placement, we don't
want to use the fallback
- If the placement identifier does not exist, the method then attempts
to fetch a fallback offering defined by `placements.fallbackOfferingId`

#### New placements object in offerings response

```js
{
    // other offerings stuff
    "placements": {
        "fallback_offering_id": "offering_a", // can be null
        "offering_ids_by_placement": {
            "onboarding_start": null,
            "onboarding_end": "offering_b",
        }
  }
}
```

---------

Co-authored-by: Guido Torres <guido@revenuecat.com>
Co-authored-by: Josh Holtz <me@joshholtz.com>
Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2024-02-28 15:11:48 -06:00
32c63cdb46 [SK2] Add support for StoreKit Config files in SK2 (#3365)
When using StoreKit Config file, we do not have access to the
transaction history or subscription status server-side.

To work around this, we introduce a new `StoreKit2Receipt` type that
closely resembles the structure of an SK1 receipt and contains all the
transaction history and subscription status for the customer. It can be
sent in a single request to `/receipt`

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
Co-authored-by: Distiller <distiller@static.38.39.183.137.cyberlynk.net>
Co-authored-by: Distiller <distiller@static.38.23.40.89.cyberlynk.net>
Co-authored-by: Distiller <distiller@static.38.39.185.65.cyberlynk.net>
Co-authored-by: NachoSoto <NachoSoto@users.noreply.github.com>
2023-12-13 17:00:37 +01:00
NachoSoto e31a531ca1 HTTPClient: test all request headers (#3425)
This allows us to verify exactly what headers are included in all
requests.

It also simplifies the implementation for #3424.
2023-11-17 12:19:49 -08:00
NachoSoto 6317f096cf Paywalls: watchOS support (#3291)
![simulator_screenshot_38A61F03-8048-40E2-AD3E-384DF4112771](https://github.com/RevenueCat/purchases-ios/assets/685609/b74e2c9d-ece1-4f00-920b-7bccb68acd82)

![simulator_screenshot_ADD7F6B5-8A39-473B-85E2-5175027F641C](https://github.com/RevenueCat/purchases-ios/assets/685609/6531d598-b859-4482-a669-34d2eaf5b8f1)
2023-11-16 12:49:53 -08:00
38b4e3b411 Paywalls: add identifier to events (#3332)
### Motivation

Send a unique `id` on each paywall event

### Description

- Added `id: ID?` to `PaywallEvent.Data`
- Optional so its backwards compatible with events recorded before this
change (see actual tests from below)
- Add `withNewID()` function that will mutate the `id` when tracked for
cancel and close

#### Events recored before `id` changes but posted with `id` changes

<img width="433" alt="Screenshot 2023-10-25 at 9 33 27 AM"
src="https://github.com/RevenueCat/purchases-ios/assets/401294/b6c77f0c-7429-4638-a4ba-7d6068c80cb7">

#### Events recorded and posted with `id` changes

<img width="479" alt="Screenshot 2023-10-25 at 9 37 53 AM"
src="https://github.com/RevenueCat/purchases-ios/assets/401294/8cae5329-2f31-4f03-8997-69dcee609e1f">

---------

Co-authored-by: NachoSoto <ignaciosoto90@gmail.com>
Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
Co-authored-by: Distiller <distiller@static.38.39.183.26.cyberlynk.net>
Co-authored-by: Distiller <distiller@static.38.39.184.242.cyberlynk.net>
Co-authored-by: distiller <distiller@static.38.23.41.34.cyberlynk.net>
2023-10-25 20:26:50 -05:00
235a7dcdc1 StoreKit 2: Optionally send JWS tokens instead of receipts to the backend (#3227)
- Added a new option `usesStoreKit2JWS` under `DangerousSettings`. If
enabled, the SDK will send a JWS token instead of a receipt to the
applicable backend endpoints.
- The option must be used in conjunction with `usesStoreKit2IfAvailable`
configuration option.

### ToDo

- [x] Send JWS token when making a purchase in SK2 mode
- [x] Send JWS token when calculating promo offer eligibility
- [x] Update `syncTransactions` to send the latest transaction JWS.
- [x] Add tests

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
Co-authored-by: Distiller <distiller@static.38.39.183.118.cyberlynk.net>
Co-authored-by: Distiller <distiller@static.198.206.135.125.macminivault.com>
Co-authored-by: Distiller <distiller@static.38.23.39.112.cyberlynk.net>
Co-authored-by: Distiller <distiller@static.38.39.183.58.cyberlynk.net>
Co-authored-by: Distiller <distiller@static.38.39.185.87.cyberlynk.net>
2023-10-16 22:45:29 +02:00
NachoSoto cc307399c3 Paywalls: added Purchases.track(paywallEvent:) (#3160)
This uses `PaywallEventsManager` (#3159) to track events, and saves the
presented `PaywallEvent` to be send along with
`PostReceiptDataOperation`.
2023-09-14 18:28:11 -07:00
NachoSoto 56de917d02 Paywalls: removed presentedPaywallViewMode (#3109)
We're going to track this in a different way in the future.
2023-09-14 18:28:11 -07:00
NachoSoto 8ba761a23f Paywalls: send presented PaywallViewMode with purchases (#2859)
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.
2023-09-14 18:28:11 -07:00
NachoSoto 456225ab65 OperationDispatcher: add support for "long" delays (#3168) 2023-09-08 07:28:54 -07:00
NachoSoto 833524314d HTTPClient: extracted HTTPRequestPath protocol (#2986)
This paves the way to add a second set of paths with a separate server
URL to be able to shed requests to offerings and product entitlement
mapping to a separate server.

### Changes:
- New `HTTPRequestPath` with the same properties as `HTTPRequest.Path` +
a new `serverHostURL`
- Moved proxy logic from `SystemInfo`/`HTTPClient` to `HTTPRequestPath`
- Simplified `HTTPRequest` implementation
2023-08-10 15:23:13 -07:00
NachoSoto 79aa55fc16 SystemInfo.init no longer throws (#2803)
Not sure when we stopped throwing errors, but we no longer do, which
simplifies code a lot.
2023-07-13 08:24:51 -07:00
NachoSoto f7e36fb993 Trusted Entitlements: add support for signing POST body (#2753)
### Changes:
- `HTTPClient` has a new `X-Post-Params-Hash` request header
- Replaced `HTTPRequest.Method.post`'s `Encodable` value with a more
specific `HTTPRequestBody` (like `HTTPResponseBody`)
- `HTTPRequestBody` allows overriding `contentForSignature` (it defaults
to `[]`) which then `Signing` uses for the hash
- Fixed `LogInOperation` not passing the `VerificationResult` to the
result `CustomerInfo`. This is captured in unit and integration tests
now.
- Add support for signing `POST` requests in `Path.logIn` and
`Path.postReceiptData`

Depends on https://github.com/RevenueCat/khepri/pull/6246
2023-07-13 07:45:16 -07:00
NachoSoto dd01d499e0 Tests: unified default timeouts (#2801) 2023-07-13 06:06:20 -07:00
NachoSoto 01ca7ae635 PostReceiptDataOperation: add new testReceiptIdentifier parameter (#2749) 2023-07-05 10:37:43 -07:00
NachoSoto 4b2138367b Refactored TransactionPoster: removed 2 dependencies and abstracted parameters (#2542)
Follow up to #2540.

This was necessary to ensure that we can implement #2533 without
reference cycles.
This was the hierarchy before this change:

![IMG_B25ECE86C2F9-1](https://github.com/RevenueCat/purchases-ios/assets/685609/70e1d939-8fa5-424c-8673-bb519f386118)

The red arrows are what this PR removes.

## Changes:
- `TransactionPoster` no longer has references to `IdentityManager` and
`Attribution`
- `markSyncedIfNeeded` is no longer in `TransactionPoster`, moved back
to `PurchasesOrchestrator`
- Changed `TransactionPoster`'s callback to return `Result<CustomerInfo,
BackendError>`, providing greater flexibility for users to be able to
read the specific errors.
- Extracted `PurchasedTransactionData` to be reduce the number of
parameters passed around. This removed the need for 2
`swiftlint:disable:next function_parameter_count`. This is the majority
of this diff. It was helpful to combine in this PR because I needed to
add another parameter to the flow: `unsyncedAttributes`, since
`TransactionPoster` could no longer read these directly.
2023-05-30 12:16:24 -07:00
NachoSoto 456b96bf59 Backend.ResponseHandler is now @Sendable (#2541)
This was necessary for a follow-up refactor to #2540. The main change is
in `Backend`, the rest are test changes that are required now that the
closure is `@Sendable`.
2023-05-26 15:29:34 -07:00
NachoSoto edc0f6b707 Offline Entitlements: don't compute offline CustomerInfo when purchasing a consumable products (#2522)
This will be logged when doing so:
```
ERROR: 😿 ❗❗ Error computing offline CustomerInfo. Will return original error.
Creation error: Unable to compute offline CustomerInfo when purchasing consumable products.
```

### Changes:
- Added unit tests for `PostReceiptDataOperation`
- Added integration test for this new scenario
- `PostReceiptDataOperation` won't use `OfflineCustomerInfoCreator` when
purchasing consumable products
2023-05-24 12:33:45 -07:00
NachoSoto db912a54ce Update SwiftSnapshotTesting (#2453)
This includes [this
fix](https://github.com/pointfreeco/swift-snapshot-testing/pull/585)
which should solve some of the flaky test failures we've been seeing
lately, which made test retries also fail.

We couldn't update to 1.10.0 because it dropped support for iOS 12.0,
but that was fixed in
https://github.com/pointfreeco/swift-snapshot-testing/pull/698

This also reverts #2426, since that's no longer required now that
retries should work properly.
2023-04-26 12:25:13 -07:00
Andy BoedoandNachoSoto 618ff121d2 Custom Entitlements Computation mode (#2439)
### Changes:

- Added `Purchases.configureInCustomEntitlementsComputationMode`
- Added `Purchases.switchUser(to:)`
- Disabled parts of the SDK in this new mode
- New example app for testing `customEntitlementsComputation` mode

---------

Co-authored-by: NachoSoto <ignaciosoto90@gmail.com>
2023-04-25 13:21:46 -07:00
NachoSoto f4a68881df BackendPostReceiptDataTests: increased timeout to fix flaky test (#2426) 2023-04-21 12:10:14 -07:00
NachoSoto 7b3b03d2b3 Xcode 14.3: fixed compilation errors (#2399)
See also #2397.
Xcode 14.3 introduced the following error:
> Heterogeneous collection literal could only be inferred to '[String :
Any]'; add explicit type annotation if this is intentional

### Changes:
- Added explicit types to fix this new error
- Removed unnecessary `@preconcurrency` imports
- Added new `CustomerInfo.emptyInfo` to reduce duplication of same fake
`CustomerInfo` creation
2023-04-11 08:55:21 -07:00
NachoSoto e68a31b206 CustomerInfo: removed entitlementVerification (#2320)
See conversation in
https://linear.app/revenuecat/issue/SDK-2842/[android]-create-trusted-property-in-entitlementinfo
This was redundant, it makes more sense to access this from
`EntitlementInfos`.
2023-03-03 09:58:33 -08:00
NachoSoto 84eed758c1 Introduced Configuration.EntitlementVerificationMode and VerificationResult (#2277)
Fixes [CSDK-629].
Depends on #2274 and #2267.

Entitlement verification is accomplished by preventing MiTM attacks
between the SDK and the RevenueCat server.
With verification enabled, the SDK ensures that the response created by
the server was not modified by a third-party, and the entitlements
received are exactly what was sent.

Entitlements are only verified if enabled using
`Configuration.Builder.with(entitlementVerificationMode:)`, which is
disabled by default.

### Changes:
- Added new `VerificationResult`, which replaces
`HTTPResponseVerificationResult`
- Renamed `Configuration.EntitlementVerificationLevel` to
`Configuration.EntitlementVerificationMode`
- `Configuration.with(entitlementVerificationMode:)` is now `public`
- Added `CustomerInfo.entitlementVerification`
- Added `EntitlementInfos.verification` and
`EntitlementInfo.verification`
- Added tests to cover serialization of these new values
- `CustomerInfoResponseHandler` copies the `ValidationResult` to
`CustomerInfo` (all operations that fetch `CustomerInfo` use this)
- Renamed "validation" to "verification" everywhere for consistency
- Finalized documentation

### TODO:
- [x] Figure out whether to use a separate type from
`HTTPResponseValidationResult` or rename that one
- [x] Figure out final API type and property names
- [x] Add tests for `CustomerInfo.copy(with:)`
- [x] Ensure validation result is encoded and decoded (for caching)
- [x] Add missing snapshots

[CSDK-629]:
https://revenuecats.atlassian.net/browse/CSDK-629?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
2023-02-17 16:49:21 -08:00
NachoSoto dd60d6c012 Tests: replaced toEventually with new waitUntilValue to simplify tests (#2071)
Example:
```diff
-        var result: Result<Offerings, OfferingsManager.Error>?
-        offeringsManager.offerings(appUserID: MockData.anyAppUserID) {
-            result = $0
+        let result = waitUntilValue { completed in
+            self.offeringsManager.offerings(appUserID: MockData.anyAppUserID) {
+                completed($0)
+            }
         }
-        expect(result).toEventuallyNot(beNil())
```

This removes the need to _poll_ for when the value is returned, and
instead it gets detected immediately, potentially providing a
significant boost in test execution speed.

I've also used `Nimble`'s own `waitUntil` for cases where we don't need
to return a value.

 #### `toEventually` usage:
- Before this PR: 353
- After: 229

There's still a lot of legitimate usage of `toEventually`, but I'm sure
I missed other places where this can also simplify the code. This is a
good start for now.
2022-11-28 08:47:08 -08:00
NachoSoto 46d9366fa4 PostReceiptDataOperation: added initiationSource parameter (#1957)
For [TRIAGE-82].

[TRIAGE-82]:
https://revenuecats.atlassian.net/browse/TRIAGE-82?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
2022-10-07 08:21:30 -07:00
NachoSoto 43d474d813 GetCustomerInfoAPI: avoid making a request if there's any PostReceiptDataOperation in progress (#1911)
Fixes [CSDK-419].

This is an improvement over the fix in #1292. In there, we avoided
appending on an existing `CustomerInfoOperation` if there were any
`PostReceiptDataOperation`s in progress, because those might come back
with outdated entitlements.
This fix removes that cache key hack, and instead *reuses* the entire
response to that `PostReceiptDataOperation` by "stealing" that request's
cache key.

This is perfectly captured by the existing test
`BackendPostReceiptDataTests.testGetsUpdatedSubscriberInfoAfterPost`,
added in #1292. Amazingly enough, that test still passes with one minor
change: the entire process requires one fewer API call 🎉 🐼

[CSDK-419]:
https://revenuecats.atlassian.net/browse/CSDK-419?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
2022-09-21 13:34:43 -07:00
NachoSoto 4f8589a30a Backend: fixed potential race conditions introduced by OperationDispatcher.dispatchOnWorkerThread(withRandomDelay:) (#1827)
Fixes [CSDK-391]. As described in that ticket, calling a method that introduces a random delay before performing an API request could lead to a race condition. Example:

> Request 1: delay 0 seconds. Start now.
> Request 2: delay 2 seconds. Waiting…
> Request 1 finishes.
> Request 2: 2 seconds past. There is no in progress request, so we start it again

This also solves [CSDK-394]. If any part of our code (or users) call a method that would enqueue a request multiple times, we need to insert it into the callback queue right away.
That's what this does: it moves the random delay to *after* the callback has been added to the `CallbackCache`.

[CSDK-391]: https://revenuecats.atlassian.net/browse/CSDK-391?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
[CSDK-394]: https://revenuecats.atlassian.net/browse/CSDK-394?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
2022-08-16 09:29:36 -07:00
NachoSoto 5e8251e933 BackendPostReceiptDataTests: added new test with ProductRequestData (#1662)
Looking into [SDKONCALL-19], realized that there's no test that explicitly checks the `ProductRequestData` is sent along with the receipt data.
2022-06-09 11:04:47 -07:00
NachoSoto d75d580952 Backend snapshot tests: separate snapshot for each major version (#1504)
Fixes [CF-547].

This also combines the duplicate copies of some tests for each version, as only 1 is needed now. `assertSnapshot` encodes the version in the filename.
Combined:
- `BackendPostRecepitDataTests`
- `BackendSubscriberAttributesTests`

No more unnecessary skipped tests.
- Before: `Number of tests skipped | 112`
- Now: `Number of tests skipped | 4`

### Example:
<img width="447" alt="Screen Shot 2022-04-13 at 16 07 15" src="https://user-images.githubusercontent.com/685609/163261646-4590f774-3ef7-43f4-a3c2-765f51ca194c.png">

[CF-547]: https://revenuecats.atlassian.net/browse/CF-547?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
2022-04-14 14:31:45 +02:00
Joshua Liebowitz 92a8004b04 Fix iOS12/13 tests for attConsentStatus availibility (#1423)
* Create < iOS 13 and >= iOS 14 tests for attribute tests and receipt tests

Fixes [CF-457]
attConsentStatus is not available on < iOS 14, so we needed to create specific test cases for each range of platforms that support/don't support.

* Update BackendPostReceiptDataTests json for < iOS13 and >= iOS14
* Update BackendSubscriberAttributesTests json for < iOS13 and >= iOS14

🙃
2022-03-31 15:17:09 -07:00
NachoSoto 4bbc9ef9cd StoreProductDiscount: added missing numberOfPeriods property (#1428)
Fixes [CF-448] and #1418.
2022-03-30 10:26:48 -07:00
aboedo d1ddd6bf9c Clean up tests folders (#1402)
* moved test suites to Tests folder

* fixed outdated path

* fixed more outdated paths

* moved TestsPlans to Tests folder

* update path to Constants.swift
2022-03-21 10:26:00 -03:00