Skip to main content

lockbook_server_lib/billing/
billing_service.rs

1use crate::ServerError::ClientError;
2use crate::billing::app_store_model::{NotificationChange, Subtype};
3use crate::billing::billing_model::{
4    AppStoreUserInfo, BillingPlatform, GooglePlayUserInfo, StripeUserInfo,
5};
6use crate::billing::billing_service::LockBillingWorkflowError::{
7    ExistingRequestPending, UserNotFound,
8};
9use crate::billing::google_play_model::NotificationType;
10use crate::document_service::DocumentService;
11use crate::guard::ServerTx;
12use crate::schema::Account;
13use crate::{RequestContext, ServerError, ServerState};
14use base64::DecodeError;
15use lb_rs::model::api::{
16    AdminSetUserTierError, AdminSetUserTierInfo, AdminSetUserTierRequest, AdminSetUserTierResponse,
17    AppStoreAccountState, CancelSubscriptionError, CancelSubscriptionRequest,
18    CancelSubscriptionResponse, FREE_TIER_USAGE_SIZE, GetSubscriptionInfoError,
19    GetSubscriptionInfoRequest, GetSubscriptionInfoRequestV2, GetSubscriptionInfoResponse,
20    GetSubscriptionInfoResponseV2, GooglePlayAccountState, PaymentPlatform, PaymentPlatformV2,
21    StripeAccountState, SubscriptionInfo, SubscriptionInfoV2, UpgradeAccountAppStoreError,
22    UpgradeAccountAppStoreRequest, UpgradeAccountAppStoreResponse, UpgradeAccountGooglePlayError,
23    UpgradeAccountGooglePlayRequest, UpgradeAccountGooglePlayResponse, UpgradeAccountStripeError,
24    UpgradeAccountStripeRequest, UpgradeAccountStripeResponse,
25};
26use lb_rs::model::clock::get_time;
27use lb_rs::model::file_metadata::Owner;
28use lb_rs::model::server_tree::ServerTree;
29use lb_rs::model::tree_like::TreeLike;
30use libsecp256k1::PublicKey;
31use std::collections::HashMap;
32use std::fmt::Debug;
33use tracing::*;
34use warp::http::HeaderValue;
35use warp::hyper::body::Bytes;
36
37use super::app_store_client::AppStoreClient;
38use super::google_play_client::GooglePlayClient;
39use super::stripe_client::StripeClient;
40
41impl<S, A, G, D> ServerState<S, A, G, D>
42where
43    S: StripeClient,
44    A: AppStoreClient,
45    G: GooglePlayClient,
46    D: DocumentService,
47{
48    async fn lock_subscription_profile(
49        &self, public_key: &PublicKey,
50    ) -> Result<Account, ServerError<LockBillingWorkflowError>> {
51        let owner = Owner(*public_key);
52        let mut guard = self.index_db.lock().await;
53        let mut tx = ServerTx::begin(&mut guard)?;
54        let db = &mut *tx;
55        let mut account = db
56            .accounts
57            .get(&owner)
58            .ok_or(ClientError(UserNotFound))?
59            .clone();
60
61        let current_time = get_time().0 as u64;
62
63        if current_time - account.billing_info.last_in_payment_flow
64            < self.config.billing.millis_between_user_payment_flows
65        {
66            warn!(
67                ?owner,
68                "User/Webhook is already in payment flow, or not enough time that has elapsed since a failed attempt"
69            );
70
71            return Err(ClientError(ExistingRequestPending));
72        }
73
74        account.billing_info.last_in_payment_flow = current_time;
75        db.accounts.insert(owner, account.clone())?;
76
77        debug!(?owner, "User successfully entered payment flow");
78
79        tx.end()?;
80        Ok(account)
81    }
82
83    async fn release_subscription_profile<T: Debug>(
84        &self, public_key: PublicKey, mut account: Account,
85    ) -> Result<(), ServerError<T>> {
86        account.billing_info.last_in_payment_flow = 0;
87        let mut db = self.index_db.lock().await;
88        let mut tx = ServerTx::begin(&mut db)?;
89        tx.accounts.insert(Owner(public_key), account)?;
90        tx.end()?;
91        Ok(())
92    }
93
94    pub async fn upgrade_account_app_store(
95        &self, context: RequestContext<UpgradeAccountAppStoreRequest>,
96    ) -> Result<UpgradeAccountAppStoreResponse, ServerError<UpgradeAccountAppStoreError>> {
97        let request = &context.request;
98
99        let mut account = self.lock_subscription_profile(&context.public_key).await?;
100
101        debug!("Upgrading the account of a user through app store billing");
102
103        {
104            let db = self.index_db.lock().await;
105            if db
106                .schema
107                .app_store_ids
108                .get(&request.app_account_token)
109                .is_some()
110            {
111                return Err(ClientError(UpgradeAccountAppStoreError::AppStoreAccountAlreadyLinked));
112            }
113        }
114
115        if account.billing_info.is_premium() {
116            return Err(ClientError(UpgradeAccountAppStoreError::AlreadyPremium));
117        }
118
119        let (expires, account_state) = Self::verify_details(
120            &self.app_store_client,
121            &self.config.billing.apple,
122            &request.app_account_token,
123            &request.original_transaction_id,
124        )
125        .await?;
126
127        debug!("Successfully verified app store subscription");
128
129        account.billing_info.billing_platform = Some(BillingPlatform::AppStore(AppStoreUserInfo {
130            account_token: request.app_account_token.clone(),
131            original_transaction_id: request.original_transaction_id.clone(),
132            subscription_product_id: self.config.billing.apple.subscription_product_id.clone(),
133            expiration_time: expires,
134            account_state,
135        }));
136
137        {
138            let mut db = self.index_db.lock().await;
139            let mut tx = ServerTx::begin(&mut db)?;
140            tx.app_store_ids
141                .insert(request.app_account_token.clone(), Owner(context.public_key))?;
142            tx.end()?;
143        }
144
145        self.release_subscription_profile::<UpgradeAccountAppStoreError>(
146            context.public_key,
147            account,
148        )
149        .await?;
150
151        Ok(UpgradeAccountAppStoreResponse {})
152    }
153
154    pub async fn upgrade_account_google_play(
155        &self, context: RequestContext<UpgradeAccountGooglePlayRequest>,
156    ) -> Result<UpgradeAccountGooglePlayResponse, ServerError<UpgradeAccountGooglePlayError>> {
157        let request = &context.request;
158
159        let mut account = self.lock_subscription_profile(&context.public_key).await?;
160
161        if account.billing_info.is_premium() {
162            return Err(ClientError(UpgradeAccountGooglePlayError::AlreadyPremium));
163        }
164
165        debug!("Upgrading the account of a user through google play billing");
166
167        self.google_play_client
168            .acknowledge_subscription(&self.config, &request.purchase_token)
169            .await?;
170
171        debug!("Acknowledged a user's google play subscription");
172
173        let expiry_info = self
174            .google_play_client
175            .get_subscription(&self.config, &request.purchase_token)
176            .await?;
177
178        account.billing_info.billing_platform = Some(BillingPlatform::new_play_sub(
179            &self.config,
180            &request.purchase_token,
181            expiry_info,
182        )?);
183
184        {
185            let mut db = self.index_db.lock().await;
186            let mut tx = ServerTx::begin(&mut db)?;
187            tx.google_play_ids
188                .insert(request.account_id.clone(), Owner(context.public_key))?;
189            tx.end()?;
190        }
191
192        self.release_subscription_profile::<UpgradeAccountGooglePlayError>(
193            context.public_key,
194            account,
195        )
196        .await?;
197
198        debug!("Successfully upgraded a user through a google play subscription. public_key");
199
200        Ok(UpgradeAccountGooglePlayResponse {})
201    }
202
203    pub async fn upgrade_account_stripe(
204        &self, context: RequestContext<UpgradeAccountStripeRequest>,
205    ) -> Result<UpgradeAccountStripeResponse, ServerError<UpgradeAccountStripeError>> {
206        let request = &context.request;
207
208        debug!("Attempting to upgrade the account tier of to premium");
209
210        let mut account = self.lock_subscription_profile(&context.public_key).await?;
211
212        if account.billing_info.is_premium() {
213            return Err(ClientError(UpgradeAccountStripeError::AlreadyPremium));
214        }
215
216        let maybe_user_info = account
217            .billing_info
218            .billing_platform
219            .and_then(|info| match info {
220                BillingPlatform::Stripe(stripe_info) => Some(stripe_info),
221                _ => None,
222            });
223
224        let user_info = self
225            .create_subscription(&context.public_key, &request.account_tier, maybe_user_info)
226            .await?;
227
228        account.billing_info.billing_platform = Some(BillingPlatform::Stripe(user_info));
229        self.release_subscription_profile::<UpgradeAccountStripeError>(context.public_key, account)
230            .await?;
231
232        debug!("Successfully upgraded the account tier of from free to premium");
233
234        Ok(UpgradeAccountStripeResponse {})
235    }
236
237    pub async fn get_subscription_info(
238        &self, context: RequestContext<GetSubscriptionInfoRequest>,
239    ) -> Result<GetSubscriptionInfoResponse, ServerError<GetSubscriptionInfoError>> {
240        let platform = self.read_billing_platform(&context.public_key).await?;
241        let subscription_info = platform.map(|info| match info {
242            BillingPlatform::Stripe(info) => SubscriptionInfo {
243                payment_platform: PaymentPlatform::Stripe { card_last_4_digits: info.last_4 },
244                period_end: info.expiration_time,
245            },
246            BillingPlatform::GooglePlay(info) => SubscriptionInfo {
247                payment_platform: PaymentPlatform::GooglePlay { account_state: info.account_state },
248                period_end: info.expiration_time,
249            },
250            BillingPlatform::AppStore(info) => SubscriptionInfo {
251                payment_platform: PaymentPlatform::AppStore { account_state: info.account_state },
252                period_end: info.expiration_time,
253            },
254        });
255        Ok(GetSubscriptionInfoResponse { subscription_info })
256    }
257
258    pub async fn get_subscription_info_v2(
259        &self, context: RequestContext<GetSubscriptionInfoRequestV2>,
260    ) -> Result<GetSubscriptionInfoResponseV2, ServerError<GetSubscriptionInfoError>> {
261        let platform = self.read_billing_platform(&context.public_key).await?;
262        let subscription_info = platform.map(|info| match info {
263            BillingPlatform::Stripe(info) => SubscriptionInfoV2 {
264                payment_platform: PaymentPlatformV2::Stripe { card_last_4_digits: info.last_4 },
265                period_end: info.expiration_time,
266            },
267            BillingPlatform::GooglePlay(info) => SubscriptionInfoV2 {
268                payment_platform: PaymentPlatformV2::GooglePlay {
269                    account_state: info.account_state,
270                },
271                period_end: info.expiration_time,
272            },
273            BillingPlatform::AppStore(info) => SubscriptionInfoV2 {
274                payment_platform: PaymentPlatformV2::AppStore { account_state: info.account_state },
275                period_end: info.expiration_time,
276            },
277        });
278        Ok(GetSubscriptionInfoResponseV2 { subscription_info })
279    }
280
281    async fn read_billing_platform(
282        &self, public_key: &PublicKey,
283    ) -> Result<Option<BillingPlatform>, ServerError<GetSubscriptionInfoError>> {
284        Ok(self
285            .index_db
286            .lock()
287            .await
288            .schema
289            .accounts
290            .get(&Owner(*public_key))
291            .ok_or(ClientError(GetSubscriptionInfoError::UserNotFound))?
292            .billing_info
293            .billing_platform
294            .clone())
295    }
296
297    pub async fn cancel_subscription(
298        &self, context: RequestContext<CancelSubscriptionRequest>,
299    ) -> Result<CancelSubscriptionResponse, ServerError<CancelSubscriptionError>> {
300        let mut account = self.lock_subscription_profile(&context.public_key).await?;
301
302        if account.billing_info.data_cap() == FREE_TIER_USAGE_SIZE {
303            return Err(ClientError(CancelSubscriptionError::NotPremium));
304        }
305
306        {
307            let mut lock = self.index_db.lock().await;
308            let mut tx = ServerTx::begin(&mut lock)?;
309            let db = &mut *tx;
310
311            let mut tree = ServerTree::new(
312                Owner(context.public_key),
313                &mut db.owned_files,
314                &mut db.shared_files,
315                &mut db.file_children,
316                &mut db.metas,
317            )?
318            .to_lazy();
319
320            let usage = tree.calculate_usage(Owner(context.public_key))?;
321
322            if usage > FREE_TIER_USAGE_SIZE {
323                debug!("Cannot downgrade user to free since they are over the data cap");
324                return Err(ClientError(CancelSubscriptionError::UsageIsOverFreeTierDataCap));
325            }
326        }
327
328        match account.billing_info.billing_platform {
329            None => {
330                return Err(internal!(
331                    "A user somehow has premium tier usage, but no billing information on redis. public_key: {:?}",
332                    context.public_key
333                ));
334            }
335            Some(BillingPlatform::GooglePlay(ref mut info)) => {
336                debug!("Canceling google play subscription of user");
337
338                if let GooglePlayAccountState::Canceled = &info.account_state {
339                    return Err(ClientError(CancelSubscriptionError::AlreadyCanceled));
340                }
341
342                self.google_play_client
343                    .cancel_subscription(&self.config, &info.purchase_token)
344                    .await?;
345
346                info.account_state = GooglePlayAccountState::Canceled;
347                debug!("Successfully canceled google play subscription of user");
348            }
349            Some(BillingPlatform::Stripe(ref mut info)) => {
350                debug!("Canceling stripe subscription of user");
351
352                self.stripe_client
353                    .cancel_subscription(&info.subscription_id.parse()?)
354                    .await
355                    .map_err::<ServerError<CancelSubscriptionError>, _>(|err| {
356                        internal!("{:?}", err)
357                    })?;
358
359                info.account_state = StripeAccountState::Canceled;
360
361                debug!("Successfully canceled stripe subscription");
362            }
363            Some(BillingPlatform::AppStore(_)) => {
364                return Err(ClientError(CancelSubscriptionError::CannotCancelForAppStore));
365            }
366        }
367
368        self.release_subscription_profile::<CancelSubscriptionError>(context.public_key, account)
369            .await?;
370
371        Ok(CancelSubscriptionResponse {})
372    }
373
374    pub async fn admin_set_user_tier(
375        &self, context: RequestContext<AdminSetUserTierRequest>,
376    ) -> Result<AdminSetUserTierResponse, ServerError<AdminSetUserTierError>> {
377        let request = &context.request;
378
379        {
380            let db = self.index_db.lock().await;
381
382            if !Self::is_admin::<AdminSetUserTierError>(
383                &db.schema,
384                &context.public_key,
385                &self.config.admin.admins,
386            )? {
387                return Err(ClientError(AdminSetUserTierError::NotPermissioned));
388            }
389        }
390
391        let public_key = self
392            .index_db
393            .lock()
394            .await
395            .schema
396            .usernames
397            .get(&request.username)
398            .ok_or(ClientError(AdminSetUserTierError::UserNotFound))?
399            .0;
400        let mut account = self.lock_subscription_profile(&public_key).await?;
401
402        let billing_config = &self.config.billing;
403
404        account.billing_info.billing_platform = match &request.info {
405            AdminSetUserTierInfo::Stripe {
406                customer_id,
407                customer_name,
408                payment_method_id,
409                last_4,
410                subscription_id,
411                expiration_time,
412                account_state,
413            } => Some(BillingPlatform::Stripe(StripeUserInfo {
414                customer_id: customer_id.to_string(),
415                customer_name: *customer_name,
416                price_id: billing_config.stripe.premium_price_id.to_string(),
417                payment_method_id: payment_method_id.to_string(),
418                last_4: last_4.to_string(),
419                subscription_id: subscription_id.to_string(),
420                expiration_time: *expiration_time,
421                account_state: account_state.clone(),
422            })),
423            AdminSetUserTierInfo::GooglePlay { purchase_token, expiration_time, account_state } => {
424                Some(BillingPlatform::GooglePlay(GooglePlayUserInfo {
425                    purchase_token: purchase_token.clone(),
426                    subscription_product_id: billing_config
427                        .google
428                        .premium_subscription_product_id
429                        .to_string(),
430                    subscription_offer_id: billing_config
431                        .google
432                        .premium_subscription_offer_id
433                        .to_string(),
434                    expiration_time: *expiration_time,
435                    account_state: account_state.clone(),
436                }))
437            }
438            AdminSetUserTierInfo::AppStore {
439                account_token,
440                original_transaction_id,
441                expiration_time,
442                account_state,
443            } => Some(BillingPlatform::AppStore(AppStoreUserInfo {
444                account_token: account_token.to_string(),
445                original_transaction_id: original_transaction_id.to_string(),
446                subscription_product_id: billing_config.apple.subscription_product_id.to_string(),
447                expiration_time: *expiration_time,
448                account_state: account_state.clone(),
449            })),
450            AdminSetUserTierInfo::Free => None,
451        };
452
453        account.username = request.username.clone();
454
455        self.release_subscription_profile::<AdminSetUserTierError>(public_key, account)
456            .await?;
457
458        Ok(AdminSetUserTierResponse {})
459    }
460
461    async fn save_subscription_profile<
462        T: Debug,
463        F: Fn(&mut Account) -> Result<(), ServerError<T>>,
464    >(
465        &self, public_key: &PublicKey, update_subscription_profile: F,
466    ) -> Result<(), ServerError<T>> {
467        let millis_between_lock_attempts = self.config.billing.time_between_lock_attempts;
468        loop {
469            match self.lock_subscription_profile(public_key).await {
470                Ok(ref mut sub_profile) => {
471                    update_subscription_profile(sub_profile)?;
472                    self.release_subscription_profile(*public_key, sub_profile.clone())
473                        .await?;
474                    break;
475                }
476                Err(ClientError(ExistingRequestPending)) => {
477                    tokio::time::sleep(millis_between_lock_attempts).await;
478                    continue;
479                }
480                Err(err) => {
481                    return Err(internal!("Cannot get billing lock in webhooks: {:#?}", err));
482                }
483            }
484        }
485
486        Ok(())
487    }
488
489    pub async fn stripe_webhooks(
490        &self, request_body: Bytes, stripe_sig: HeaderValue,
491    ) -> Result<(), ServerError<StripeWebhookError>> {
492        let event = self.verify_request_and_get_event(&request_body, stripe_sig)?;
493
494        let event_type = event.type_;
495        debug!(?event_type, "Verified stripe request");
496
497        match (&event.type_, &event.data.object) {
498            (stripe::EventType::InvoicePaymentFailed, stripe::EventObject::Invoice(invoice)) => {
499                if let Some(stripe::InvoiceBillingReason::SubscriptionCycle) =
500                    invoice.billing_reason
501                {
502                    let public_key = self.get_public_key_from_invoice(invoice).await?;
503                    let owner = Owner(public_key);
504
505                    debug!(
506                        ?owner,
507                        "User's tier is being reduced due to failed renewal payment in stripe"
508                    );
509
510                    self.save_subscription_profile(&public_key, |account| {
511                        if let Some(BillingPlatform::Stripe(ref mut info)) =
512                            account.billing_info.billing_platform
513                        {
514                            info.account_state = StripeAccountState::InvoiceFailed;
515
516                            Ok(())
517                        } else {
518                            Err(internal!(
519                                "Cannot get any billing info for user. public_key: {:?}",
520                                public_key
521                            ))
522                        }
523                    })
524                    .await?;
525                }
526            }
527            (stripe::EventType::InvoicePaid, stripe::EventObject::Invoice(invoice)) => {
528                if let Some(stripe::InvoiceBillingReason::SubscriptionCycle) =
529                    invoice.billing_reason
530                {
531                    let public_key = self.get_public_key_from_invoice(invoice).await?;
532                    let owner = Owner(public_key);
533
534                    debug!(
535                        ?owner,
536                        "User's subscription period_end is being changed after successful renewal",
537                    );
538
539                    let subscription_period_end = match &invoice.subscription {
540                        Some(stripe::Expandable::Object(subscription)) => {
541                            subscription.current_period_end
542                        }
543                        Some(stripe::Expandable::Id(subscription_id)) => {
544                            self.stripe_client
545                                .get_subscription(subscription_id)
546                                .await
547                                .map_err::<ServerError<StripeWebhookError>, _>(|err| {
548                                    internal!("{:?}", err)
549                                })?
550                                .current_period_end
551                        }
552                        None => {
553                            return Err(internal!(
554                                "The subscription should be included in this invoice: {:?}",
555                                invoice
556                            ));
557                        }
558                    };
559
560                    self.save_subscription_profile(&public_key, |account| {
561                        if let Some(BillingPlatform::Stripe(ref mut info)) =
562                            account.billing_info.billing_platform
563                        {
564                            info.account_state = StripeAccountState::Ok;
565                            info.expiration_time = subscription_period_end as u64;
566
567                            Ok(())
568                        } else {
569                            Err(internal!(
570                                "Cannot get any billing info for user. public_key: {:?}",
571                                public_key
572                            ))
573                        }
574                    })
575                    .await?;
576                }
577            }
578            (_, _) => {
579                return Err(internal!("Unexpected stripe event: {:?}", event.type_));
580            }
581        }
582
583        Ok(())
584    }
585
586    pub async fn google_play_notification_webhooks(
587        &self, request_body: Bytes, query_parameters: HashMap<String, String>,
588    ) -> Result<(), ServerError<GooglePlayWebhookError>> {
589        let notification = self
590            .verify_request_and_get_notification(request_body, query_parameters)
591            .await?;
592
593        if let Some(sub_notif) = notification.subscription_notification {
594            debug!(?sub_notif, "Notification is for a subscription");
595
596            let subscription = self
597                .google_play_client
598                .get_subscription(&self.config, &sub_notif.purchase_token)
599                .await
600                .map_err(|e| internal!("{:#?}", e))?;
601
602            let notification_type = sub_notif.notification_type();
603            if let NotificationType::SubscriptionPurchased = notification_type {
604                return Ok(());
605            }
606
607            let public_key = self
608                .get_public_key_from_subnotif(&sub_notif, &subscription, &notification_type)
609                .await?;
610            let owner = Owner(public_key);
611
612            debug!(
613                ?owner,
614                ?notification_type,
615                "Updating google play user's subscription profile to match new subscription state"
616            );
617
618            self.save_subscription_profile(&public_key, |account| {
619                if let Some(BillingPlatform::GooglePlay(ref mut info)) =
620                    account.billing_info.billing_platform
621                {
622                    match notification_type {
623                        NotificationType::SubscriptionRecovered
624                        | NotificationType::SubscriptionRestarted
625                        | NotificationType::SubscriptionRenewed => {
626                            info.account_state = GooglePlayAccountState::Ok;
627                            info.expiration_time = Self::get_subscription_period_end(
628                                &subscription,
629                                &notification_type,
630                                public_key,
631                            )?;
632                        }
633                        NotificationType::SubscriptionInGracePeriod => {
634                            info.account_state = GooglePlayAccountState::GracePeriod;
635                        }
636                        NotificationType::SubscriptionOnHold => {
637                            info.account_state = GooglePlayAccountState::OnHold;
638                            info.expiration_time = Self::get_subscription_period_end(
639                                &subscription,
640                                &notification_type,
641                                public_key,
642                            )?;
643                        }
644                        NotificationType::SubscriptionExpired
645                        | NotificationType::SubscriptionRevoked => {
646                            if info.purchase_token == sub_notif.purchase_token {
647                                account.billing_info.billing_platform = None
648                            } else {
649                                let old_purchase_token = &sub_notif.purchase_token;
650                                let new_purchase_token = &info.purchase_token;
651                                debug!(
652                                ?old_purchase_token,
653                                ?new_purchase_token,
654                                "Expired or revoked subscription was tied to an old purchase_token"
655                            );
656                            }
657                        }
658                        NotificationType::SubscriptionCanceled => {
659                            info.account_state = GooglePlayAccountState::Canceled;
660                            let cancellation_reason = &subscription.cancel_survey_result;
661                            let owner = Owner(public_key);
662                            debug!(?cancellation_reason, ?owner, "Subscription cancelled");
663                        }
664                        NotificationType::SubscriptionPriceChangeConfirmed
665                        | NotificationType::SubscriptionDeferred
666                        | NotificationType::SubscriptionPaused
667                        | NotificationType::SubscriptionPausedScheduleChanged
668                        | NotificationType::SubscriptionPurchased => {
669                            return Err(internal!(
670                                "Unexpected subscription notification: {:?}, public_key: {:?}",
671                                notification_type,
672                                public_key
673                            ))
674                        }
675                        NotificationType::Unknown => {
676                            return Err(internal!(
677                                "Unknown subscription change. public_key: {:?}",
678                                public_key
679                            ))
680                        }
681                    }
682
683                    Ok(())
684                } else {
685                    Err(internal!(
686                        "Cannot get any billing info for user. public_key: {:?}",
687                        public_key
688                    ))
689                }
690            })
691            .await?;
692        }
693
694        if let Some(test_notif) = notification.test_notification {
695            let version = &test_notif.version;
696            debug!(?version, "Test notification");
697        }
698
699        if let Some(otp_notif) = notification.one_time_product_notification {
700            return Err(internal!(
701                "Received a one time product notification although there are no registered one time products. one_time_product_notification: {:?}",
702                otp_notif
703            ));
704        }
705
706        Ok(())
707    }
708
709    pub async fn app_store_notification_webhook(
710        &self, body: Bytes,
711    ) -> Result<(), ServerError<AppStoreNotificationError>> {
712        let resp = Self::decode_verify_notification(&self.config.billing.apple, &body)?;
713
714        if let NotificationChange::Subscribed = resp.notification_type {
715            return Ok(());
716        } else if let NotificationChange::Test = resp.notification_type {
717            debug!(?resp, "This is a test notification.");
718            return Ok(());
719        }
720
721        let trans = Self::decode_verify_transaction(
722            &self.config.billing.apple,
723            &resp
724                .clone()
725                .data
726                .encoded_transaction_info
727                .ok_or(ClientError(AppStoreNotificationError::InvalidJWS))?,
728        )?;
729        let public_key = self.get_public_key_from_tx(&trans).await?;
730
731        let owner = Owner(public_key);
732        let maybe_username = &self
733            .index_db
734            .lock()
735            .await
736            .schema
737            .accounts
738            .get(&owner)
739            .map(|acc| acc.username.clone());
740
741        info!(
742            ?owner,
743            ?maybe_username,
744            ?resp.notification_type,
745            ?resp.subtype,
746            "Updating app store user's subscription profile to match new subscription state"
747        );
748
749        self.save_subscription_profile(&public_key, |account| {
750            if let Some(BillingPlatform::AppStore(ref mut info)) =
751                account.billing_info.billing_platform
752            {
753                match resp.notification_type {
754                    NotificationChange::DidFailToRenew => {
755                        info.account_state = if let Some(Subtype::GracePeriod) = resp.subtype {
756                            AppStoreAccountState::GracePeriod
757                        } else {
758                            AppStoreAccountState::FailedToRenew
759                        };
760                    }
761                    NotificationChange::Expired => {
762                        info.account_state = AppStoreAccountState::Expired;
763
764                        match resp.subtype {
765                            Some(Subtype::BillingRetry) => {
766                                info!(
767                                    ?owner,
768                                    ?resp,
769                                    "Subscription failed to renew due to billing issues."
770                                );
771                            }
772                            Some(Subtype::Voluntary) => {
773                                info!(?owner, ?resp, "Subscription cancelled");
774                            }
775                            _ => {
776                                return Err(internal!(
777                            "Unexpected subtype: {:?}, notification_type {:?}, public_key: {:?}",
778                            resp.subtype,
779                            resp.notification_type,
780                            public_key
781                        ))
782                            }
783                        }
784                    }
785                    NotificationChange::GracePeriodExpired => {
786                        info.account_state = AppStoreAccountState::Expired
787                    }
788                    NotificationChange::Refund => {
789                        info!(?resp, "A user has requested a refund.");
790                    }
791                    NotificationChange::RefundDeclined => {
792                        info!(?resp, "A user's refund request has been denied.");
793                    }
794                    NotificationChange::DidChangeRenewalStatus => match resp.subtype {
795                        Some(Subtype::AutoRenewEnabled) => {
796                            info.account_state = AppStoreAccountState::Ok;
797                            info.expiration_time = trans.expires_date;
798                        }
799                        Some(Subtype::AutoRenewDisabled) => {}
800                        _ => {
801                            return Err(internal!(
802                            "Unexpected subtype: {:?}, notification_type {:?}, public_key: {:?}",
803                            resp.subtype,
804                            resp.notification_type,
805                            public_key
806                        ))
807                        }
808                    },
809                    NotificationChange::RenewalExtended => {
810                        info.expiration_time = trans.expires_date
811                    }
812                    NotificationChange::DidRenew => {
813                        if let Some(Subtype::BillingRecovery) = resp.subtype {
814                            info.account_state = AppStoreAccountState::Ok;
815                        }
816                        info.expiration_time = trans.expires_date
817                    }
818                    NotificationChange::ConsumptionRequest
819                    | NotificationChange::Subscribed
820                    | NotificationChange::DidChangeRenewalPref
821                    | NotificationChange::OfferRedeemed
822                    | NotificationChange::PriceIncrease
823                    | NotificationChange::Revoke
824                    | NotificationChange::Test => {
825                        return Err(internal!(
826                            "Unexpected notification change: {:?} {:?}, public_key: {:?}",
827                            resp.notification_type,
828                            resp.subtype,
829                            public_key
830                        ))
831                    }
832                }
833
834                Ok(())
835            } else {
836                Err(internal!("Cannot get any billing info for user. public_key: {:?}", public_key))
837            }
838        })
839        .await?;
840
841        Ok(())
842    }
843}
844
845pub fn stringify_public_key(pk: &PublicKey) -> String {
846    base64::encode(pk.serialize_compressed())
847}
848
849#[derive(Debug)]
850pub enum StripeWebhookError {
851    VerificationError(String),
852    InvalidHeader(String),
853    InvalidBody(String),
854    ParseError(String),
855}
856
857#[derive(Debug)]
858pub enum LockBillingWorkflowError {
859    UserNotFound,
860    ExistingRequestPending,
861}
862
863#[derive(Debug)]
864pub enum GooglePlayWebhookError {
865    InvalidToken,
866    CannotRetrieveData,
867    CannotDecodePubSubData(DecodeError),
868    CannotRetrieveUserInfo,
869    CannotRetrievePublicKey,
870    CannotParseTime,
871}
872
873#[derive(Debug)]
874pub enum AppStoreNotificationError {
875    InvalidJWS,
876}