app-store-server-library 2.3.1

The Rust server library for the App Store Server API and App Store Server Notifications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
use std::collections::HashMap;
use std::fmt;
use chrono::{Utc};
use serde::{Serialize, Deserialize};
use reqwest::{Client, RequestBuilder, Method};
use jsonwebtoken::{Header, Algorithm, encode, EncodingKey};
use reqwest::header::HeaderMap;
use crate::primitives::check_test_notification_response::CheckTestNotificationResponse;
use crate::primitives::consumption_request::ConsumptionRequest;
use crate::primitives::environment::Environment;
use crate::primitives::extend_renewal_date_request::ExtendRenewalDateRequest;
use crate::primitives::extend_renewal_date_response::ExtendRenewalDateResponse;
use crate::primitives::history_response::HistoryResponse;
use crate::primitives::mass_extend_renewal_date_request::MassExtendRenewalDateRequest;
use crate::primitives::mass_extend_renewal_date_status_response::MassExtendRenewalDateStatusResponse;
use crate::primitives::notification_history_request::NotificationHistoryRequest;
use crate::primitives::notification_history_response::NotificationHistoryResponse;
use crate::primitives::order_lookup_response::OrderLookupResponse;
use crate::primitives::refund_history_response::RefundHistoryResponse;
use crate::primitives::send_test_notification_response::SendTestNotificationResponse;
use crate::primitives::status::Status;
use crate::primitives::status_response::StatusResponse;
use crate::primitives::transaction_history_request::TransactionHistoryRequest;
use crate::primitives::transaction_info_response::TransactionInfoResponse;

#[derive(Debug, Serialize, Deserialize)]
pub struct APIException {
    pub http_status_code: u16,
    pub api_error: Option<APIError>,
    pub raw_api_error: Option<i64>,
    pub error_message: Option<String>,
}

impl fmt::Display for APIException {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "APIException: HTTP Status Code {}", self.http_status_code)?;
        if let Some(api_error) = &self.api_error {
            write!(f, ", API Error: {:?}", api_error)?;
        }
        if let Some(raw_api_error) = &self.raw_api_error {
            write!(f, ", Raw API Error: {}", raw_api_error)?;
        }
        if let Some(error_message) = &self.error_message {
            write!(f, ", Error Message: {}", error_message)?;
        }
        Ok(())
    }
}

#[cfg(test)]
use http::Response;
use serde_json::Value;
use crate::primitives::error_payload::{APIError, ErrorPayload};

impl std::error::Error for APIException {}

#[cfg(test)]
type RequestVerifier = fn(&reqwest::Request, Option<&[u8]>) -> ();
#[cfg(test)]
type RequestOverride = dyn Fn(&reqwest::Request, Option<&[u8]>) -> http::Response<Vec<u8>>;

pub struct AppStoreServerAPIClient {
    base_url: String,
    signing_key: Vec<u8>,
    key_id: String,
    issuer_id: String,
    bundle_id: String,
    client: Client,
    #[cfg(test)]
    request_override: Box<RequestOverride>,
}

impl AppStoreServerAPIClient {
    #[cfg(not(test))]
    pub fn new(signing_key: Vec<u8>, key_id: &str, issuer_id: &str, bundle_id: &str, environment: Environment) -> Self {
        let base_url = environment.base_url();
        let client = Client::new();
        Self { base_url, signing_key, key_id: key_id.to_string(), issuer_id: issuer_id.to_string(), bundle_id: bundle_id.to_string(), client }
    }

    #[cfg(test)]
    pub fn new(signing_key: Vec<u8>, key_id: &str, issuer_id: &str, bundle_id: &str, environment: Environment, request_override: Box<RequestOverride>) -> Self {
        let base_url = environment.base_url();
        let client = Client::new();
        Self { base_url, signing_key, key_id: key_id.to_string(), issuer_id: issuer_id.to_string(), bundle_id: bundle_id.to_string(), client, request_override}
    }

    fn generate_token(&self) -> String {
        let future_time = Utc::now() + chrono::Duration::minutes(5);
        let key_id = (&self.key_id).to_string();

        let mut header = Header::new(Algorithm::ES256);
        header.kid = Some(key_id);

        let claims = Claims {
            bid: &self.bundle_id,
            iss: &self.issuer_id,
            aud: "appstoreconnect-v1",
            exp: future_time.timestamp(),
        };

        encode(&header, &claims, &EncodingKey::from_ec_pem(self.signing_key.as_slice()).unwrap()).unwrap()
    }

    fn build_request(&self, path: &str, method: Method) -> RequestBuilder {
        let url = format!("{}{}", self.base_url, path);

        let mut headers = HeaderMap::new();
        headers.append("User-Agent", "app-store-server-library/rust/1.0.0".parse().unwrap());
        headers.append("Authorization", format!("Bearer {}", self.generate_token()).parse().unwrap());
        headers.append("Accept", "application/json".parse().unwrap());

        self.client
            .request(method, url)
            .headers(headers)
    }

    async fn make_request_with_response_body<Res>(&self, request: RequestBuilder) -> Result<Res, APIException>
        where
            Res: for<'de> Deserialize<'de>
    {
        let response = self.make_request(request).await?;
        let json_result = response.json::<Res>().await.map_err(|_| APIException {
            http_status_code: 500,
            api_error: None,
            raw_api_error: None,
            error_message: Some("Failed to deserialize response JSON".to_string()),
        })?;
        Ok(json_result)
    }

    async fn make_request_without_response_body(&self, request: RequestBuilder) -> Result<(), APIException> {
        let _ = self.make_request(request).await?;
        Ok(())
    }

    #[cfg(not(test))]
    async fn make_request(&self, request: RequestBuilder) -> Result<reqwest::Response, APIException> {
        let response = request.send().await;

        match response {
            Ok(response) => {
                let status_code = response.status().as_u16();

                if status_code >= 200 && status_code < 300 {
                    Ok(response)
                } else if let Ok(json_error) = response.json::<ErrorPayload>().await {
                    let error_code = json_error.error_code.clone();
                    let error_message = json_error.error_message.clone();
                    Err(APIException {
                        http_status_code: status_code,
                        api_error: error_code,
                        raw_api_error: (&json_error).raw_error_code(),
                        error_message: error_message,
                    })
                } else {
                    Err(APIException {
                        http_status_code: 500,
                        api_error: None,
                        raw_api_error: None,
                        error_message: Some("Failed to send HTTP request".to_string()),
                    })
                }
            }
            Err(_) => Err(APIException {
                http_status_code: 500,
                api_error: None,
                raw_api_error: None,
                error_message: Some("Failed to send HTTP request".to_string()),
            }),
        }
    }

