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