@smbcloud / smbcloud-ascapi Mirror · read-only / commits / dc0d84b
Fork 0

Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.

Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git

Synced Nov 25, 09:15 UTC

Add in-app purchase commands

New crate smbcloud-ascapi-iap covers the v2 inAppPurchases resource: the product, its localizations, the price schedule, territory availability and the App Review screenshot. The CLI gets an `in-app-purchases` command with list, get, create, update, localize, price-points, set-price, set-availability and review-screenshot. Every write honours --dry-run and reads the result back. set-price matches the customer price string exactly against the territory's price points. Subscriptions and submission are not covered; the first in-app purchase of an app is submitted with an app version. The release workflow publishes the new crate before the CLI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Nov 4, 2026 at 16:57 UTC dc0d84b70da82cf5d2ebb396ba06e5e9c73f1f1b
14 files changed +1754 -3
.agents/AGENTS.md
+37 -2
@@ -17,7 +17,7 @@ for the full crate table.
17
18 ## Workspace layout
19
20 -Domain crates (`aso`, `pricing`, `signing`, `reports`) know nothing about each
20 +Domain crates (`aso`, `pricing`, `iap`, `signing`, `reports`) know nothing about each
21 other or the front ends. Each extends `smbcloud_ascapi_core::Client` with an
22 **extension trait** (Rust only allows inherent impls in the crate that owns the
23 type). Import a domain's `prelude::*` to pull its traits in at once.
@@ -74,6 +74,41 @@ stale `AuthKey_<id>.p8` and fail with a 401, and `--auth-string` would put
74 the key in the process table. Upload is CLI-only, because a tool call that
75 blocks for minutes and publishes a build doesn't belong in MCP.
76
77 +## In-app purchases (CLI)
78 +
79 +One-time products (the v2 `inAppPurchases` resource) through `crates/iap`.
80 +Subscriptions are not covered. A product is ready to submit once it has a
81 +localization, a price, territories and a review screenshot:
82 +
83 +```sh
84 +asc in-app-purchases list <APP_ID>
85 +asc in-app-purchases get <IAP_ID> # product, localizations, manual price, territories, screenshot
86 +asc in-app-purchases create <APP_ID> --product-id onde.unlock --name Onde --type non-consumable \
87 + [--family-sharable] [--review-note-file note.txt]
88 +asc in-app-purchases update <IAP_ID> [--name …] [--review-note-file …]
89 +asc in-app-purchases localize <IAP_ID> --locale en-US --name "Unlock Onde" --description "Unlimited answers, paid once"
90 +asc in-app-purchases price-points <IAP_ID> [--territory USA]
91 +asc in-app-purchases set-price <IAP_ID> --price 4.99 [--territory USA]
92 +asc in-app-purchases set-availability <IAP_ID> (--all-territories | --territory SWE …) [--no-new-territories]
93 +asc in-app-purchases review-screenshot <IAP_ID> paywall.png [--replace]
94 +```
95 +
96 +- Every write honours the global `--dry-run` and reads the result back,
97 + exiting nonzero when it does not match.
98 +- The product id is permanent: Apple never lets this account reuse it, even
99 + after deletion. `create` refuses an id the app already has.
100 +- Family Sharing can be turned on later but never off, so `create` leaves it
101 + off unless `--family-sharable` is given, and `update` cannot change it.
102 +- `set-price` matches the customer price string exactly ("4.99") against the
103 + territory's price points and posts a schedule with that one manual price;
104 + Apple derives the other storefronts. The inline price uses the local id
105 + `${price1}`, as Apple documents.
106 +- There is no submit command. An app's first in-app purchase is reviewed with
107 + an app version and is attached on the version page in App Store Connect.
108 +- A freshly created product can answer one read with a 401 for a few seconds.
109 + Rerunning the same command is safe: every write is idempotent.
110 +- No MCP tools yet, like `pricing`.
111 +
112 ## AppGallery (CLI)
113
114 `asc appgallery` covers the Android Publishing API through `crates/appgallery`
@@ -161,7 +196,7 @@ merged since.
196
197 ## Architecture notes
198
164 -- Layering is `core` → `aso`/`pricing`/`signing`/`reports` → `frontend` →
199 +- Layering is `core` → `aso`/`pricing`/`iap`/`signing`/`reports` → `frontend` →
200 `mcp` / `cli`. Don't add a dependency that points up or sideways; CI checks
201 the lower crates build alone.
202 - The MCP tool set is declared by the `ascapi_mcp_tools!` macro
.github/workflows/release-crates.yml
+2 -1
@@ -92,7 +92,7 @@ jobs:
92 - name: Check the lower crates build alone
93 shell: bash
94 run: |
95 - for crate in core aso pricing signing reports play appgallery msstore; do
95 + for crate in core aso pricing iap signing reports play appgallery msstore; do
96 cargo check -p "smbcloud-ascapi-${crate}" --locked
97 done
98
@@ -142,6 +142,7 @@ jobs:
142 core
143 aso
144 pricing
145 + iap
146 signing
147 reports
148 play
Cargo.lock
+13
@@ -1796,6 +1796,7 @@ dependencies = [
1796 "smbcloud-ascapi-aso",
1797 "smbcloud-ascapi-core",
1798 "smbcloud-ascapi-frontend",
1799 + "smbcloud-ascapi-iap",
1800 "smbcloud-ascapi-mcp",
1801 "smbcloud-ascapi-msstore",
1802 "smbcloud-ascapi-play",
@@ -1834,6 +1835,18 @@ dependencies = [
1835 "tokio",
1836 ]
1837
1838 +[[package]]
1839 +name = "smbcloud-ascapi-iap"
1840 +version = "0.3.0"
1841 +dependencies = [
1842 + "async-trait",
1843 + "md5",
1844 + "reqwest",
1845 + "serde",
1846 + "serde_json",
1847 + "smbcloud-ascapi-core",
1848 +]
1849 +
1850 [[package]]
1851 name = "smbcloud-ascapi-mcp"
1852 version = "0.3.0"
Cargo.toml
+2
@@ -8,6 +8,7 @@ members = [
8 "crates/msstore",
9 "crates/signing",
10 "crates/pricing",
11 + "crates/iap",
12 "crates/reports",
13 "crates/frontend",
14 "crates/mcp",
@@ -29,6 +30,7 @@ smbcloud-ascapi-appgallery = { version = "0.3.0", path = "crates/appgallery" }
30 smbcloud-ascapi-msstore = { version = "0.3.0", path = "crates/msstore" }
31 smbcloud-ascapi-signing = { version = "0.3.0", path = "crates/signing" }
32 smbcloud-ascapi-pricing = { version = "0.3.0", path = "crates/pricing" }
33 +smbcloud-ascapi-iap = { version = "0.3.0", path = "crates/iap" }
34 smbcloud-ascapi-reports = { version = "0.3.0", path = "crates/reports" }
35 smbcloud-ascapi-frontend = { version = "0.3.0", path = "crates/frontend" }
36 smbcloud-ascapi-mcp = { version = "0.3.0", path = "crates/mcp" }
crates/cli/Cargo.toml
+1
@@ -26,6 +26,7 @@ smbcloud-ascapi-appgallery = { workspace = true }
26 smbcloud-ascapi-msstore = { workspace = true }
27 smbcloud-ascapi-play = { workspace = true }
28 smbcloud-ascapi-pricing = { workspace = true }
29 +smbcloud-ascapi-iap = { workspace = true }
30 smbcloud-ascapi-signing = { workspace = true }
31 smbcloud-ascapi-reports = { workspace = true }
32 smbcloud-ascapi-frontend = { workspace = true }
crates/cli/src/main.rs
+431
@@ -34,6 +34,11 @@ use smbcloud_ascapi_frontend::await_processing::{
34 use smbcloud_ascapi_frontend::release_controls;
35 use smbcloud_ascapi_frontend::review;
36 use smbcloud_ascapi_frontend::upload::{self, upload_package, validate_app, AltoolAuth, AltoolOp};
37 +use smbcloud_ascapi_iap::in_app_purchase::{
38 + InAppPurchaseCreateAttributes, InAppPurchaseType, InAppPurchaseUpdateAttributes,
39 +};
40 +use smbcloud_ascapi_iap::localization::LocalizationUpdate;
41 +use smbcloud_ascapi_iap::prelude::*;
42 use smbcloud_ascapi_msstore::ListingFields as MsStoreListingFields;
43 use smbcloud_ascapi_play::{ImageType as PlayImageType, ListingFields as PlayListingFields};
44 use smbcloud_ascapi_pricing::app_price::PriceKind;
@@ -815,6 +820,13 @@ enum Command {
820 #[command(subcommand)]
821 command: AppPricesCommand,
822 },
823 + /// In-app purchases (one-time products, not subscriptions): create
824 + /// one, localize it, price it, choose its territories and upload the
825 + /// App Review screenshot.
826 + InAppPurchases {
827 + #[command(subcommand)]
828 + command: InAppPurchasesCommand,
829 + },
830 /// Signing certificates: list what the team holds, issue a new one, or
831 /// revoke an old one.
832 Certificates {
@@ -1830,6 +1842,119 @@ enum AppPricesCommand {
1842 },
1843 }
1844
1845 +#[derive(Clone, Copy, ValueEnum)]
1846 +enum CliInAppPurchaseType {
1847 + Consumable,
1848 + NonConsumable,
1849 + NonRenewingSubscription,
1850 +}
1851 +
1852 +impl From<CliInAppPurchaseType> for InAppPurchaseType {
1853 + fn from(value: CliInAppPurchaseType) -> Self {
1854 + match value {
1855 + CliInAppPurchaseType::Consumable => InAppPurchaseType::Consumable,
1856 + CliInAppPurchaseType::NonConsumable => InAppPurchaseType::NonConsumable,
1857 + CliInAppPurchaseType::NonRenewingSubscription => {
1858 + InAppPurchaseType::NonRenewingSubscription
1859 + }
1860 + }
1861 + }
1862 +}
1863 +
1864 +#[derive(Subcommand)]
1865 +enum InAppPurchasesCommand {
1866 + /// Every in-app purchase of an app, with its state.
1867 + List { app_id: String },
1868 + /// One product with everything that decides whether it can be
1869 + /// submitted: localizations, manual price, territories, screenshot.
1870 + Get { id: String },
1871 + /// Create a product. The product id is permanent and can never be
1872 + /// reused by this account, even after the product is deleted.
1873 + Create {
1874 + app_id: String,
1875 + /// The id the app asks the store for, e.g. `onde.unlock`.
1876 + #[arg(long)]
1877 + product_id: String,
1878 + /// Reference name, seen only in App Store Connect (max 64).
1879 + #[arg(long)]
1880 + name: String,
1881 + #[arg(long, value_enum)]
1882 + r#type: CliInAppPurchaseType,
1883 + /// Let Family Sharing members use the purchase. Can only be
1884 + /// turned on later, never off, so it is off unless given.
1885 + #[arg(long)]
1886 + family_sharable: bool,
1887 + #[arg(long, conflicts_with = "review_note_file")]
1888 + review_note: Option<String>,
1889 + #[arg(long)]
1890 + review_note_file: Option<PathBuf>,
1891 + },
1892 + /// Change the reference name or the review note.
1893 + Update {
1894 + id: String,
1895 + #[arg(long)]
1896 + name: Option<String>,
1897 + #[arg(long, conflicts_with = "review_note_file")]
1898 + review_note: Option<String>,
1899 + #[arg(long)]
1900 + review_note_file: Option<PathBuf>,
1901 + },
1902 + /// Set the display name and description for one locale, creating the
1903 + /// localization or updating the one that exists.
1904 + Localize {
1905 + id: String,
1906 + /// e.g. `en-US`.
1907 + #[arg(long)]
1908 + locale: String,
1909 + /// Display name on the purchase sheet (max 30).
1910 + #[arg(long)]
1911 + name: String,
1912 + /// Description on the purchase sheet (max 45).
1913 + #[arg(long)]
1914 + description: Option<String>,
1915 + },
1916 + /// The price points Apple offers in a territory.
1917 + PricePoints {
1918 + id: String,
1919 + #[arg(long, default_value = "USA")]
1920 + territory: String,
1921 + },
1922 + /// Set one manual price in a base territory; Apple derives the rest.
1923 + SetPrice {
1924 + id: String,
1925 + #[arg(long, default_value = "USA")]
1926 + territory: String,
1927 + /// The customer price exactly as Apple writes it, e.g. `4.99`.
1928 + #[arg(long)]
1929 + price: String,
1930 + },
1931 + /// Choose the storefronts the product is sold in. Replaces the set.
1932 + SetAvailability {
1933 + id: String,
1934 + /// Every storefront App Store Connect lists.
1935 + #[arg(
1936 + long,
1937 + conflicts_with = "territory",
1938 + required_unless_present = "territory"
1939 + )]
1940 + all_territories: bool,
1941 + /// One storefront code; repeat for more.
1942 + #[arg(long)]
1943 + territory: Vec<String>,
1944 + /// Don't add storefronts Apple opens later.
1945 + #[arg(long)]
1946 + no_new_territories: bool,
1947 + },
1948 + /// Upload the screenshot App Review asks for (the purchase as it
1949 + /// appears in the app). Replaces an existing one only with --replace.
1950 + ReviewScreenshot {
1951 + id: String,
1952 + path: PathBuf,
1953 + #[arg(long)]
1954 + replace: bool,
1955 + },
1956 +}
1957 +
1958 #[derive(Subcommand)]
1959 enum AppsCommand {
1960 /// `GET /v1/apps`.
@@ -2645,6 +2770,9 @@ async fn main() -> Result<()> {
2770 run_app_screenshots(&client, command, cli.dry_run).await
2771 }
2772 Command::AppPrices { command } => run_app_prices(&client, command).await,
2773 + Command::InAppPurchases { command } => {
2774 + run_in_app_purchases(&client, command, cli.dry_run).await
2775 + }
2776 Command::Certificates { command } => run_certificates(&client, command, cli.dry_run).await,
2777 Command::Profiles { command } => run_profiles(&client, command, cli.dry_run).await,
2778 Command::ReviewSubmissions { command } => {
@@ -3608,6 +3736,309 @@ async fn run_app_prices(client: &Client, command: AppPricesCommand) -> Result<()
3736 }
3737 }
3738
3739 +fn check_len(field: &str, value: &str, max: usize) -> Result<()> {
3740 + let len = value.chars().count();
3741 + if len > max {
3742 + anyhow::bail!("{field} is {len} characters; App Store Connect allows {max}");
3743 + }
3744 + Ok(())
3745 +}
3746 +
3747 +async fn run_in_app_purchases(
3748 + client: &Client,
3749 + command: InAppPurchasesCommand,
3750 + dry_run: bool,
3751 +) -> Result<()> {
3752 + use smbcloud_ascapi_iap::{availability, in_app_purchase, localization, price};
3753 + match command {
3754 + InAppPurchasesCommand::List { app_id } => {
3755 + print_json(&client.list_in_app_purchases(&app_id).await?)
3756 + }
3757 + InAppPurchasesCommand::Get { id } => {
3758 + let product = client.get_in_app_purchase(&id).await?;
3759 + let localizations = client.list_in_app_purchase_localizations(&id).await?;
3760 + let manual_prices = client.list_manual_prices(&id).await?;
3761 + let availability = client.get_in_app_purchase_availability(&id).await?;
3762 + let screenshot = client.get_review_screenshot(&id).await?;
3763 + print_json(&serde_json::json!({
3764 + "product": product,
3765 + "localizations": localizations,
3766 + "manualPrices": manual_prices,
3767 + "availability": availability,
3768 + "reviewScreenshot": screenshot,
3769 + }))
3770 + }
3771 + InAppPurchasesCommand::Create {
3772 + app_id,
3773 + product_id,
3774 + name,
3775 + r#type,
3776 + family_sharable,
3777 + review_note,
3778 + review_note_file,
3779 + } => {
3780 + check_len("--name", &name, in_app_purchase::NAME_MAX_LEN)?;
3781 + let review_note = text_arg(review_note, review_note_file, "--review-note-file")?;
3782 + if let Some(note) = &review_note {
3783 + check_len("--review-note", note, in_app_purchase::REVIEW_NOTE_MAX_LEN)?;
3784 + }
3785 + let existing = client.list_in_app_purchases(&app_id).await?;
3786 + if let Some(found) = existing
3787 + .iter()
3788 + .find(|p| p.attributes.product_id.as_deref() == Some(product_id.as_str()))
3789 + {
3790 + anyhow::bail!(
3791 + "{product_id} already exists on this app (id {}); use `update`",
3792 + found.id
3793 + );
3794 + }
3795 + let attributes = InAppPurchaseCreateAttributes {
3796 + name,
3797 + product_id,
3798 + in_app_purchase_type: r#type.into(),
3799 + review_note,
3800 + family_sharable: Some(family_sharable),
3801 + };
3802 + let body = in_app_purchase::create_body(&app_id, attributes.clone());
3803 + if dry_run_guard(dry_run, &body)? {
3804 + return Ok(());
3805 + }
3806 + let created = client
3807 + .create_in_app_purchase(&app_id, attributes.clone())
3808 + .await?;
3809 + let back = client.get_in_app_purchase(&created.id).await?;
3810 + if back.attributes.product_id.as_deref() != Some(attributes.product_id.as_str()) {
3811 + anyhow::bail!(
3812 + "created {} but reading it back shows a different product id",
3813 + created.id
3814 + );
3815 + }
3816 + print_json(&back)
3817 + }
3818 + InAppPurchasesCommand::Update {
3819 + id,
3820 + name,
3821 + review_note,
3822 + review_note_file,
3823 + } => {
3824 + let review_note = text_arg(review_note, review_note_file, "--review-note-file")?;
3825 + if let Some(name) = &name {
3826 + check_len("--name", name, in_app_purchase::NAME_MAX_LEN)?;
3827 + }
3828 + if let Some(note) = &review_note {
3829 + check_len("--review-note", note, in_app_purchase::REVIEW_NOTE_MAX_LEN)?;
3830 + }
3831 + if name.is_none() && review_note.is_none() {
3832 + anyhow::bail!("nothing to change: pass --name or --review-note");
3833 + }
3834 + let update = InAppPurchaseUpdateAttributes {
3835 + name,
3836 + review_note,
3837 + family_sharable: None,
3838 + };
3839 + let body = in_app_purchase::update_body(&id, update.clone());
3840 + if dry_run_guard(dry_run, &body)? {
3841 + return Ok(());
3842 + }
3843 + client.update_in_app_purchase(&id, update.clone()).await?;
3844 + let back = client.get_in_app_purchase(&id).await?;
3845 + if update.name.is_some() && back.attributes.name != update.name
3846 + || update.review_note.is_some() && back.attributes.review_note != update.review_note
3847 + {
3848 + anyhow::bail!("updated {id} but reading it back does not match what was sent");
3849 + }
3850 + print_json(&back)
3851 + }
3852 + InAppPurchasesCommand::Localize {
3853 + id,
3854 + locale,
3855 + name,
3856 + description,
3857 + } => {
3858 + check_len("--name", &name, localization::NAME_MAX_LEN)?;
3859 + if let Some(d) = &description {
3860 + check_len("--description", d, localization::DESCRIPTION_MAX_LEN)?;
3861 + }
3862 + let existing = client
3863 + .list_in_app_purchase_localizations(&id)
3864 + .await?
3865 + .into_iter()
3866 + .find(|l| l.attributes.locale.as_deref() == Some(locale.as_str()));
3867 + let written = match existing {
3868 + Some(found) => {
3869 + let update = LocalizationUpdate {
3870 + name: Some(name.clone()),
3871 + description: description.clone(),
3872 + };
3873 + if dry_run_guard(
3874 + dry_run,
3875 + &localization::update_body(&found.id, update.clone()),
3876 + )? {
3877 + return Ok(());
3878 + }
3879 + client
3880 + .update_in_app_purchase_localization(&found.id, update)
3881 + .await?
3882 + }
3883 + None => {
3884 + let body =
3885 + localization::create_body(&id, &locale, &name, description.as_deref());
3886 + if dry_run_guard(dry_run, &body)? {
3887 + return Ok(());
3888 + }
3889 + client
3890 + .create_in_app_purchase_localization(
3891 + &id,
3892 + &locale,
3893 + &name,
3894 + description.as_deref(),
3895 + )
3896 + .await?
3897 + }
3898 + };
3899 + let back = client
3900 + .list_in_app_purchase_localizations(&id)
3901 + .await?
3902 + .into_iter()
3903 + .find(|l| l.id == written.id)
3904 + .context("the localization was written but is missing when read back")?;
3905 + if back.attributes.name.as_deref() != Some(name.as_str())
3906 + || description.is_some() && back.attributes.description != description
3907 + {
3908 + anyhow::bail!(
3909 + "localization {} reads back differently from what was sent",
3910 + back.id
3911 + );
3912 + }
3913 + print_json(&back)
3914 + }
3915 + InAppPurchasesCommand::PricePoints { id, territory } => {
3916 + let points = client.list_price_points(&id, &territory).await?;
3917 + let rows: Vec<_> = points
3918 + .iter()
3919 + .map(|p| {
3920 + serde_json::json!({
3921 + "id": p.id,
3922 + "customerPrice": p.attributes.customer_price,
3923 + "proceeds": p.attributes.proceeds,
3924 + })
3925 + })
3926 + .collect();
3927 + print_json(&rows)
3928 + }
3929 + InAppPurchasesCommand::SetPrice {
3930 + id,
3931 + territory,
3932 + price: amount,
3933 + } => {
3934 + let Some(point) = client.find_price_point(&id, &territory, &amount).await? else {
3935 + anyhow::bail!(
3936 + "{amount} is not one of Apple's price points in {territory}; \
3937 + `asc in-app-purchases price-points {id} --territory {territory}` lists them"
3938 + );
3939 + };
3940 + let body = price::schedule_body(&id, &territory, &point.id);
3941 + if dry_run_guard(dry_run, &body)? {
3942 + return Ok(());
3943 + }
3944 + client
3945 + .set_price_schedule(&id, &territory, &point.id)
3946 + .await?;
3947 + let prices = client.list_manual_prices(&id).await?;
3948 + let matches = prices.iter().any(|p| {
3949 + p.territory.as_deref() == Some(territory.as_str())
3950 + && p.customer_price.as_deref() == Some(amount.as_str())
3951 + });
3952 + if !matches {
3953 + anyhow::bail!(
3954 + "the price schedule was posted but reads back without {amount} in {territory}"
3955 + );
3956 + }
3957 + print_json(&prices)
3958 + }
3959 + InAppPurchasesCommand::SetAvailability {
3960 + id,
3961 + all_territories,
3962 + territory,
3963 + no_new_territories,
3964 + } => {
3965 + let mut codes: Vec<String> = if all_territories {
3966 + client
3967 + .list_territories()
3968 + .await?
3969 + .into_iter()
3970 + .map(|t| t.id)
3971 + .collect()
3972 + } else {
3973 + territory.iter().map(|t| t.to_uppercase()).collect()
3974 + };
3975 + codes.sort();
3976 + codes.dedup();
3977 + let body = availability::availability_body(&id, &codes, !no_new_territories);
3978 + if dry_run_guard(dry_run, &body)? {
3979 + return Ok(());
3980 + }
3981 + client
3982 + .set_in_app_purchase_availability(&id, &codes, !no_new_territories)
3983 + .await?;
3984 + let back = client
3985 + .get_in_app_purchase_availability(&id)
3986 + .await?
3987 + .context("availability was posted but reads back as unset")?;
3988 + if back.territories != codes {
3989 + anyhow::bail!(
3990 + "availability reads back with {} territories, {} were sent",
3991 + back.territories.len(),
3992 + codes.len()
3993 + );
3994 + }
3995 + print_json(&back)
3996 + }
3997 + InAppPurchasesCommand::ReviewScreenshot { id, path, replace } => {
3998 + let bytes =
3999 + std::fs::read(&path).with_context(|| format!("cannot read {}", path.display()))?;
4000 + let file_name = path
4001 + .file_name()
4002 + .and_then(|n| n.to_str())
4003 + .context("the screenshot path has no file name")?
4004 + .to_string();
4005 + let existing = client.get_review_screenshot(&id).await?;
4006 + if dry_run {
4007 + println!(
4008 + "# dry run: would {}upload {file_name} ({} bytes) as the review screenshot of {id}",
4009 + if existing.is_some() { "delete the current screenshot and " } else { "" },
4010 + bytes.len()
4011 + );
4012 + return Ok(());
4013 + }
4014 + if let Some(old) = existing {
4015 + if !replace {
4016 + anyhow::bail!(
4017 + "{id} already has a review screenshot ({}); pass --replace",
4018 + old.id
4019 + );
4020 + }
4021 + client.delete_review_screenshot(&old.id).await?;
4022 + }
4023 + let uploaded = client
4024 + .upload_review_screenshot(&id, file_name, bytes)
4025 + .await?;
4026 + let back = client
4027 + .get_review_screenshot(&id)
4028 + .await?
4029 + .context("the screenshot was committed but reads back as missing")?;
4030 + if back.id != uploaded.id {
4031 + anyhow::bail!(
4032 + "a different screenshot reads back ({}) than the one uploaded ({})",
4033 + back.id,
4034 + uploaded.id
4035 + );
4036 + }
4037 + print_json(&back)
4038 + }
4039 + }
4040 +}
4041 +
4042 async fn run_certificates(
4043 client: &Client,
4044 command: CertificatesCommand,
crates/iap/Cargo.toml new
+20
@@ -0,0 +1,20 @@
1 +[package]
2 +name = "smbcloud-ascapi-iap"
3 +version.workspace = true
4 +edition.workspace = true
5 +authors.workspace = true
6 +license.workspace = true
7 +repository.workspace = true
8 +description = "App Store Connect in-app purchases: the product, its localizations, price schedule, territory availability and App Review screenshot."
9 +readme = "README.md"
10 +
11 +[lib]
12 +path = "src/lib.rs"
13 +
14 +[dependencies]
15 +async-trait = { workspace = true }
16 +md5 = "0.7"
17 +reqwest = { workspace = true }
18 +serde = { workspace = true, features = ["derive"] }
19 +serde_json = { workspace = true }
20 +smbcloud-ascapi-core = { workspace = true }
crates/iap/README.md new
+8
@@ -0,0 +1,8 @@
1 +# smbcloud-ascapi-iap
2 +
3 +App Store Connect in-app purchases (the v2 `inAppPurchases` resource): create a
4 +product, add its per-locale display name and description, set its price and the
5 +territories it is sold in, and upload the screenshot App Review asks for.
6 +
7 +Extension traits on `smbcloud_ascapi_core::Client`; import `prelude::*`.
8 +Subscriptions (`subscriptionGroups`) are not covered.
crates/iap/src/availability.rs new
+167
@@ -0,0 +1,167 @@
1 +//! `inAppPurchaseAvailabilities`: the storefronts a product is sold in.
2 +//!
3 +//! Posting one replaces the whole set. `availableInNewTerritories` decides
4 +//! whether storefronts Apple opens later are added automatically.
5 +
6 +use async_trait::async_trait;
7 +use reqwest::Method;
8 +use serde::{Deserialize, Serialize};
9 +use smbcloud_ascapi_core::jsonapi::Resource;
10 +use smbcloud_ascapi_core::{Client, Result};
11 +
12 +pub const RESOURCE_TYPE: &str = "inAppPurchaseAvailabilities";
13 +
14 +#[derive(Debug, Clone, Default, Serialize, Deserialize)]
15 +#[serde(rename_all = "camelCase")]
16 +pub struct TerritoryAttributes {
17 + #[serde(default)]
18 + pub currency: Option<String>,
19 +}
20 +
21 +/// A storefront; its id is the territory code (`USA`, `SWE`, `IDN`).
22 +pub type Territory = Resource<TerritoryAttributes>;
23 +
24 +#[derive(Debug, Clone, Default, Serialize, Deserialize)]
25 +#[serde(rename_all = "camelCase")]
26 +pub struct AvailabilityAttributes {
27 + #[serde(default)]
28 + pub available_in_new_territories: Option<bool>,
29 +}
30 +
31 +/// What a product is available in, as read back.
32 +#[derive(Debug, Clone, Serialize)]
33 +#[serde(rename_all = "camelCase")]
34 +pub struct Availability {
35 + pub id: String,
36 + pub available_in_new_territories: Option<bool>,
37 + pub territories: Vec<String>,
38 +}
39 +
40 +/// The `POST /v1/inAppPurchaseAvailabilities` body.
41 +pub fn availability_body(
42 + in_app_purchase_id: &str,
43 + territories: &[String],
44 + available_in_new_territories: bool,
45 +) -> serde_json::Value {
46 + let territories: Vec<_> = territories
47 + .iter()
48 + .map(|code| serde_json::json!({ "type": "territories", "id": code }))
49 + .collect();
50 + serde_json::json!({
51 + "data": {
52 + "type": RESOURCE_TYPE,
53 + "attributes": { "availableInNewTerritories": available_in_new_territories },
54 + "relationships": {
55 + "inAppPurchase": {
56 + "data": { "type": crate::in_app_purchase::RESOURCE_TYPE, "id": in_app_purchase_id }
57 + },
58 + "availableTerritories": { "data": territories }
59 + }
60 + }
61 + })
62 +}
63 +
64 +#[async_trait]
65 +pub trait InAppPurchaseAvailabilityApi {
66 + /// `GET /v1/territories`: every storefront App Store Connect knows.
67 + async fn list_territories(&self) -> Result<Vec<Territory>>;
68 +
69 + /// `POST /v1/inAppPurchaseAvailabilities`. Returns the availability id.
70 + async fn set_in_app_purchase_availability(
71 + &self,
72 + in_app_purchase_id: &str,
73 + territories: &[String],
74 + available_in_new_territories: bool,
75 + ) -> Result<String>;
76 +
77 + /// `GET /v2/inAppPurchases/{id}/inAppPurchaseAvailability` and its
78 + /// territories. `None` when availability was never set.
79 + async fn get_in_app_purchase_availability(
80 + &self,
81 + in_app_purchase_id: &str,
82 + ) -> Result<Option<Availability>>;
83 +}
84 +
85 +#[derive(Debug, Deserialize)]
86 +struct AvailabilityDocument {
87 + data: Option<Resource<AvailabilityAttributes>>,
88 +}
89 +
90 +#[async_trait]
91 +impl InAppPurchaseAvailabilityApi for Client {
92 + async fn list_territories(&self) -> Result<Vec<Territory>> {
93 + self.list_all::<TerritoryAttributes>("/v1/territories", &[("limit", "200")])
94 + .await
95 + }
96 +
97 + async fn set_in_app_purchase_availability(
98 + &self,
99 + in_app_purchase_id: &str,
100 + territories: &[String],
101 + available_in_new_territories: bool,
102 + ) -> Result<String> {
103 + let body = availability_body(
104 + in_app_purchase_id,
105 + territories,
106 + available_in_new_territories,
107 + );
108 + let doc: AvailabilityDocument = self
109 + .request(
110 + Method::POST,
111 + "/v1/inAppPurchaseAvailabilities",
112 + &[],
113 + Some(&body),
114 + )
115 + .await?;
116 + Ok(doc.data.map(|d| d.id).unwrap_or_default())
117 + }
118 +
119 + async fn get_in_app_purchase_availability(
120 + &self,
121 + in_app_purchase_id: &str,
122 + ) -> Result<Option<Availability>> {
123 + let path = format!("/v2/inAppPurchases/{in_app_purchase_id}/inAppPurchaseAvailability");
124 + let doc: AvailabilityDocument = self.request(Method::GET, &path, &[], None::<&()>).await?;
125 + let Some(data) = doc.data else {
126 + return Ok(None);
127 + };
128 + let territories_path = format!(
129 + "/v1/inAppPurchaseAvailabilities/{}/availableTerritories",
130 + data.id
131 + );
132 + let mut territories: Vec<String> = self
133 + .list_all::<TerritoryAttributes>(&territories_path, &[("limit", "200")])
134 + .await?
135 + .into_iter()
136 + .map(|t| t.id)
137 + .collect();
138 + territories.sort();
139 + Ok(Some(Availability {
140 + id: data.id,
141 + available_in_new_territories: data.attributes.available_in_new_territories,
142 + territories,
143 + }))
144 + }
145 +}
146 +
147 +#[cfg(test)]
148 +mod tests {
149 + use super::*;
150 +
151 + #[test]
152 + fn the_body_lists_every_territory() {
153 + let v = availability_body("IAP1", &["SWE".into(), "USA".into()], true);
154 + assert_eq!(v["data"]["type"], "inAppPurchaseAvailabilities");
155 + assert_eq!(v["data"]["attributes"]["availableInNewTerritories"], true);
156 + assert_eq!(
157 + v["data"]["relationships"]["inAppPurchase"]["data"]["id"],
158 + "IAP1"
159 + );
160 + let list = v["data"]["relationships"]["availableTerritories"]["data"]
161 + .as_array()
162 + .unwrap();
163 + assert_eq!(list.len(), 2);
164 + assert_eq!(list[1]["type"], "territories");
165 + assert_eq!(list[1]["id"], "USA");
166 + }
167 +}
crates/iap/src/in_app_purchase.rs new
+257
@@ -0,0 +1,257 @@
1 +//! `inAppPurchases` (v2): the product record.
2 +//!
3 +//! Lists come from `GET /v1/apps/{id}/inAppPurchasesV2`; create, read and
4 +//! update go through `/v2/inAppPurchases`. The v1 resource is deprecated and
5 +//! not used here.
6 +
7 +use async_trait::async_trait;
8 +use reqwest::Method;
9 +use serde::{Deserialize, Serialize};
10 +use smbcloud_ascapi_core::jsonapi::{
11 + CreateBody, CreateData, Document, Resource, ResourceId, ToOne, UpdateBody, UpdateData,
12 +};
13 +use smbcloud_ascapi_core::Client;
14 +use smbcloud_ascapi_core::Result;
15 +
16 +pub const RESOURCE_TYPE: &str = "inAppPurchases";
17 +
18 +/// Apple's limit on the reference name (seen only in App Store Connect).
19 +pub const NAME_MAX_LEN: usize = 64;
20 +/// Apple's limit on the note for the reviewer.
21 +pub const REVIEW_NOTE_MAX_LEN: usize = 4000;
22 +
23 +/// `inAppPurchaseType`. Subscriptions that renew are a different resource
24 +/// (`subscriptions`) and are not listed here.
25 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26 +#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
27 +pub enum InAppPurchaseType {
28 + Consumable,
29 + NonConsumable,
30 + NonRenewingSubscription,
31 +}
32 +
33 +#[derive(Debug, Clone, Default, Serialize, Deserialize)]
34 +#[serde(rename_all = "camelCase")]
35 +pub struct InAppPurchaseAttributes {
36 + /// Reference name, shown only in App Store Connect.
37 + #[serde(default)]
38 + pub name: Option<String>,
39 + #[serde(default)]
40 + pub product_id: Option<String>,
41 + #[serde(default)]
42 + pub in_app_purchase_type: Option<InAppPurchaseType>,
43 + /// e.g. `MISSING_METADATA`, `READY_TO_SUBMIT`, `WAITING_FOR_REVIEW`,
44 + /// `APPROVED`. Left as a string: Apple adds states.
45 + #[serde(default)]
46 + pub state: Option<String>,
47 + #[serde(default)]
48 + pub review_note: Option<String>,
49 + #[serde(default)]
50 + pub family_sharable: Option<bool>,
51 + #[serde(default)]
52 + pub content_hosting: Option<bool>,
53 +}
54 +
55 +pub type InAppPurchase = Resource<InAppPurchaseAttributes>;
56 +
57 +/// The fields of a new product.
58 +#[derive(Debug, Clone, Serialize)]
59 +#[serde(rename_all = "camelCase")]
60 +pub struct InAppPurchaseCreateAttributes {
61 + pub name: String,
62 + pub product_id: String,
63 + pub in_app_purchase_type: InAppPurchaseType,
64 + #[serde(skip_serializing_if = "Option::is_none")]
65 + pub review_note: Option<String>,
66 + #[serde(skip_serializing_if = "Option::is_none")]
67 + pub family_sharable: Option<bool>,
68 +}
69 +
70 +/// A partial update: only `Some` fields are sent. The product id and type
71 +/// cannot change after creation.
72 +#[derive(Debug, Clone, Default, Serialize)]
73 +#[serde(rename_all = "camelCase")]
74 +pub struct InAppPurchaseUpdateAttributes {
75 + #[serde(skip_serializing_if = "Option::is_none")]
76 + pub name: Option<String>,
77 + #[serde(skip_serializing_if = "Option::is_none")]
78 + pub review_note: Option<String>,
79 + #[serde(skip_serializing_if = "Option::is_none")]
80 + pub family_sharable: Option<bool>,
81 +}
82 +
83 +#[derive(Debug, Clone, Serialize)]
84 +struct CreateRelationships {
85 + app: ToOne,
86 +}
87 +
88 +/// Build the `POST /v2/inAppPurchases` body. Public so the CLI can print it
89 +/// for `--dry-run` without sending anything.
90 +pub fn create_body(
91 + app_id: &str,
92 + attributes: InAppPurchaseCreateAttributes,
93 +) -> impl Serialize + Send + Sync {
94 + CreateBody {
95 + data: CreateData {
96 + resource_type: RESOURCE_TYPE,
97 + attributes,
98 + relationships: Some(CreateRelationships {
99 + app: ToOne {
100 + data: ResourceId {
101 + resource_type: "apps",
102 + id: app_id.to_string(),
103 + },
104 + },
105 + }),
106 + },
107 + }
108 +}
109 +
110 +/// Build the `PATCH /v2/inAppPurchases/{id}` body.
111 +pub fn update_body(
112 + id: &str,
113 + attributes: InAppPurchaseUpdateAttributes,
114 +) -> impl Serialize + Send + Sync {
115 + UpdateBody {
116 + data: UpdateData {
117 + resource_type: RESOURCE_TYPE,
118 + id: id.to_string(),
119 + attributes,
120 + },
121 + }
122 +}
123 +
124 +/// The product record of an in-app purchase.
125 +#[async_trait]
126 +pub trait InAppPurchasesApi {
127 + /// `GET /v1/apps/{app_id}/inAppPurchasesV2`: every product of the app.
128 + async fn list_in_app_purchases(&self, app_id: &str) -> Result<Vec<InAppPurchase>>;
129 +
130 + /// `GET /v2/inAppPurchases/{id}`.
131 + async fn get_in_app_purchase(&self, id: &str) -> Result<InAppPurchase>;
132 +
133 + /// `POST /v2/inAppPurchases`. Apple refuses a product id already used
134 + /// by this developer account, even on another app or after deletion.
135 + async fn create_in_app_purchase(
136 + &self,
137 + app_id: &str,
138 + attributes: InAppPurchaseCreateAttributes,
139 + ) -> Result<InAppPurchase>;
140 +
141 + /// `PATCH /v2/inAppPurchases/{id}`.
142 + async fn update_in_app_purchase(
143 + &self,
144 + id: &str,
145 + attributes: InAppPurchaseUpdateAttributes,
146 + ) -> Result<InAppPurchase>;
147 +}
148 +
149 +#[async_trait]
150 +impl InAppPurchasesApi for Client {
151 + async fn list_in_app_purchases(&self, app_id: &str) -> Result<Vec<InAppPurchase>> {
152 + let path = format!("/v1/apps/{app_id}/inAppPurchasesV2");
153 + self.list_all::<InAppPurchaseAttributes>(&path, &[("limit", "200")])
154 + .await
155 + }
156 +
157 + async fn get_in_app_purchase(&self, id: &str) -> Result<InAppPurchase> {
158 + let path = format!("/v2/inAppPurchases/{id}");
159 + let doc: Document<InAppPurchaseAttributes> =
160 + self.request(Method::GET, &path, &[], None::<&()>).await?;
161 + Ok(doc.data)
162 + }
163 +
164 + async fn create_in_app_purchase(
165 + &self,
166 + app_id: &str,
167 + attributes: InAppPurchaseCreateAttributes,
168 + ) -> Result<InAppPurchase> {
169 + let body = create_body(app_id, attributes);
170 + let doc: Document<InAppPurchaseAttributes> = self
171 + .request(Method::POST, "/v2/inAppPurchases", &[], Some(&body))
172 + .await?;
173 + Ok(doc.data)
174 + }
175 +
176 + async fn update_in_app_purchase(
177 + &self,
178 + id: &str,
179 + attributes: InAppPurchaseUpdateAttributes,
180 + ) -> Result<InAppPurchase> {
181 + let path = format!("/v2/inAppPurchases/{id}");
182 + let body = update_body(id, attributes);
183 + let doc: Document<InAppPurchaseAttributes> =
184 + self.request(Method::PATCH, &path, &[], Some(&body)).await?;
185 + Ok(doc.data)
186 + }
187 +}
188 +
189 +#[cfg(test)]
190 +mod tests {
191 + use super::*;
192 + use smbcloud_ascapi_core::jsonapi::ListDocument;
193 +
194 + #[test]
195 + fn the_create_body_points_at_the_app() {
196 + let body = create_body(
197 + "6828625369",
198 + InAppPurchaseCreateAttributes {
199 + name: "Onde".into(),
200 + product_id: "onde.unlock".into(),
201 + in_app_purchase_type: InAppPurchaseType::NonConsumable,
202 + review_note: None,
203 + family_sharable: Some(false),
204 + },
205 + );
206 + let v = serde_json::to_value(&body).unwrap();
207 + assert_eq!(v["data"]["type"], "inAppPurchases");
208 + assert_eq!(v["data"]["attributes"]["productId"], "onde.unlock");
209 + assert_eq!(
210 + v["data"]["attributes"]["inAppPurchaseType"],
211 + "NON_CONSUMABLE"
212 + );
213 + assert_eq!(v["data"]["attributes"]["familySharable"], false);
214 + assert!(v["data"]["attributes"].get("reviewNote").is_none());
215 + assert_eq!(v["data"]["relationships"]["app"]["data"]["type"], "apps");
216 + assert_eq!(
217 + v["data"]["relationships"]["app"]["data"]["id"],
218 + "6828625369"
219 + );
220 + }
221 +
222 + #[test]
223 + fn an_update_sends_only_what_changed() {
224 + let body = update_body(
225 + "IAP1",
226 + InAppPurchaseUpdateAttributes {
227 + review_note: Some("Paywall after 15 answers.".into()),
228 + ..Default::default()
229 + },
230 + );
231 + let v = serde_json::to_value(&body).unwrap();
232 + assert_eq!(v["data"]["id"], "IAP1");
233 + let attrs = v["data"]["attributes"].as_object().unwrap();
234 + assert_eq!(attrs.len(), 1);
235 + assert_eq!(attrs["reviewNote"], "Paywall after 15 answers.");
236 + }
237 +
238 + #[test]
239 + fn a_list_deserializes() {
240 + let body = serde_json::json!({"data": [{
241 + "id": "6700000001", "type": "inAppPurchases",
242 + "attributes": {
243 + "name": "Onde", "productId": "onde.unlock",
244 + "inAppPurchaseType": "NON_CONSUMABLE", "state": "MISSING_METADATA",
245 + "reviewNote": null, "familySharable": false, "contentHosting": false
246 + }
247 + }]});
248 + let doc: ListDocument<InAppPurchaseAttributes> = serde_json::from_value(body).unwrap();
249 + let a = &doc.data[0].attributes;
250 + assert_eq!(a.product_id.as_deref(), Some("onde.unlock"));
251 + assert_eq!(
252 + a.in_app_purchase_type,
253 + Some(InAppPurchaseType::NonConsumable)
254 + );
255 + assert_eq!(a.state.as_deref(), Some("MISSING_METADATA"));
256 + }
257 +}
crates/iap/src/lib.rs new
+37
@@ -0,0 +1,37 @@
1 +//! App Store Connect's
2 +//! [in-app purchases](https://developer.apple.com/documentation/appstoreconnectapi/in-app-purchases):
3 +//! the v2 `inAppPurchases` resource and what hangs off it.
4 +//!
5 +//! A product is not sellable until five things exist, each its own
6 +//! resource:
7 +//!
8 +//! 1. the product itself ([`in_app_purchase`]): reference name, product id
9 +//! and type;
10 +//! 2. at least one localization ([`localization`]): the display name and
11 +//! description the store sheet shows;
12 +//! 3. a price schedule ([`price`]): one manual price in a base territory,
13 +//! from which Apple derives every other storefront;
14 +//! 4. territory availability ([`availability`]);
15 +//! 5. an App Review screenshot ([`review_screenshot`]).
16 +//!
17 +//! With those in place the product reaches `READY_TO_SUBMIT`. An app's
18 +//! first in-app purchase is reviewed together with an app version, which is
19 +//! done on the version page, so this crate has no submit call.
20 +//!
21 +//! Everything is an extension trait on
22 +//! [`Client`](smbcloud_ascapi_core::Client); import [`prelude`].
23 +
24 +pub mod availability;
25 +pub mod in_app_purchase;
26 +pub mod localization;
27 +pub mod price;
28 +pub mod review_screenshot;
29 +
30 +/// Every extension trait in this crate, for one glob import.
31 +pub mod prelude {
32 + pub use crate::availability::InAppPurchaseAvailabilityApi;
33 + pub use crate::in_app_purchase::InAppPurchasesApi;
34 + pub use crate::localization::InAppPurchaseLocalizationsApi;
35 + pub use crate::price::InAppPurchasePricesApi;
36 + pub use crate::review_screenshot::InAppPurchaseReviewScreenshotApi;
37 +}
crates/iap/src/localization.rs new
+191
@@ -0,0 +1,191 @@
1 +//! `inAppPurchaseLocalizations`: the display name and description of a
2 +//! product in one locale, as the store's purchase sheet shows them.
3 +
4 +use async_trait::async_trait;
5 +use reqwest::Method;
6 +use serde::{Deserialize, Serialize};
7 +use smbcloud_ascapi_core::jsonapi::{
8 + CreateBody, CreateData, Document, Resource, ResourceId, ToOne, UpdateBody, UpdateData,
9 +};
10 +use smbcloud_ascapi_core::Client;
11 +use smbcloud_ascapi_core::Result;
12 +
13 +pub const RESOURCE_TYPE: &str = "inAppPurchaseLocalizations";
14 +
15 +/// Apple's limits, in characters.
16 +pub const NAME_MAX_LEN: usize = 30;
17 +pub const DESCRIPTION_MAX_LEN: usize = 45;
18 +
19 +#[derive(Debug, Clone, Default, Serialize, Deserialize)]
20 +#[serde(rename_all = "camelCase")]
21 +pub struct InAppPurchaseLocalizationAttributes {
22 + #[serde(default)]
23 + pub name: Option<String>,
24 + #[serde(default)]
25 + pub locale: Option<String>,
26 + #[serde(default)]
27 + pub description: Option<String>,
28 + #[serde(default)]
29 + pub state: Option<String>,
30 +}
31 +
32 +pub type InAppPurchaseLocalization = Resource<InAppPurchaseLocalizationAttributes>;
33 +
34 +#[derive(Debug, Clone, Serialize)]
35 +#[serde(rename_all = "camelCase")]
36 +struct CreateAttributes {
37 + locale: String,
38 + name: String,
39 + #[serde(skip_serializing_if = "Option::is_none")]
40 + description: Option<String>,
41 +}
42 +
43 +#[derive(Debug, Clone, Serialize)]
44 +#[serde(rename_all = "camelCase")]
45 +struct CreateRelationships {
46 + in_app_purchase_v2: ToOne,
47 +}
48 +
49 +/// What a localization update sends; only `Some` fields.
50 +#[derive(Debug, Clone, Default, Serialize)]
51 +#[serde(rename_all = "camelCase")]
52 +pub struct LocalizationUpdate {
53 + #[serde(skip_serializing_if = "Option::is_none")]
54 + pub name: Option<String>,
55 + #[serde(skip_serializing_if = "Option::is_none")]
56 + pub description: Option<String>,
57 +}
58 +
59 +/// The `POST /v1/inAppPurchaseLocalizations` body.
60 +pub fn create_body(
61 + in_app_purchase_id: &str,
62 + locale: &str,
63 + name: &str,
64 + description: Option<&str>,
65 +) -> impl Serialize + Send + Sync {
66 + CreateBody {
67 + data: CreateData {
68 + resource_type: RESOURCE_TYPE,
69 + attributes: CreateAttributes {
70 + locale: locale.to_string(),
71 + name: name.to_string(),
72 + description: description.map(str::to_string),
73 + },
74 + relationships: Some(CreateRelationships {
75 + in_app_purchase_v2: ToOne {
76 + data: ResourceId {
77 + resource_type: crate::in_app_purchase::RESOURCE_TYPE,
78 + id: in_app_purchase_id.to_string(),
79 + },
80 + },
81 + }),
82 + },
83 + }
84 +}
85 +
86 +/// The `PATCH /v1/inAppPurchaseLocalizations/{id}` body.
87 +pub fn update_body(id: &str, update: LocalizationUpdate) -> impl Serialize + Send + Sync {
88 + UpdateBody {
89 + data: UpdateData {
90 + resource_type: RESOURCE_TYPE,
91 + id: id.to_string(),
92 + attributes: update,
93 + },
94 + }
95 +}
96 +
97 +#[async_trait]
98 +pub trait InAppPurchaseLocalizationsApi {
99 + /// `GET /v2/inAppPurchases/{id}/inAppPurchaseLocalizations`.
100 + async fn list_in_app_purchase_localizations(
101 + &self,
102 + in_app_purchase_id: &str,
103 + ) -> Result<Vec<InAppPurchaseLocalization>>;
104 +
105 + /// `POST /v1/inAppPurchaseLocalizations`.
106 + async fn create_in_app_purchase_localization(
107 + &self,
108 + in_app_purchase_id: &str,
109 + locale: &str,
110 + name: &str,
111 + description: Option<&str>,
112 + ) -> Result<InAppPurchaseLocalization>;
113 +
114 + /// `PATCH /v1/inAppPurchaseLocalizations/{id}`.
115 + async fn update_in_app_purchase_localization(
116 + &self,
117 + id: &str,
118 + update: LocalizationUpdate,
119 + ) -> Result<InAppPurchaseLocalization>;
120 +}
121 +
122 +#[async_trait]
123 +impl InAppPurchaseLocalizationsApi for Client {
124 + async fn list_in_app_purchase_localizations(
125 + &self,
126 + in_app_purchase_id: &str,
127 + ) -> Result<Vec<InAppPurchaseLocalization>> {
128 + let path = format!("/v2/inAppPurchases/{in_app_purchase_id}/inAppPurchaseLocalizations");
129 + self.list_all::<InAppPurchaseLocalizationAttributes>(&path, &[("limit", "200")])
130 + .await
131 + }
132 +
133 + async fn create_in_app_purchase_localization(
134 + &self,
135 + in_app_purchase_id: &str,
136 + locale: &str,
137 + name: &str,
138 + description: Option<&str>,
139 + ) -> Result<InAppPurchaseLocalization> {
140 + let body = create_body(in_app_purchase_id, locale, name, description);
141 + let doc: Document<InAppPurchaseLocalizationAttributes> = self
142 + .request(
143 + Method::POST,
144 + "/v1/inAppPurchaseLocalizations",
145 + &[],
146 + Some(&body),
147 + )
148 + .await?;
149 + Ok(doc.data)
150 + }
151 +
152 + async fn update_in_app_purchase_localization(
153 + &self,
154 + id: &str,
155 + update: LocalizationUpdate,
156 + ) -> Result<InAppPurchaseLocalization> {
157 + let path = format!("/v1/inAppPurchaseLocalizations/{id}");
158 + let body = update_body(id, update);
159 + let doc: Document<InAppPurchaseLocalizationAttributes> =
160 + self.request(Method::PATCH, &path, &[], Some(&body)).await?;
161 + Ok(doc.data)
162 + }
163 +}
164 +
165 +#[cfg(test)]
166 +mod tests {
167 + use super::*;
168 +
169 + #[test]
170 + fn the_create_body_names_the_v2_relationship() {
171 + let v = serde_json::to_value(create_body(
172 + "IAP1",
173 + "en-US",
174 + "Onde",
175 + Some("Unlimited answers"),
176 + ))
177 + .unwrap();
178 + assert_eq!(v["data"]["type"], "inAppPurchaseLocalizations");
179 + assert_eq!(v["data"]["attributes"]["locale"], "en-US");
180 + assert_eq!(v["data"]["attributes"]["name"], "Onde");
181 + let rel = &v["data"]["relationships"]["inAppPurchaseV2"]["data"];
182 + assert_eq!(rel["type"], "inAppPurchases");
183 + assert_eq!(rel["id"], "IAP1");
184 + }
185 +
186 + #[test]
187 + fn a_missing_description_is_left_out() {
188 + let v = serde_json::to_value(create_body("IAP1", "en-US", "Onde", None)).unwrap();
189 + assert!(v["data"]["attributes"].get("description").is_none());
190 + }
191 +}
crates/iap/src/price.rs new
+361
@@ -0,0 +1,361 @@
1 +//! What an in-app purchase costs.
2 +//!
3 +//! A price is set by choosing one of Apple's price points in a base
4 +//! territory and posting an `inAppPurchasePriceSchedules` resource that
5 +//! names it as the only manual price. Apple derives the other storefronts
6 +//! from it. The manual price itself is created inline, in the request's
7 +//! `included` array, under a local id of the form `${name}`, which is how
8 +//! Apple documents this endpoint.
9 +//!
10 +//! Price points are opaque ids. [`InAppPurchasePricesApi::find_price_point`]
11 +//! looks one up by its customer price ("4.99") in a territory, matching the
12 +//! string Apple sends exactly rather than parsing money as a float.
13 +
14 +use async_trait::async_trait;
15 +use reqwest::Method;
16 +use serde::{Deserialize, Serialize};
17 +use smbcloud_ascapi_core::jsonapi::{path_and_query, Links, Resource};
18 +use smbcloud_ascapi_core::{Client, Result};
19 +use std::collections::HashMap;
20 +
21 +pub const SCHEDULE_TYPE: &str = "inAppPurchasePriceSchedules";
22 +pub const PRICE_TYPE: &str = "inAppPurchasePrices";
23 +pub const PRICE_POINT_TYPE: &str = "inAppPurchasePricePoints";
24 +
25 +/// The local id of the inline manual price in a schedule request.
26 +const LOCAL_PRICE_ID: &str = "${price1}";
27 +
28 +#[derive(Debug, Clone, Default, Serialize, Deserialize)]
29 +#[serde(rename_all = "camelCase")]
30 +pub struct PricePointAttributes {
31 + /// What the customer pays, as Apple formats it ("4.99").
32 + #[serde(default)]
33 + pub customer_price: Option<String>,
34 + /// What the developer receives after commission and withheld tax.
35 + #[serde(default)]
36 + pub proceeds: Option<String>,
37 +}
38 +
39 +pub type PricePoint = Resource<PricePointAttributes>;
40 +
41 +/// One manual or automatic price of a schedule, with its point joined in.
42 +#[derive(Debug, Clone, Serialize, Deserialize)]
43 +#[serde(rename_all = "camelCase")]
44 +pub struct ScheduledPrice {
45 + pub territory: Option<String>,
46 + pub customer_price: Option<String>,
47 + pub proceeds: Option<String>,
48 + pub start_date: Option<String>,
49 + pub end_date: Option<String>,
50 + pub price_point_id: Option<String>,
51 +}
52 +
53 +/// Build the `POST /v1/inAppPurchasePriceSchedules` body: `territory` is the
54 +/// base territory, `price_point_id` the point to charge there, from today.
55 +pub fn schedule_body(
56 + in_app_purchase_id: &str,
57 + territory: &str,
58 + price_point_id: &str,
59 +) -> serde_json::Value {
60 + serde_json::json!({
61 + "data": {
62 + "type": SCHEDULE_TYPE,
63 + "relationships": {
64 + "inAppPurchase": {
65 + "data": { "type": crate::in_app_purchase::RESOURCE_TYPE, "id": in_app_purchase_id }
66 + },
67 + "baseTerritory": { "data": { "type": "territories", "id": territory } },
68 + "manualPrices": { "data": [ { "type": PRICE_TYPE, "id": LOCAL_PRICE_ID } ] }
69 + }
70 + },
71 + "included": [ {
72 + "type": PRICE_TYPE,
73 + "id": LOCAL_PRICE_ID,
74 + "attributes": { "startDate": null },
75 + "relationships": {
76 + "inAppPurchaseV2": {
77 + "data": { "type": crate::in_app_purchase::RESOURCE_TYPE, "id": in_app_purchase_id }
78 + },
79 + "inAppPurchasePricePoint": {
80 + "data": { "type": PRICE_POINT_TYPE, "id": price_point_id }
81 + }
82 + }
83 + } ]
84 + })
85 +}
86 +
87 +/// The price point whose customer price is exactly `customer_price`.
88 +pub fn pick_price_point<'a>(
89 + points: &'a [PricePoint],
90 + customer_price: &str,
91 +) -> Option<&'a PricePoint> {
92 + points
93 + .iter()
94 + .find(|point| point.attributes.customer_price.as_deref() == Some(customer_price))
95 +}
96 +
97 +#[async_trait]
98 +pub trait InAppPurchasePricesApi {
99 + /// `GET /v2/inAppPurchases/{id}/pricePoints?filter[territory]=…`: every
100 + /// price point offered in one territory (several hundred; all pages).
101 + async fn list_price_points(
102 + &self,
103 + in_app_purchase_id: &str,
104 + territory: &str,
105 + ) -> Result<Vec<PricePoint>>;
106 +
107 + /// The price point charging exactly `customer_price` in `territory`,
108 + /// or `None` when that amount is not one of Apple's points there.
109 + async fn find_price_point(
110 + &self,
111 + in_app_purchase_id: &str,
112 + territory: &str,
113 + customer_price: &str,
114 + ) -> Result<Option<PricePoint>>;
115 +
116 + /// `POST /v1/inAppPurchasePriceSchedules`: replace the product's prices
117 + /// with one manual price in `territory`. Returns the schedule id.
118 + async fn set_price_schedule(
119 + &self,
120 + in_app_purchase_id: &str,
121 + territory: &str,
122 + price_point_id: &str,
123 + ) -> Result<String>;
124 +
125 + /// The schedule's manual prices, with customer price and proceeds
126 + /// joined in. Empty when no price has been set.
127 + async fn list_manual_prices(&self, in_app_purchase_id: &str) -> Result<Vec<ScheduledPrice>>;
128 +}
129 +
130 +#[async_trait]
131 +impl InAppPurchasePricesApi for Client {
132 + async fn list_price_points(
133 + &self,
134 + in_app_purchase_id: &str,
135 + territory: &str,
136 + ) -> Result<Vec<PricePoint>> {
137 + let path = format!("/v2/inAppPurchases/{in_app_purchase_id}/pricePoints");
138 + self.list_all::<PricePointAttributes>(
139 + &path,
140 + &[("filter[territory]", territory), ("limit", "200")],
141 + )
142 + .await
143 + }
144 +
145 + async fn find_price_point(
146 + &self,
147 + in_app_purchase_id: &str,
148 + territory: &str,
149 + customer_price: &str,
150 + ) -> Result<Option<PricePoint>> {
151 + let points = self
152 + .list_price_points(in_app_purchase_id, territory)
153 + .await?;
154 + Ok(pick_price_point(&points, customer_price).cloned())
155 + }
156 +
157 + async fn set_price_schedule(
158 + &self,
159 + in_app_purchase_id: &str,
160 + territory: &str,
161 + price_point_id: &str,
162 + ) -> Result<String> {
163 + let body = schedule_body(in_app_purchase_id, territory, price_point_id);
164 + let doc: IdDocument = self
165 + .request(
166 + Method::POST,
167 + "/v1/inAppPurchasePriceSchedules",
168 + &[],
169 + Some(&body),
170 + )
171 + .await?;
172 + Ok(doc.data.id)
173 + }
174 +
175 + async fn list_manual_prices(&self, in_app_purchase_id: &str) -> Result<Vec<ScheduledPrice>> {
176 + let schedule_path = format!("/v2/inAppPurchases/{in_app_purchase_id}/iapPriceSchedule");
177 + let schedule: OptionalIdDocument = self
178 + .request(Method::GET, &schedule_path, &[], None::<&()>)
179 + .await?;
180 + let Some(schedule) = schedule.data else {
181 + return Ok(Vec::new());
182 + };
183 +
184 + let query = [
185 + ("include", "inAppPurchasePricePoint,territory"),
186 + ("limit", "200"),
187 + ];
188 + let mut path = format!(
189 + "/v1/inAppPurchasePriceSchedules/{}/manualPrices",
190 + schedule.id
191 + );
192 + let mut page_query: &[(&str, &str)] = &query;
193 + let mut prices = Vec::new();
194 + loop {
195 + let doc: PricesDocument = self
196 + .request(Method::GET, &path, page_query, None::<&()>)
197 + .await?;
198 + prices.extend(join(&doc));
199 + let Some(next) = doc
200 + .links
201 + .and_then(|l| l.next)
202 + .and_then(|n| path_and_query(&n))
203 + else {
204 + break;
205 + };
206 + path = next;
207 + page_query = &[];
208 + }
209 + Ok(prices)
210 + }
211 +}
212 +
213 +#[derive(Debug, Deserialize)]
214 +struct IdOnly {
215 + id: String,
216 +}
217 +
218 +#[derive(Debug, Deserialize)]
219 +struct IdDocument {
220 + data: IdOnly,
221 +}
222 +
223 +#[derive(Debug, Deserialize)]
224 +struct OptionalIdDocument {
225 + data: Option<IdOnly>,
226 +}
227 +
228 +#[derive(Debug, Deserialize)]
229 +struct PricesDocument {
230 + data: Vec<PriceRow>,
231 + #[serde(default)]
232 + included: Vec<serde_json::Value>,
233 + #[serde(default)]
234 + links: Option<Links>,
235 +}
236 +
237 +#[derive(Debug, Deserialize)]
238 +struct PriceRow {
239 + #[serde(default)]
240 + attributes: PriceRowAttributes,
241 + #[serde(default)]
242 + relationships: serde_json::Value,
243 +}
244 +
245 +#[derive(Debug, Default, Deserialize)]
246 +#[serde(rename_all = "camelCase")]
247 +struct PriceRowAttributes {
248 + #[serde(default)]
249 + start_date: Option<String>,
250 + #[serde(default)]
251 + end_date: Option<String>,
252 +}
253 +
254 +fn related_id(relationships: &serde_json::Value, key: &str) -> Option<String> {
255 + relationships[key]["data"]["id"]
256 + .as_str()
257 + .map(str::to_string)
258 +}
259 +
260 +fn join(doc: &PricesDocument) -> Vec<ScheduledPrice> {
261 + let points: HashMap<&str, PricePointAttributes> = doc
262 + .included
263 + .iter()
264 + .filter(|r| r["type"] == PRICE_POINT_TYPE)
265 + .filter_map(|r| {
266 + let id = r["id"].as_str()?;
267 + let attrs = serde_json::from_value(r["attributes"].clone()).ok()?;
268 + Some((id, attrs))
269 + })
270 + .collect();
271 + doc.data
272 + .iter()
273 + .map(|row| {
274 + let point_id = related_id(&row.relationships, "inAppPurchasePricePoint");
275 + let point = point_id.as_deref().and_then(|id| points.get(id));
276 + ScheduledPrice {
277 + territory: related_id(&row.relationships, "territory"),
278 + customer_price: point.and_then(|p| p.customer_price.clone()),
279 + proceeds: point.and_then(|p| p.proceeds.clone()),
280 + start_date: row.attributes.start_date.clone(),
281 + end_date: row.attributes.end_date.clone(),
282 + price_point_id: point_id,
283 + }
284 + })
285 + .collect()
286 +}
287 +
288 +#[cfg(test)]
289 +mod tests {
290 + use super::*;
291 +
292 + fn point(id: &str, price: &str) -> PricePoint {
293 + Resource {
294 + id: id.into(),
295 + resource_type: PRICE_POINT_TYPE.into(),
296 + attributes: PricePointAttributes {
297 + customer_price: Some(price.into()),
298 + proceeds: None,
299 + },
300 + relationships: None,
301 + }
302 + }
303 +
304 + #[test]
305 + fn the_schedule_body_creates_its_price_inline() {
306 + let v = schedule_body("IAP1", "USA", "PP499");
307 + let rel = &v["data"]["relationships"];
308 + assert_eq!(v["data"]["type"], "inAppPurchasePriceSchedules");
309 + assert_eq!(rel["inAppPurchase"]["data"]["id"], "IAP1");
310 + assert_eq!(rel["baseTerritory"]["data"]["id"], "USA");
311 + assert_eq!(rel["manualPrices"]["data"][0]["id"], "${price1}");
312 + let price = &v["included"][0];
313 + assert_eq!(price["id"], "${price1}");
314 + assert_eq!(price["type"], "inAppPurchasePrices");
315 + assert!(price["attributes"]["startDate"].is_null());
316 + assert_eq!(
317 + price["relationships"]["inAppPurchaseV2"]["data"]["id"],
318 + "IAP1"
319 + );
320 + assert_eq!(
321 + price["relationships"]["inAppPurchasePricePoint"]["data"]["id"],
322 + "PP499"
323 + );
324 + }
325 +
326 + #[test]
327 + fn a_price_point_matches_the_exact_string() {
328 + let points = vec![point("A", "4.49"), point("B", "4.99"), point("C", "49.99")];
329 + assert_eq!(
330 + pick_price_point(&points, "4.99").map(|p| p.id.as_str()),
331 + Some("B")
332 + );
333 + assert!(pick_price_point(&points, "4.9").is_none());
334 + assert!(pick_price_point(&points, "5").is_none());
335 + }
336 +
337 + #[test]
338 + fn manual_prices_join_their_point() {
339 + let doc: PricesDocument = serde_json::from_value(serde_json::json!({
340 + "data": [{
341 + "type": "inAppPurchasePrices", "id": "P1",
342 + "attributes": { "startDate": null, "endDate": null },
343 + "relationships": {
344 + "inAppPurchasePricePoint": { "data": { "type": "inAppPurchasePricePoints", "id": "PP499" } },
345 + "territory": { "data": { "type": "territories", "id": "USA" } }
346 + }
347 + }],
348 + "included": [
349 + { "type": "inAppPurchasePricePoints", "id": "PP499",
350 + "attributes": { "customerPrice": "4.99", "proceeds": "4.24" } },
351 + { "type": "territories", "id": "USA", "attributes": { "currency": "USD" } }
352 + ]
353 + }))
354 + .unwrap();
355 + let prices = join(&doc);
356 + assert_eq!(prices.len(), 1);
357 + assert_eq!(prices[0].territory.as_deref(), Some("USA"));
358 + assert_eq!(prices[0].customer_price.as_deref(), Some("4.99"));
359 + assert_eq!(prices[0].proceeds.as_deref(), Some("4.24"));
360 + }
361 +}
crates/iap/src/review_screenshot.rs new
+227
@@ -0,0 +1,227 @@
1 +//! `inAppPurchaseAppStoreReviewScreenshots`: the one screenshot App Review
2 +//! wants of the purchase in the app.
3 +//!
4 +//! Same three steps as any App Store Connect asset: reserve (`POST`, which
5 +//! returns pre-signed upload operations), PUT the bytes to each operation,
6 +//! then commit (`PATCH` with `uploaded: true` and the file's MD5).
7 +
8 +use async_trait::async_trait;
9 +use reqwest::Method;
10 +use serde::{Deserialize, Deserializer, Serialize};
11 +use smbcloud_ascapi_core::jsonapi::{
12 + CreateBody, CreateData, Document, OptionalDocument, Resource, ResourceId, ToOne, UpdateBody,
13 + UpdateData,
14 +};
15 +use smbcloud_ascapi_core::{Client, Result};
16 +
17 +pub const RESOURCE_TYPE: &str = "inAppPurchaseAppStoreReviewScreenshots";
18 +
19 +/// Apple sends `null` for these lists once an asset is committed.
20 +fn null_as_default<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
21 +where
22 + D: Deserializer<'de>,
23 + T: Default + Deserialize<'de>,
24 +{
25 + Ok(Option::deserialize(deserializer)?.unwrap_or_default())
26 +}
27 +
28 +#[derive(Debug, Clone, Serialize, Deserialize)]
29 +#[serde(rename_all = "camelCase")]
30 +pub struct RequestHeader {
31 + pub name: String,
32 + pub value: String,
33 +}
34 +
35 +#[derive(Debug, Clone, Serialize, Deserialize)]
36 +#[serde(rename_all = "camelCase")]
37 +pub struct UploadOperation {
38 + pub method: String,
39 + pub url: String,
40 + #[serde(default)]
41 + pub length: u64,
42 + #[serde(default)]
43 + pub offset: u64,
44 + #[serde(default, deserialize_with = "null_as_default")]
45 + pub request_headers: Vec<RequestHeader>,
46 +}
47 +
48 +#[derive(Debug, Clone, Default, Serialize, Deserialize)]
49 +#[serde(rename_all = "camelCase")]
50 +pub struct ReviewScreenshotAttributes {
51 + #[serde(default)]
52 + pub file_name: Option<String>,
53 + #[serde(default)]
54 + pub file_size: Option<u64>,
55 + #[serde(default)]
56 + pub source_file_checksum: Option<String>,
57 + #[serde(default)]
58 + pub asset_delivery_state: Option<serde_json::Value>,
59 + #[serde(default, deserialize_with = "null_as_default")]
60 + pub upload_operations: Vec<UploadOperation>,
61 +}
62 +
63 +pub type ReviewScreenshot = Resource<ReviewScreenshotAttributes>;
64 +
65 +#[derive(Debug, Clone, Serialize)]
66 +#[serde(rename_all = "camelCase")]
67 +struct CreateAttributes {
68 + file_name: String,
69 + file_size: u64,
70 +}
71 +
72 +#[derive(Debug, Clone, Serialize)]
73 +#[serde(rename_all = "camelCase")]
74 +struct CreateRelationships {
75 + in_app_purchase_v2: ToOne,
76 +}
77 +
78 +#[derive(Debug, Clone, Serialize)]
79 +#[serde(rename_all = "camelCase")]
80 +struct CommitAttributes {
81 + uploaded: bool,
82 + source_file_checksum: String,
83 +}
84 +
85 +/// The reserve (`POST`) body.
86 +pub fn create_body(
87 + in_app_purchase_id: &str,
88 + file_name: &str,
89 + file_size: u64,
90 +) -> impl Serialize + Send + Sync {
91 + CreateBody {
92 + data: CreateData {
93 + resource_type: RESOURCE_TYPE,
94 + attributes: CreateAttributes {
95 + file_name: file_name.to_string(),
96 + file_size,
97 + },
98 + relationships: Some(CreateRelationships {
99 + in_app_purchase_v2: ToOne {
100 + data: ResourceId {
101 + resource_type: crate::in_app_purchase::RESOURCE_TYPE,
102 + id: in_app_purchase_id.to_string(),
103 + },
104 + },
105 + }),
106 + },
107 + }
108 +}
109 +
110 +#[async_trait]
111 +pub trait InAppPurchaseReviewScreenshotApi {
112 + /// `GET /v2/inAppPurchases/{id}/appStoreReviewScreenshot`.
113 + async fn get_review_screenshot(
114 + &self,
115 + in_app_purchase_id: &str,
116 + ) -> Result<Option<ReviewScreenshot>>;
117 +
118 + /// `DELETE /v1/inAppPurchaseAppStoreReviewScreenshots/{id}`.
119 + async fn delete_review_screenshot(&self, id: &str) -> Result<()>;
120 +
121 + /// Reserve, upload and commit `bytes` as the product's review
122 + /// screenshot. A product holds one; delete the old one first.
123 + async fn upload_review_screenshot(
124 + &self,
125 + in_app_purchase_id: &str,
126 + file_name: String,
127 + bytes: Vec<u8>,
128 + ) -> Result<ReviewScreenshot>;
129 +}
130 +
131 +#[async_trait]
132 +impl InAppPurchaseReviewScreenshotApi for Client {
133 + async fn get_review_screenshot(
134 + &self,
135 + in_app_purchase_id: &str,
136 + ) -> Result<Option<ReviewScreenshot>> {
137 + let path = format!("/v2/inAppPurchases/{in_app_purchase_id}/appStoreReviewScreenshot");
138 + let doc: OptionalDocument<ReviewScreenshotAttributes> =
139 + self.request(Method::GET, &path, &[], None::<&()>).await?;
140 + Ok(doc.data)
141 + }
142 +
143 + async fn delete_review_screenshot(&self, id: &str) -> Result<()> {
144 + let path = format!("/v1/inAppPurchaseAppStoreReviewScreenshots/{id}");
145 + self.request_no_content::<()>(Method::DELETE, &path, &[], None)
146 + .await
147 + }
148 +
149 + async fn upload_review_screenshot(
150 + &self,
151 + in_app_purchase_id: &str,
152 + file_name: String,
153 + bytes: Vec<u8>,
154 + ) -> Result<ReviewScreenshot> {
155 + let checksum = format!("{:x}", md5::compute(&bytes));
156 + let body = create_body(in_app_purchase_id, &file_name, bytes.len() as u64);
157 + let reserved: Document<ReviewScreenshotAttributes> = self
158 + .request(
159 + Method::POST,
160 + "/v1/inAppPurchaseAppStoreReviewScreenshots",
161 + &[],
162 + Some(&body),
163 + )
164 + .await?;
165 + let reserved = reserved.data;
166 +
167 + for op in &reserved.attributes.upload_operations {
168 + let start = op.offset as usize;
169 + let end = start + op.length as usize;
170 + let chunk = bytes
171 + .get(start..end)
172 + .map(<[u8]>::to_vec)
173 + .unwrap_or_default();
174 + let headers: Vec<(String, String)> = op
175 + .request_headers
176 + .iter()
177 + .map(|h| (h.name.clone(), h.value.clone()))
178 + .collect();
179 + let method: Method = op.method.parse().unwrap_or(Method::PUT);
180 + self.upload_bytes(method, &op.url, &headers, chunk).await?;
181 + }
182 +
183 + let path = format!("/v1/inAppPurchaseAppStoreReviewScreenshots/{}", reserved.id);
184 + let commit = UpdateBody {
185 + data: UpdateData {
186 + resource_type: RESOURCE_TYPE,
187 + id: reserved.id.clone(),
188 + attributes: CommitAttributes {
189 + uploaded: true,
190 + source_file_checksum: checksum,
191 + },
192 + },
193 + };
194 + let doc: Document<ReviewScreenshotAttributes> = self
195 + .request(Method::PATCH, &path, &[], Some(&commit))
196 + .await?;
197 + Ok(doc.data)
198 + }
199 +}
200 +
201 +#[cfg(test)]
202 +mod tests {
203 + use super::*;
204 +
205 + #[test]
206 + fn the_reserve_body_names_the_v2_relationship() {
207 + let v = serde_json::to_value(create_body("IAP1", "paywall.png", 1234)).unwrap();
208 + assert_eq!(v["data"]["type"], "inAppPurchaseAppStoreReviewScreenshots");
209 + assert_eq!(v["data"]["attributes"]["fileName"], "paywall.png");
210 + assert_eq!(v["data"]["attributes"]["fileSize"], 1234);
211 + assert_eq!(
212 + v["data"]["relationships"]["inAppPurchaseV2"]["data"]["id"],
213 + "IAP1"
214 + );
215 + }
216 +
217 + #[test]
218 + fn a_committed_screenshot_with_null_operations_deserializes() {
219 + let doc: Document<ReviewScreenshotAttributes> = serde_json::from_value(serde_json::json!({
220 + "data": { "id": "S1", "type": RESOURCE_TYPE,
221 + "attributes": { "fileName": "paywall.png", "fileSize": 10,
222 + "uploadOperations": null, "assetDeliveryState": { "state": "COMPLETE" } } }
223 + }))
224 + .unwrap();
225 + assert!(doc.data.attributes.upload_operations.is_empty());
226 + }
227 +}