    #[cfg(test)]
    async fn make_request(&self, request: RequestBuilder) -> Result<Response<Vec<u8>>, APIException>
    {
        let request = request.build().unwrap();
        let body_encoded = match request.body() {
            None => None,
            Some(body) => body.as_bytes()
        };
        let response = (self.request_override)(&request, body_encoded);

        let status_code = response.status().as_u16();

        if status_code >= 200 && status_code < 300 {
            Ok(response)
        } else if let Ok(json_error) = response.json::<ErrorPayload>().await {
            let error_code = json_error.error_code.clone();
            let error_message = json_error.error_message.clone();

            Err(APIException {
                http_status_code: status_code,
                api_error: error_code,
                raw_api_error: (&json_error).raw_error_code(),
                error_message: error_message,
            })
        } else {
            Err(APIException {
                http_status_code: 500,
                api_error: None,
                raw_api_error: None,
                error_message: Some("Failed to send HTTP request".to_string()),
            })
        }
    }

    /// Uses a subscription's product identifier to extend the renewal date for all of its eligible active subscribers.
    ///
    /// [Documentation](https://developer.apple.com/documentation/appstoreserverapi/extend_subscription_renewal_dates_for_all_active_subscribers)
    ///
    /// # Arguments
    ///
    /// * `mass_extend_renewal_date_request` - The request body for extending a subscription renewal date for all of its active subscribers.
    ///
    /// # Returns
    ///
    /// A response that indicates the server successfully received the subscription-renewal-date extension request.
    ///
    /// # Errors
    ///
    /// Throws an `APIException` if a response was returned indicating the request could not be processed.
    pub async fn extend_renewal_date_for_all_active_subscribers(&self, mass_extend_renewal_date_request: &MassExtendRenewalDateRequest) -> Result<MassExtendRenewalDateStatusResponse, APIException> {
        let req = self.build_request("/inApps/v1/subscriptions/extend/mass", Method::POST)
            .json(&mass_extend_renewal_date_request);
        self.make_request_with_response_body(req).await
    }

    /// Extends the renewal date of a customer's active subscription using the original transaction identifier.
    ///
    /// [Documentation](https://developer.apple.com/documentation/appstoreserverapi/extend_a_subscription_renewal_date)
    ///
    /// # Arguments
    ///
    /// * `original_transaction_id` - The original transaction identifier of the subscription receiving a renewal date extension.
    /// * `extend_renewal_date_request` - The request body containing subscription-renewal-extension data.
    ///
    /// # Returns
    ///
    /// A response that indicates whether an individual renewal-date extension succeeded, and related details.
    ///
    /// # Errors
    ///
    /// Returns an `APIError` if the request could not be processed.
    pub async fn extend_subscription_renewal_date(&self, original_transaction_id: &str, extend_renewal_date_request: &ExtendRenewalDateRequest) -> Result<ExtendRenewalDateResponse, APIException> {
        let path = format!("/inApps/v1/subscriptions/extend/{}", original_transaction_id);
        let req = self.build_request(path.as_str(), Method::PUT)
            .json(&extend_renewal_date_request);
        self.make_request_with_response_body(req).await
    }

    /// Get the statuses for all of a customer's auto-renewable subscriptions in your app.
    ///
    /// [Documentation](https://developer.apple.com/documentation/appstoreserverapi/get_all_subscription_statuses)
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
    /// * `status` - An optional filter that indicates the status of subscriptions to include in the response.
    ///
    /// # Returns
    ///
    /// A response that contains status information for all of a customer's auto-renewable subscriptions in your app.
    ///
    /// # Errors
    ///
    /// Returns an `APIError` if the request could not be processed.
    pub async fn get_all_subscription_statuses(&self, transaction_id: &str, status: Option<&Vec<Status>>) -> Result<StatusResponse, APIException> {
        let mut query_parameters: Vec<(&str, String)> = vec![];
        if let Some(status) = status {
            for item in status {
                let value = ("status", item.raw_value().to_string());
                query_parameters.push(value);
            }
        }

        let path = format!("/inApps/v1/subscriptions/{}", transaction_id);
        let req = self.build_request(path.as_str(), Method::GET)
            .query(&query_parameters);
        self.make_request_with_response_body(req).await
    }

    /// Get a paginated list of all of a customer's refunded in-app purchases for your app.
    ///
    /// [Apple Documentation](https://developer.apple.com/documentation/appstoreserverapi/get_refund_history)
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
    /// * `revision` - A token you provide to get the next set of up to 20 transactions. All responses include a revision token. Use the revision token from the previous `RefundHistoryResponse`.
    ///
    /// # Returns
    ///
    /// A result containing either the response that contains status information for all of a customer's auto-renewable subscriptions in your app, or an `APIError` if the request could not be processed.
    ///
    /// # Errors
    ///
    /// * `RefundHistoryNotFoundError` (Status Code: 4040008) - An error that indicates that the test notification token is expired or the test notification status isn’t available.
    /// * `RefundHistoryRequestNotFoundError` (Status Code: 4040009) - An error that indicates the server didn't find a subscription-renewal-date extension request for the request identifier and product identifier you provided.
    /// * `RefundHistoryServerError` (Status Code: 5000000) - An error that indicates a server error occurred during the request processing.
    ///
    pub async fn get_refund_history(&self, transaction_id: &str, revision: &str) -> Result<RefundHistoryResponse, APIException> {
        let mut query_parameters: HashMap<&str, &str> = HashMap::new();
        if !revision.is_empty() {
            query_parameters.insert("revision", revision);
        }
        let path = format!("/inApps/v2/refund/lookup/{}", transaction_id);
        let req = self.build_request(path.as_str(), Method::GET)
            .query(&query_parameters);
        self.make_request_with_response_body(req).await
    }

    /// Checks whether a renewal date extension request completed, and provides the final count of successful or failed extensions.
    ///
    /// [Apple Documentation](https://developer.apple.com/documentation/appstoreserverapi/get_status_of_subscription_renewal_date_extensions)
    ///
    /// # Arguments
    ///
    /// * `request_identifier` - The UUID that represents your request to the Extend Subscription Renewal Dates for All Active Subscribers endpoint.
    /// * `product_id` - The product identifier of the auto-renewable subscription that you request a renewal-date extension for.
    ///
    /// # Returns
    ///
    /// A result containing either the response that indicates the current status of a request to extend the subscription renewal date to all eligible subscribers, or an `APIError` if the request could not be processed.
    ///
    /// # Errors
    ///
    /// * `SubscriptionRenewalDateStatusNotFoundError` (Status Code: 4040009) - An error that indicates the server didn't find a subscription-renewal-date extension request for the request identifier and product identifier you provided.
    /// * `SubscriptionRenewalDateStatusServerError` (Status Code: 5000000) - An error that indicates a server error occurred during the request processing.
    ///
    pub async fn get_status_of_subscription_renewal_date_extensions(&self, request_identifier: &str, product_id: &str) -> Result<MassExtendRenewalDateStatusResponse, APIException> {
        let path = format!("/inApps/v1/subscriptions/extend/mass/{}/{}", product_id, request_identifier);
        let req = self.build_request(path.as_str(), Method::GET);
        self.make_request_with_response_body(req).await
    }

    /// Check the status of the test App Store server notification sent to your server.
    ///
    /// [Apple Documentation](https://developer.apple.com/documentation/appstoreserverapi/get_test_notification_status)
    ///
    /// # Arguments
    ///
    /// * `test_notification_token` - The test notification token received from the Request a Test Notification endpoint.
    ///
    /// # Returns
    ///
    /// A result containing either the response that contains the contents of the test notification sent by the App Store server and the result from your server, or an `APIError` if the request could not be processed.
    ///
    /// # Errors
    ///
    /// * `TestNotificationNotFoundError` (Status Code: 4040008) - An error that indicates that the test notification token is expired or the test notification status isn’t available.
    /// * `TestNotificationServerError` (Status Code: 5000000) - An error that indicates a server error occurred during the request processing.
    ///
    pub async fn get_test_notification_status(
        &self,
        test_notification_token: &str,
    ) -> Result<CheckTestNotificationResponse, APIException> {
        let path = format!("/inApps/v1/notifications/test/{}", test_notification_token);
        let req = self.build_request(path.as_str(), Method::GET);
        self.make_request_with_response_body(req).await
    }

    /// Get the transaction history for a given transaction ID.
    ///
    /// This method is deprecated. Please use `get_transaction_history_with_version` instead.
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The identifier of the transaction to retrieve the history for.
    /// * `revision` - An optional revision string to specify the starting point of the transaction history.
    /// * `transaction_history_request` - The request object containing additional parameters for the transaction history.
    ///
    /// # Returns
    ///
    /// A response that contains the transaction history for the given transaction ID.
    ///
    /// # Errors
    ///
    /// Returns an `APIException` if the request could not be processed.
    #[deprecated(note = "Use `get_transaction_history_with_version` instead.")]
    pub async fn get_transaction_history(
        &self,
        transaction_id: &str,
        revision: Option<&str>,
        transaction_history_request: TransactionHistoryRequest,
    ) -> Result<HistoryResponse, APIException> {
        self.get_transaction_history_with_version(transaction_id, revision, &transaction_history_request, GetTransactionHistoryVersion::V1).await
    }

    /// Get a list of notifications that the App Store server attempted to send to your server.
    ///
    /// [Apple Documentation](https://developer.apple.com/documentation/appstoreserverapi/get_notification_history)
    ///
    /// # Arguments
    ///
    /// * `pagination_token` - An optional token you use to get the next set of up to 20 notification history records. All responses that have more records available include a paginationToken. Omit this parameter the first time you call this endpoint.
    /// * `notification_history_request` - The request body that includes the start and end dates, and optional query constraints.
    ///
    /// # Returns
    ///
    /// A response that contains the App Store Server Notifications history for your app.
    ///
    /// # Errors
    ///
    /// * `NotificationHistoryNotFoundError` (Status Code: 4040008) - An error that indicates that the notification history is not found.
    /// * `NotificationHistoryServerError` (Status Code: 5000000) - An error that indicates a server error occurred during the request processing.
    ///
    pub async fn get_notification_history(
        &self,
        pagination_token: &str,
        notification_history_request: &NotificationHistoryRequest,
    ) -> Result<NotificationHistoryResponse, APIException> {
        let mut query_parameters: HashMap<&str, &str> = HashMap::new();
        if !pagination_token.is_empty() {
            query_parameters.insert("paginationToken", pagination_token);
        }

        let req = self.build_request("/inApps/v1/notifications/history", Method::POST)
            .query(&query_parameters)
            .json(&notification_history_request);
        self.make_request_with_response_body(req).await
    }

    /// Get a customer's in-app purchase transaction history for your app.
    ///
    /// [Apple Documentation](https://developer.apple.com/documentation/appstoreserverapi/get_transaction_history)
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
    /// * `revision` - A token you provide to get the next set of up to 20 transactions. All responses include a revision token. Note: For requests that use the revision token, include the same query parameters from the initial request. Use the revision token from the previous HistoryResponse.
    /// * `transaction_history_request` - The request body that includes the start and end dates, and optional query constraints.
    ///
    /// # Returns
    ///
    /// A response that contains the customer's transaction history for an app.
    ///
    /// # Errors
    ///
    /// * `TransactionHistoryNotFoundError` (Status Code: 4040010) - An error that indicates a transaction identifier wasn't found.
    /// * `TransactionHistoryServerError` (Status Code: 5000000) - An error that indicates a server error occurred during the request processing.
    ///
    pub async fn get_transaction_history_with_version(
        &self,
        transaction_id: &str,
        revision: Option<&str>,
        transaction_history_request: &TransactionHistoryRequest,
        version: GetTransactionHistoryVersion,
    ) -> Result<HistoryResponse, APIException> {
        let mut query_parameters: Vec<(&str, Value)> = vec![];

        if let Some(rev) = revision {
            query_parameters.push(("revision", rev.into()));
        }

        if let Some(start_date) = transaction_history_request.start_date {
            let start_date = start_date.timestamp_millis().to_string();
            query_parameters.push(("startDate", start_date.into()));
        }

        if let Some(end_date) = transaction_history_request.end_date {
            let end_date = end_date.timestamp_millis().to_string();
            query_parameters.push(("endDate", end_date.into()));
        }

        if let Some(product_ids) = &transaction_history_request.product_ids {
            for item in product_ids {
                query_parameters.push(("productId", item.as_str().into()));
            }
        }

        if let Some(product_types) = &transaction_history_request.product_types {
            for item in product_types {
                query_parameters.push(("productType", item.raw_value().to_string().into()));
            }
        }

        if let Some(sort) = &transaction_history_request.sort {
            query_parameters.push(("sort", sort.raw_value().to_string().into()));
        }

        if let Some(subscription_group_ids) = &transaction_history_request.subscription_group_identifiers {
            for item in subscription_group_ids {
                query_parameters.push(("subscriptionGroupIdentifier", item.as_str().into()));
            }
        }

        if let Some(ownership_type) = &transaction_history_request.in_app_ownership_type {
            query_parameters.push(("inAppOwnershipType", ownership_type.raw_value().to_string().into()));
        }

        if let Some(revoked) = &transaction_history_request.revoked {
            query_parameters.push(("revoked", revoked.to_string().into()));
        }

        let path = format!("/inApps/{}/history/{}", version.as_str(), transaction_id);
        let req = self.build_request(path.as_str(), Method::GET)
            .query(&query_parameters);
        self.make_request_with_response_body(req).await
    }

    /// Get information about a single transaction for your app.
    ///
    /// [Documentation](https://developer.apple.com/documentation/appstoreserverapi/get_transaction_info)
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
    ///
    /// # Returns
    ///
    /// A response that contains signed transaction information for a single transaction.
    ///
    /// # Errors
    ///
    /// Returns an `APIException` if the request could not be processed.
    pub async fn get_transaction_info(&self, transaction_id: &str) -> Result<TransactionInfoResponse, APIException> {
        let path = format!("/inApps/v1/transactions/{}", transaction_id);
        let req = self.build_request(path.as_str(), Method::GET);
        self.make_request_with_response_body(req).await
    }

    /// Get a customer's in-app purchases from a receipt using the order ID.
    ///
    /// [Documentation](https://developer.apple.com/documentation/appstoreserverapi/look_up_order_id)
    ///
    /// # Arguments
    ///
    /// * `order_id` - The order ID for in-app purchases that belong to the customer.
    ///
    /// # Returns
    ///
    /// A response that includes the order lookup status and an array of signed transactions for the in-app purchases in the order.
    ///
    /// # Errors
    ///
    /// Returns an `APIException` if the request could not be processed.
    pub async fn look_up_order_id(&self, order_id: &str) -> Result<OrderLookupResponse, APIException> {
        let path = format!("/inApps/v1/lookup/{}", order_id);
        let req = self.build_request(path.as_str(), Method::GET);
        self.make_request_with_response_body(req).await
    }

    /// Ask App Store Server Notifications to send a test notification to your server.
    ///
    /// [Documentation](https://developer.apple.com/documentation/appstoreserverapi/request_a_test_notification)
    ///
    /// # Returns
    ///
    /// A response that contains the test notification token.
    ///
    /// # Errors
    ///
    /// Returns an `APIException` if the request could not be processed.
    pub async fn request_test_notification(&self) -> Result<SendTestNotificationResponse, APIException> {
        let path = "/inApps/v1/notifications/test";
        let req = self.build_request(path, Method::POST);
        self.make_request_with_response_body(req).await
    }

    /// Send consumption information about a consumable in-app purchase to the App Store after your server receives a consumption request notification.
    ///
    /// [Documentation](https://developer.apple.com/documentation/appstoreserverapi/send_consumption_information)
    ///
    /// # Arguments
    ///
    /// * `transaction_id` - The transaction identifier for which you're providing consumption information.
    /// * `consumption_request` - The request body containing consumption information.
    ///
    /// # Errors
    ///
    /// Returns an `APIException` if the request could not be processed.
    pub async fn send_consumption_data(&self, transaction_id: &str, consumption_request: &ConsumptionRequest) -> Result<(), APIException> {
        let path = format!("/inApps/v1/transactions/consumption/{}", transaction_id);
        let req = self.build_request(path.as_str(), Method::PUT)
            .json(consumption_request);
        self.make_request_without_response_body(req).await
    }
}

/// Represents the version of the Get Transaction History endpoint to use.
#[derive(Debug)]
pub enum GetTransactionHistoryVersion {
    #[deprecated(note = "Version v1 is deprecated, use v2 instead.")]
    V1,
    V2,
}

impl GetTransactionHistoryVersion {
    /// Converts the enum variant to its corresponding string representation.
    pub fn as_str(&self) -> &str {
        match self {
            GetTransactionHistoryVersion::V1 => "v1",
            GetTransactionHistoryVersion::V2 => "v2",
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct Claims<'a> {
    bid: &'a str,
    iss: &'a str,
    aud: &'a str,
    exp: i64,
}

#[cfg(test)]
use serde::de::DeserializeOwned;

#[cfg(test)]
trait ResponseExt {
    async fn json<T: DeserializeOwned>(self) -> serde_json::Result<T>;
}

#[cfg(test)]
impl ResponseExt for Response<Vec<u8>> {
    async fn json<T: DeserializeOwned>(self) -> serde_json::Result<T> {
        let body = std::str::from_utf8(self.body().as_slice()).unwrap();
        serde_json::from_str(body)
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use base64::Engine;
    use http::StatusCode;
    use serde_json::Value;
    use chrono::DateTime;
    use uuid::Uuid;
    use base64::prelude::BASE64_STANDARD_NO_PAD;
    use crate::primitives::account_tenure::AccountTenure;
    use crate::primitives::consumption_status::ConsumptionStatus;
    use crate::primitives::delivery_status::DeliveryStatus;
    use crate::primitives::extend_reason_code::ExtendReasonCode;
    use crate::primitives::in_app_ownership_type::InAppOwnershipType;
    use crate::primitives::last_transactions_item::LastTransactionsItem;
    use crate::primitives::lifetime_dollars_purchased::LifetimeDollarsPurchased;
    use crate::primitives::lifetime_dollars_refunded::LifetimeDollarsRefunded;
    use crate::primitives::notification_history_response_item::NotificationHistoryResponseItem;
    use crate::primitives::notification_type_v2::NotificationTypeV2;
    use crate::primitives::order_lookup_status::OrderLookupStatus;
    use crate::primitives::platform::Platform;
    use crate::primitives::play_time::PlayTime;
    use crate::primitives::refund_preference::RefundPreference;
    use crate::primitives::send_attempt_item::SendAttemptItem;
    use crate::primitives::send_attempt_result::SendAttemptResult;
    use crate::primitives::subscription_group_identifier_item::SubscriptionGroupIdentifierItem;
    use crate::primitives::subtype::Subtype;
    use crate::primitives::transaction_history_request::{Order, ProductType};
    use crate::primitives::user_status::UserStatus;
    use super::*;

    #[tokio::test]
    async fn test_extend_renewal_date_for_all_active_subscribers() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/extendRenewalDateForAllActiveSubscribersResponse.json", StatusCode::OK, Some(|req, body| {
            assert_eq!(Method::POST, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/subscriptions/extend/mass", req.url().as_str());

            let decoded_json: HashMap<&str, Value> = serde_json::from_slice(body.unwrap()).unwrap();
            assert_eq!(45, decoded_json.get("extendByDays").unwrap().as_u64().unwrap());
            assert_eq!(1, decoded_json.get("extendReasonCode").unwrap().as_u64().unwrap());
            assert_eq!("fdf964a4-233b-486c-aac1-97d8d52688ac", decoded_json.get("requestIdentifier").unwrap().as_str().unwrap());
            assert_eq!(vec!["USA", "MEX"], decoded_json.get("storefrontCountryCodes").unwrap().as_array().unwrap().to_vec());
            assert_eq!("com.example.productId", decoded_json.get("productId").unwrap().as_str().unwrap());
        }));

        let dto = MassExtendRenewalDateRequest {
            extend_by_days: 45,
            extend_reason_code: ExtendReasonCode::CustomerSatisfaction,
            request_identifier: "fdf964a4-233b-486c-aac1-97d8d52688ac".to_string(),
            storefront_country_codes: vec!["USA".to_string(), "MEX".to_string()],
            product_id: "com.example.productId".to_string(),
        };

        let response = client.extend_renewal_date_for_all_active_subscribers(&dto).await.unwrap();
        assert_eq!("758883e8-151b-47b7-abd0-60c4d804c2f5", response.request_identifier.unwrap().as_str());
    }

    #[tokio::test]
    async fn test_extend_subscription_renewal_date() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/extendSubscriptionRenewalDateResponse.json", StatusCode::OK, Some(|req, body| {
            assert_eq!(Method::PUT, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/subscriptions/extend/4124214", req.url().as_str());

            let decoded_json: HashMap<&str, Value> = serde_json::from_slice(body.unwrap()).unwrap();
            assert_eq!(45, decoded_json.get("extendByDays").unwrap().as_u64().unwrap());
            assert_eq!(1, decoded_json.get("extendReasonCode").unwrap().as_u64().unwrap());
            assert_eq!("fdf964a4-233b-486c-aac1-97d8d52688ac", decoded_json.get("requestIdentifier").unwrap().as_str().unwrap());
        }));

        let extend_renewal_date_request = ExtendRenewalDateRequest {
            extend_by_days: Some(45),
            extend_reason_code: Some(ExtendReasonCode::CustomerSatisfaction),
            request_identifier: Some("fdf964a4-233b-486c-aac1-97d8d52688ac".to_string()),
        };

        let response = client.extend_subscription_renewal_date("4124214", &extend_renewal_date_request).await.unwrap();
        assert_eq!("2312412", response.original_transaction_id.unwrap().as_str());
        assert_eq!("9993", response.web_order_line_item_id.unwrap().as_str());
        assert_eq!(true, response.success.unwrap());
        assert_eq!(1698148900, response.effective_date.unwrap().timestamp());
    }

    #[tokio::test]
    async fn test_get_all_subscription_statuses() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/getAllSubscriptionStatusesResponse.json", StatusCode::OK, Some(|req, _body| {
            assert_eq!(Method::GET, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/subscriptions/4321?status=2&status=1", req.url().as_str());
            assert!(req.body().is_none());
        }));

        let statuses = vec![Status::Expired, Status::Active];
        let response = client.get_all_subscription_statuses("4321", Some(&statuses)).await.unwrap();

        assert_eq!(Environment::LocalTesting, response.environment.unwrap());
        assert_eq!("com.example", response.bundle_id.as_str());
        assert_eq!(5454545, response.app_apple_id.unwrap());

        let item = SubscriptionGroupIdentifierItem {
            subscription_group_identifier: Some("sub_group_one".to_string()),
            last_transactions: Some(vec![
                LastTransactionsItem {
                    status: Status::Active.into(),
                    original_transaction_id: "3749183".to_string().into(),
                    signed_transaction_info: "signed_transaction_one".to_string().into(),
                    signed_renewal_info: "signed_renewal_one".to_string().into(),
                },
                LastTransactionsItem {
                    status: Status::Revoked.into(),
                    original_transaction_id: "5314314134".to_string().into(),
                    signed_transaction_info: "signed_transaction_two".to_string().into(),
                    signed_renewal_info: "signed_renewal_two".to_string().into(),
                },
            ]),
        };

        let second_item = SubscriptionGroupIdentifierItem {
            subscription_group_identifier: "sub_group_two".to_string().into(),
            last_transactions: vec![
                LastTransactionsItem {
                    status: Status::Expired.into(),
                    original_transaction_id: "3413453".to_string().into(),
                    signed_transaction_info: "signed_transaction_three".to_string().into(),
                    signed_renewal_info: "signed_renewal_three".to_string().into(),
                },
            ].into(),
        };

        assert_eq!(vec![item, second_item], response.data);
    }

    #[tokio::test]
    async fn test_get_refund_history() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/getRefundHistoryResponse.json", StatusCode::OK, Some(|req, _body| {
            assert_eq!(Method::GET, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v2/refund/lookup/555555?revision=revision_input", req.url().as_str());
            assert!(req.body().is_none());
        }));

        let response = client.get_refund_history("555555", "revision_input").await.unwrap();

        assert_eq!(vec!["signed_transaction_one", "signed_transaction_two"], response.signed_transactions);
        assert_eq!("revision_output", response.revision);
        assert_eq!(true, response.has_more);
    }

    #[tokio::test]
    async fn test_get_status_of_subscription_renewal_date_extensions() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/getStatusOfSubscriptionRenewalDateExtensionsResponse.json", StatusCode::OK, Some(|req, _body| {
            assert_eq!(Method::GET, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/subscriptions/extend/mass/20fba8a0-2b80-4a7d-a17f-85c1854727f8/com.example.product", req.url().as_str());
            assert!(req.body().is_none());
        }));

        let response = client.get_status_of_subscription_renewal_date_extensions("com.example.product", "20fba8a0-2b80-4a7d-a17f-85c1854727f8").await.unwrap();

        assert_eq!("20fba8a0-2b80-4a7d-a17f-85c1854727f8", response.request_identifier.unwrap().as_str());
        assert_eq!(true, response.complete.unwrap());
        assert_eq!(1698148900, response.complete_date.unwrap().timestamp());
        assert_eq!(30, response.succeeded_count.unwrap());
        assert_eq!(2, response.failed_count.unwrap());
    }

    #[tokio::test]
    async fn test_get_test_notification_status() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/getTestNotificationStatusResponse.json", StatusCode::OK, Some(|req, _body| {
            assert_eq!(Method::GET, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/notifications/test/8cd2974c-f905-492a-bf9a-b2f47c791d19", req.url().as_str());
            assert!(req.body().is_none());
        }));

        let response = client.get_test_notification_status("8cd2974c-f905-492a-bf9a-b2f47c791d19").await.unwrap();
        assert_eq!("signed_payload", response.signed_payload.unwrap());

        let send_attempt_items = vec![
            SendAttemptItem {
                attempt_date: DateTime::from_timestamp(1698148900, 0),
                send_attempt_result: SendAttemptResult::NoResponse.into(),
            },
            SendAttemptItem {
                attempt_date: DateTime::from_timestamp(1698148950, 0),
                send_attempt_result: SendAttemptResult::Success.into(),
            },
        ];
        assert_eq!(send_attempt_items, response.send_attempts.unwrap());
    }

    #[tokio::test]
    async fn test_get_notification_history() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/getNotificationHistoryResponse.json", StatusCode::OK, Some(|req, body| {
            assert_eq!(Method::POST, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/notifications/history?paginationToken=a036bc0e-52b8-4bee-82fc-8c24cb6715d6", req.url().as_str());

            let decoded_json: HashMap<&str, Value> = serde_json::from_slice(body.unwrap()).unwrap();
            assert_eq!(1698148900000, decoded_json["startDate"].as_i64().unwrap());
            assert_eq!(1698148950000, decoded_json["endDate"].as_i64().unwrap());
            assert_eq!("SUBSCRIBED", decoded_json["notificationType"].as_str().unwrap());
            assert_eq!("INITIAL_BUY", decoded_json["notificationSubtype"].as_str().unwrap());
            assert_eq!("999733843", decoded_json["transactionId"].as_str().unwrap());
            assert_eq!(true, decoded_json["onlyFailures"].as_bool().unwrap());
        }));

        let notification_history_request = NotificationHistoryRequest {
            start_date:DateTime::from_timestamp(1698148900, 0),
            end_date:DateTime::from_timestamp(1698148950, 0),
            notification_type: NotificationTypeV2::Subscribed.into(),
            notification_subtype: Subtype::InitialBuy.into(),
            transaction_id: "999733843".to_string().into(),
            only_failures: true.into(),
        };

        let response = client.get_notification_history("a036bc0e-52b8-4bee-82fc-8c24cb6715d6", &notification_history_request).await.unwrap();
        assert_eq!("57715481-805a-4283-8499-1c19b5d6b20a", response.pagination_token.unwrap());
        assert_eq!(true, response.has_more.unwrap());

        let expected_notification_history = vec![
            NotificationHistoryResponseItem {
                signed_payload: "signed_payload_one".to_string().into(),
                send_attempts: vec![
                    SendAttemptItem {
                        attempt_date: DateTime::from_timestamp(1698148900, 0),
                        send_attempt_result: SendAttemptResult::NoResponse.into(),
                    },
                    SendAttemptItem {
                        attempt_date: DateTime::from_timestamp(1698148950, 0),
                        send_attempt_result: SendAttemptResult::Success.into(),
                    },
                ].into(),
            },
            NotificationHistoryResponseItem {
                signed_payload: "signed_payload_two".to_string().into(),
                send_attempts: vec![
                    SendAttemptItem {
                        attempt_date: DateTime::from_timestamp(1698148800, 0),
                        send_attempt_result: SendAttemptResult::CircularRedirect.into(),
                    },
                ].into(),
            },
        ];
        assert_eq!(expected_notification_history, response.notification_history.unwrap());
    }

    #[tokio::test]
    async fn test_get_transaction_history_v1() {
        let client = app_store_server_api_client_with_body_from_file(
            "assets/models/transactionHistoryResponse.json",
            StatusCode::OK,
            Some(|req, _body| {
                assert_eq!(Method::GET, req.method());
                assert_eq!(
                    "/inApps/v1/history/1234",
                    req.url().path()
                );
                assert!(req.body().is_none());
            }),
        );

        let request = TransactionHistoryRequest {
            start_date: DateTime::from_timestamp(123, 455000000),
            end_date: DateTime::from_timestamp(123, 456000000),
            product_ids: Some(vec!["com.example.1".to_string(), "com.example.2".to_string()]),
            product_types: Some(vec![ProductType::Consumable, ProductType::AutoRenewable]),
            sort: Some(Order::Ascending),
            subscription_group_identifiers: Some(vec![
                "sub_group_id".to_string(),
                "sub_group_id_2".to_string(),
            ]),
            in_app_ownership_type: Some(InAppOwnershipType::FamilyShared),
            revoked: Some(false),
        };

        let response = client
            .get_transaction_history("1234", Some("revision_input"), request)
            .await
            .unwrap();

        assert_eq!("revision_output", response.revision.unwrap());
        assert_eq!(response.has_more, Some(true));
        assert_eq!("com.example", response.bundle_id.unwrap().as_str());
        assert_eq!(323232, response.app_apple_id.unwrap());
        assert_eq!(Environment::LocalTesting, response.environment.unwrap());
        assert_eq!(vec!["signed_transaction_value", "signed_transaction_value2"], response.signed_transactions.unwrap());
    }

    #[tokio::test]
    async fn test_get_transaction_history_v2() {
        let client = app_store_server_api_client_with_body_from_file(
            "assets/models/transactionHistoryResponse.json",
            StatusCode::OK,
            Some(|req, _body| {
                assert_eq!(Method::GET, req.method());
                let url = req.url();
                assert_eq!(
                    "/inApps/v2/history/1234",
                    url.path()
                );

                let params: HashMap<String, Vec<String>> = url.query_pairs()
                    .into_owned()
                    .fold(HashMap::new(), |mut acc, (k, v)| {
                        acc.entry(k).or_insert_with(Vec::new).push(v);
                        acc
                    });

                assert_eq!(vec!["revision_input".to_string()], *params.get("revision").unwrap());
                assert_eq!(vec!["123455"], *params.get("startDate").unwrap());
                assert_eq!(vec!["123456"], *params.get("endDate").unwrap());
                assert_eq!(vec!["com.example.1", "com.example.2"], *params.get("productId").unwrap());
                assert_eq!(vec!["CONSUMABLE", "AUTO_RENEWABLE"], *params.get("productType").unwrap());
                assert_eq!(vec!["ASCENDING"], *params.get("sort").unwrap());
                assert_eq!(vec!["sub_group_id", "sub_group_id_2"], *params.get("subscriptionGroupIdentifier").unwrap());
                assert_eq!(vec!["FAMILY_SHARED"], *params.get("inAppOwnershipType").unwrap());
                assert_eq!(vec!["false"], *params.get("revoked").unwrap());

                assert!(req.body().is_none());
            }),
        );

        let request = TransactionHistoryRequest {
            start_date: DateTime::from_timestamp(123, 455000000),
            end_date: DateTime::from_timestamp(123, 456000000),
            product_ids: Some(vec!["com.example.1".to_string(), "com.example.2".to_string()]),
            product_types: Some(vec![ProductType::Consumable, ProductType::AutoRenewable]),
            sort: Some(Order::Ascending),
            subscription_group_identifiers: Some(vec![
                "sub_group_id".to_string(),
                "sub_group_id_2".to_string(),
            ]),
            in_app_ownership_type: Some(InAppOwnershipType::FamilyShared),
            revoked: Some(false),
        };

        let response = client
            .get_transaction_history_with_version("1234", Some("revision_input"), &request, GetTransactionHistoryVersion::V2)
            .await
            .unwrap();

        assert_eq!("revision_output", response.revision.unwrap());
        assert_eq!(response.has_more, Some(true));
        assert_eq!("com.example", response.bundle_id.unwrap().as_str());
        assert_eq!(323232, response.app_apple_id.unwrap());
        assert_eq!(Environment::LocalTesting, response.environment.unwrap());
        assert_eq!(vec!["signed_transaction_value", "signed_transaction_value2"], response.signed_transactions.unwrap());
    }

    #[tokio::test]
    async fn test_get_transaction_info() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/transactionInfoResponse.json", StatusCode::OK, Some(|req, _body| {
            assert_eq!(Method::GET, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/transactions/1234", req.url().as_str());
            assert!(req.body().is_none());
        }));

        let response = client.get_transaction_info("1234").await.unwrap();
        assert_eq!("signed_transaction_info_value", response.signed_transaction_info.unwrap());
    }

    #[tokio::test]
    async fn test_look_up_order_id() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/lookupOrderIdResponse.json", StatusCode::OK, Some(|req, _body| {
            assert_eq!(Method::GET, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/lookup/W002182", req.url().as_str());
            assert!(req.body().is_none());
        }));

        let response = client.look_up_order_id("W002182").await.unwrap();
        assert_eq!(OrderLookupStatus::Invalid, response.status);
        assert_eq!(vec!["signed_transaction_one", "signed_transaction_two"], response.signed_transactions);
    }

    #[tokio::test]
    async fn test_request_test_notification() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/requestTestNotificationResponse.json", StatusCode::OK, Some(|req, _body| {
            assert_eq!(Method::POST, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/notifications/test", req.url().as_str());
            assert!(req.body().is_none());
        }));

        let response = client.request_test_notification().await.unwrap();
        assert_eq!("ce3af791-365e-4c60-841b-1674b43c1609", response.test_notification_token.unwrap());
    }

    #[tokio::test]
    async fn test_send_consumption_data() {
        let client = app_store_server_api_client("".into(), StatusCode::OK, Some(|req, body| {
            assert_eq!(Method::PUT, req.method());
            assert_eq!("https://local-testing-base-url/inApps/v1/transactions/consumption/49571273", req.url().as_str());
            assert_eq!("application/json", req.headers().get("Content-Type").unwrap().to_str().unwrap());
            let decoded_json: HashMap<String, Value> = serde_json::from_slice(body.unwrap()).unwrap();
            assert_eq!(true, decoded_json["customerConsented"].as_bool().unwrap());
            assert_eq!(1, decoded_json["consumptionStatus"].as_i64().unwrap());
            assert_eq!(2, decoded_json["platform"].as_i64().unwrap());
            assert_eq!(false, decoded_json["sampleContentProvided"].as_bool().unwrap());
            assert_eq!(3, decoded_json["deliveryStatus"].as_i64().unwrap());
            assert_eq!("7389A31A-FB6D-4569-A2A6-DB7D85D84813".to_lowercase().as_str(), decoded_json["appAccountToken"].as_str().unwrap());
            assert_eq!(4, decoded_json["accountTenure"].as_i64().unwrap());
            assert_eq!(5, decoded_json["playTime"].as_i64().unwrap());
            assert_eq!(6, decoded_json["lifetimeDollarsRefunded"].as_i64().unwrap());
            assert_eq!(7, decoded_json["lifetimeDollarsPurchased"].as_i64().unwrap());
            assert_eq!(4, decoded_json["userStatus"].as_i64().unwrap());
            assert_eq!(3, decoded_json["refundPreference"].as_i64().unwrap());
        }));

        let consumption_request = ConsumptionRequest {
            customer_consented: true.into(),
            consumption_status: ConsumptionStatus::NotConsumed.into(),
            platform: Platform::NonApple.into(),
            sample_content_provided: false.into(),
            delivery_status: DeliveryStatus::DidNotDeliverDueToServerOutage.into(),
            app_account_token: Some(Uuid::parse_str("7389a31a-fb6d-4569-a2a6-db7d85d84813").unwrap()),
            account_tenure: AccountTenure::ThirtyDaysToNinetyDays.into(),
            play_time: PlayTime::OneDayToFourDays.into(),
            lifetime_dollars_refunded: LifetimeDollarsRefunded::OneThousandDollarsToOneThousandNineHundredNinetyNineDollarsAndNinetyNineCents.into(),
            lifetime_dollars_purchased: LifetimeDollarsPurchased::TwoThousandDollarsOrGreater.into(),
            user_status: UserStatus::LimitedAccess.into(),
            refund_preference: RefundPreference::NoPreference.into(),
        };

        let _ = client.send_consumption_data("49571273", &consumption_request).await.unwrap();
    }

    #[tokio::test]
    async fn test_headers() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/transactionInfoResponse.json", StatusCode::OK, Some(|req, _body| {
            let headers = req.headers();
            assert!(headers.get("User-Agent").unwrap().to_str().unwrap().starts_with("app-store-server-library/rust"));
            assert_eq!("application/json", headers.get("Accept").unwrap());
            let authorization = headers.get("Authorization").unwrap().to_str().unwrap();
            assert!(authorization.starts_with("Bearer "));
            let token_components: Vec<&str> = authorization[7..].split('.').collect();
            let header_data = BASE64_STANDARD_NO_PAD.decode(token_components[0]).unwrap();
            let payload_data = BASE64_STANDARD_NO_PAD.decode(token_components[1]).unwrap();
            let header: HashMap<String, Value> = serde_json::from_slice(&header_data).unwrap();
            let payload: HashMap<String, Value> = serde_json::from_slice(&payload_data).unwrap();

            assert_eq!("appstoreconnect-v1", payload["aud"].as_str().unwrap());
            assert_eq!("issuerId", payload["iss"].as_str().unwrap());
            assert_eq!("keyId", header["kid"].as_str().unwrap());
            assert_eq!("com.example", payload["bid"].as_str().unwrap());
            assert_eq!("ES256", header["alg"].as_str().unwrap());
        }));

        let _ = client.get_transaction_info("1234").await;
    }

    #[tokio::test]
    async fn test_api_error() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/apiException.json", StatusCode::INTERNAL_SERVER_ERROR, None);
        let result = client.get_transaction_info("1234").await;

        match result {
            Ok(_) => {
                assert!(false, "Unexpected response type");
            }
            Err(error) => {
                assert_eq!(500, error.http_status_code);
                assert_eq!(APIError::GeneralInternal, error.api_error.unwrap());
                assert_eq!(5000000, error.raw_api_error.unwrap());
                assert_eq!("An unknown error occurred.", error.error_message.unwrap());
            }
        }
    }

    #[tokio::test]
    async fn test_api_too_many_requests() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/apiTooManyRequestsException.json", StatusCode::TOO_MANY_REQUESTS, None);
        let result = client.get_transaction_info("1234").await;

        match result {
            Ok(_) => {
                assert!(false, "Unexpected response type");
            }
            Err(error) => {
                assert_eq!(429, error.http_status_code);
                assert_eq!(APIError::RateLimitExceeded, error.api_error.unwrap());
                assert_eq!("Rate limit exceeded.", error.error_message.unwrap());
            }
        }
    }

    #[tokio::test]
    async fn test_api_unknown_error() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/apiUnknownError.json", StatusCode::BAD_REQUEST, None);
        let result = client.get_transaction_info("1234").await;

        match result {
            Ok(_) => {
                assert!(false, "Unexpected response type");
            }
            Err(error) => {
                assert_eq!(400, error.http_status_code);
                assert_eq!(None, error.api_error);
                //todo! assert_eq!(9990000, error.raw_api_error.unwrap());
                assert_eq!("Testing error.", error.error_message.unwrap());
            }
        }
    }

    #[tokio::test]
    async fn test_decoding_with_unknown_enum_value() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/transactionHistoryResponseWithMalformedEnvironment.json", StatusCode::OK, None);

        let request = TransactionHistoryRequest {
            start_date: DateTime::from_timestamp(123, 455000000),
            end_date: DateTime::from_timestamp(123, 456000000),
            product_ids: vec!["com.example.1".to_string(), "com.example.2".to_string()].into(),
            product_types: vec![ProductType::Consumable, ProductType::AutoRenewable].into(),
            sort: Some(Order::Ascending),
            subscription_group_identifiers: vec!["sub_group_id".to_string(), "sub_group_id_2".to_string()].into(),
            in_app_ownership_type: Some(InAppOwnershipType::FamilyShared),
            revoked: Some(false),
        };

        let result = client.get_transaction_history("1234", Some("revision_input"), request).await.unwrap();
        assert_eq!(Environment::Unknown, result.environment.unwrap());
    }

    #[tokio::test]
    async fn test_decoding_with_malformed_json() {
        let client = app_store_server_api_client_with_body_from_file("assets/models/transactionHistoryResponseWithMalformedAppAppleId.json", StatusCode::OK, None);

        let request = TransactionHistoryRequest {
            start_date: DateTime::from_timestamp(123, 455000000),
            end_date: DateTime::from_timestamp(123, 456000000),
            product_ids: vec!["com.example.1".to_string(), "com.example.2".to_string()].into(),
            product_types: vec![ProductType::Consumable, ProductType::AutoRenewable].into(),
            sort: Some(Order::Ascending),
            subscription_group_identifiers: vec!["sub_group_id".to_string(), "sub_group_id_2".to_string()].into(),
            in_app_ownership_type: Some(InAppOwnershipType::FamilyShared),
            revoked: Some(false),
        };

        let result = client.get_transaction_history("1234", Some("revision_input"), request).await;
        match result {
            Ok(_) => {
                assert!(false, "Unexpected response type");
            }
            Err(error) => {
                assert_eq!(500, error.http_status_code);
                assert_eq!(None, error.api_error);
                assert_eq!(None, error.raw_api_error);
                assert_eq!("Failed to deserialize response JSON", error.error_message.unwrap());
            }
        }
    }

    fn app_store_server_api_client_with_body_from_file(path: &str, status: http::StatusCode, request_verifier: Option<RequestVerifier>) -> AppStoreServerAPIClient {
        let body = fs::read_to_string(path)
            .expect("Failed to read file");
        app_store_server_api_client(body, status, request_verifier)
    }

    fn app_store_server_api_client(body: String, status: http::StatusCode, request_verifier: Option<RequestVerifier>) -> AppStoreServerAPIClient {
        let key = fs::read("assets/testSigningKey.p8")
            .expect("Failed to read file");

        let request_overrider = move |req: &reqwest::Request, request_body: Option<&[u8]>| {
            if let Some(request_verifier) = request_verifier {
                (request_verifier)(req, request_body)
            }

            let buffered_body = body.as_bytes().to_vec();

            let response = http::response::Builder::new()
                .header("Content-Type", "application/json")
                .status(status)
                .body(buffered_body)
                .unwrap();

            response
        };

        AppStoreServerAPIClient::new(key, "keyId", "issuerId", "com.example", Environment::LocalTesting, Box::new(request_overrider))
    }
}