forked from apple/app-store-server-library-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
1290 lines (997 loc) · 65.5 KB
/
Copy pathapi_client.py
File metadata and controls
1290 lines (997 loc) · 65.5 KB
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
# Copyright (c) 2023 Apple Inc. Licensed under MIT License.
import calendar
import datetime
from enum import IntEnum, Enum
from typing import Any, Dict, List, MutableMapping, Optional, Type, TypeVar, Union
from attr import define
import requests
import jwt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from appstoreserverlibrary.models.LibraryUtility import _get_cattrs_converter
from .models.CheckTestNotificationResponse import CheckTestNotificationResponse
from .models.ConsumptionRequest import ConsumptionRequest
from .models.DefaultConfigurationRequest import DefaultConfigurationRequest
from .models.Environment import Environment
from .models.ExtendRenewalDateRequest import ExtendRenewalDateRequest
from .models.ExtendRenewalDateResponse import ExtendRenewalDateResponse
from .models.GetImageListResponse import GetImageListResponse
from .models.GetMessageListResponse import GetMessageListResponse
from .models.HistoryResponse import HistoryResponse
from .models.MassExtendRenewalDateRequest import MassExtendRenewalDateRequest
from .models.MassExtendRenewalDateResponse import MassExtendRenewalDateResponse
from .models.MassExtendRenewalDateStatusResponse import MassExtendRenewalDateStatusResponse
from .models.NotificationHistoryRequest import NotificationHistoryRequest
from .models.NotificationHistoryResponse import NotificationHistoryResponse
from .models.OrderLookupResponse import OrderLookupResponse
from .models.RefundHistoryResponse import RefundHistoryResponse
from .models.SendTestNotificationResponse import SendTestNotificationResponse
from .models.Status import Status
from .models.StatusResponse import StatusResponse
from .models.TransactionHistoryRequest import TransactionHistoryRequest
from .models.TransactionInfoResponse import TransactionInfoResponse
from .models.AppTransactionInfoResponse import AppTransactionInfoResponse
from .models.UpdateAppAccountTokenRequest import UpdateAppAccountTokenRequest
from .models.UploadMessageRequestBody import UploadMessageRequestBody
from uuid import UUID
T = TypeVar('T')
class APIError(IntEnum):
GENERAL_BAD_REQUEST = 4000000
"""
An error that indicates an invalid request.
https://developer.apple.com/documentation/appstoreserverapi/generalbadrequesterror
"""
INVALID_APP_IDENTIFIER = 4000002
"""
An error that indicates an invalid app identifier.
https://developer.apple.com/documentation/appstoreserverapi/invalidappidentifiererror
"""
INVALID_REQUEST_REVISION = 4000005
"""
An error that indicates an invalid request revision.
https://developer.apple.com/documentation/appstoreserverapi/invalidrequestrevisionerror
"""
INVALID_TRANSACTION_ID = 4000006
"""
An error that indicates an invalid transaction identifier.
https://developer.apple.com/documentation/appstoreserverapi/invalidtransactioniderror
"""
INVALID_ORIGINAL_TRANSACTION_ID = 4000008
"""
An error that indicates an invalid original transaction identifier.
https://developer.apple.com/documentation/appstoreserverapi/invalidoriginaltransactioniderror
"""
INVALID_EXTEND_BY_DAYS = 4000009
"""
An error that indicates an invalid extend-by-days value.
https://developer.apple.com/documentation/appstoreserverapi/invalidextendbydayserror
"""
INVALID_EXTEND_REASON_CODE = 4000010
"""
An error that indicates an invalid reason code.
https://developer.apple.com/documentation/appstoreserverapi/invalidextendreasoncodeerror
"""
INVALID_REQUEST_IDENTIFIER = 4000011
"""
An error that indicates an invalid request identifier.
https://developer.apple.com/documentation/appstoreserverapi/invalidrequestidentifiererror
"""
START_DATE_TOO_FAR_IN_PAST = 4000012
"""
An error that indicates that the start date is earlier than the earliest allowed date.
https://developer.apple.com/documentation/appstoreserverapi/startdatetoofarinpasterror
"""
START_DATE_AFTER_END_DATE = 4000013
"""
An error that indicates that the end date precedes the start date, or the two dates are equal.
https://developer.apple.com/documentation/appstoreserverapi/startdateafterenddateerror
"""
INVALID_PAGINATION_TOKEN = 4000014
"""
An error that indicates the pagination token is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidpaginationtokenerror
"""
INVALID_START_DATE = 4000015
"""
An error that indicates the start date is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidstartdateerror
"""
INVALID_END_DATE = 4000016
"""
An error that indicates the end date is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidenddateerror
"""
PAGINATION_TOKEN_EXPIRED = 4000017
"""
An error that indicates the pagination token expired.
https://developer.apple.com/documentation/appstoreserverapi/paginationtokenexpirederror
"""
INVALID_NOTIFICATION_TYPE = 4000018
"""
An error that indicates the notification type or subtype is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidnotificationtypeerror
"""
MULTIPLE_FILTERS_SUPPLIED = 4000019
"""
An error that indicates the request is invalid because it has too many constraints applied.
https://developer.apple.com/documentation/appstoreserverapi/multiplefilterssuppliederror
"""
INVALID_TEST_NOTIFICATION_TOKEN = 4000020
"""
An error that indicates the test notification token is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidtestnotificationtokenerror
"""
INVALID_SORT = 4000021
"""
An error that indicates an invalid sort parameter.
https://developer.apple.com/documentation/appstoreserverapi/invalidsorterror
"""
INVALID_PRODUCT_TYPE = 4000022
"""
An error that indicates an invalid product type parameter.
https://developer.apple.com/documentation/appstoreserverapi/invalidproducttypeerror
"""
INVALID_PRODUCT_ID = 4000023
"""
An error that indicates the product ID parameter is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidproductiderror
"""
INVALID_SUBSCRIPTION_GROUP_IDENTIFIER = 4000024
"""
An error that indicates an invalid subscription group identifier.
https://developer.apple.com/documentation/appstoreserverapi/invalidsubscriptiongroupidentifiererror
"""
INVALID_EXCLUDE_REVOKED = 4000025
"""
An error that indicates the query parameter exclude-revoked is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidexcluderevokederror
.. deprecated:: 1.5
"""
INVALID_IN_APP_OWNERSHIP_TYPE = 4000026
"""
An error that indicates an invalid in-app ownership type parameter.
https://developer.apple.com/documentation/appstoreserverapi/invalidinappownershiptypeerror
"""
INVALID_EMPTY_STOREFRONT_COUNTRY_CODE_LIST = 4000027
"""
An error that indicates a required storefront country code is empty.
https://developer.apple.com/documentation/appstoreserverapi/invalidemptystorefrontcountrycodelisterror
"""
INVALID_STOREFRONT_COUNTRY_CODE = 4000028
"""
An error that indicates a storefront code is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidstorefrontcountrycodeerror
"""
INVALID_REVOKED = 4000030
"""
An error that indicates the revoked parameter contains an invalid value.
https://developer.apple.com/documentation/appstoreserverapi/invalidrevokederror
"""
INVALID_STATUS = 4000031
"""
An error that indicates the status parameter is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidstatuserror
"""
INVALID_ACCOUNT_TENURE = 4000032
"""
An error that indicates the value of the account tenure field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidaccounttenureerror
"""
INVALID_APP_ACCOUNT_TOKEN = 4000033
"""
An error that indicates the value of the app account token field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidappaccounttokenerror
"""
INVALID_CONSUMPTION_STATUS = 4000034
"""
An error that indicates the value of the consumption status field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidconsumptionstatuserror
"""
INVALID_CUSTOMER_CONSENTED = 4000035
"""
An error that indicates the customer consented field is invalid or doesn’t indicate that the customer consented.
https://developer.apple.com/documentation/appstoreserverapi/invalidcustomerconsentederror
"""
INVALID_DELIVERY_STATUS = 4000036
"""
An error that indicates the value in the delivery status field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invaliddeliverystatuserror
"""
INVALID_LIFETIME_DOLLARS_PURCHASED = 4000037
"""
An error that indicates the value in the lifetime dollars purchased field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidlifetimedollarspurchasederror
"""
INVALID_LIFETIME_DOLLARS_REFUNDED = 4000038
"""
An error that indicates the value in the lifetime dollars refunded field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidlifetimedollarsrefundederror
"""
INVALID_PLATFORM = 4000039
"""
An error that indicates the value in the platform field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidplatformerror
"""
INVALID_PLAY_TIME = 4000040
"""
An error that indicates the value in the playtime field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidplaytimeerror
"""
INVALID_SAMPLE_CONTENT_PROVIDED = 4000041
"""
An error that indicates the value in the sample content provided field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invalidsamplecontentprovidederror
"""
INVALID_USER_STATUS = 4000042
"""
An error that indicates the value in the user status field is invalid.
https://developer.apple.com/documentation/appstoreserverapi/invaliduserstatuserror
"""
INVALID_TRANSACTION_NOT_CONSUMABLE = 4000043
"""
An error that indicates the transaction identifier doesn’t represent a consumable in-app purchase.
https://developer.apple.com/documentation/appstoreserverapi/invalidtransactionnotconsumableerror
.. deprecated:: 1.11
"""
INVALID_TRANSACTION_TYPE_NOT_SUPPORTED = 4000047
"""
An error that indicates the transaction identifier represents an unsupported in-app purchase type.
https://developer.apple.com/documentation/appstoreserverapi/invalidtransactiontypenotsupportederror
"""
APP_TRANSACTION_ID_NOT_SUPPORTED_ERROR = 4000048
"""
An error that indicates the endpoint doesn't support an app transaction ID.
https://developer.apple.com/documentation/appstoreserverapi/apptransactionidnotsupportederror
"""
INVALID_IMAGE = 4000161
"""
An error that indicates the image that's uploading is invalid.
https://developer.apple.com/documentation/retentionmessaging/invalidimageerror
"""
HEADER_TOO_LONG = 4000162
"""
An error that indicates the header text is too long.
https://developer.apple.com/documentation/retentionmessaging/headertoolongerror
"""
BODY_TOO_LONG = 4000163
"""
An error that indicates the body text is too long.
https://developer.apple.com/documentation/retentionmessaging/bodytoolongerror
"""
INVALID_LOCALE = 4000164
"""
An error that indicates the locale is invalid.
https://developer.apple.com/documentation/retentionmessaging/invalidlocaleerror
"""
ALT_TEXT_TOO_LONG = 4000175
"""
An error that indicates the alternative text for an image is too long.
https://developer.apple.com/documentation/retentionmessaging/alttexttoolongerror
"""
INVALID_APP_ACCOUNT_TOKEN_UUID_ERROR = 4000183
"""
An error that indicates the app account token value is not a valid UUID.
https://developer.apple.com/documentation/appstoreserverapi/invalidappaccounttokenuuiderror
"""
FAMILY_TRANSACTION_NOT_SUPPORTED_ERROR = 4000185
"""
An error that indicates the transaction is for a product the customer obtains through Family Sharing,
which the endpoint doesn’t support.
https://developer.apple.com/documentation/appstoreserverapi/familytransactionnotsupportederror
"""
TRANSACTION_ID_IS_NOT_ORIGINAL_TRANSACTION_ID_ERROR = 4000187
"""
An error that indicates the endpoint expects an original transaction identifier.
https://developer.apple.com/documentation/appstoreserverapi/transactionidisnotoriginaltransactioniderror
"""
SUBSCRIPTION_EXTENSION_INELIGIBLE = 4030004
"""
An error that indicates the subscription doesn't qualify for a renewal-date extension due to its subscription state.
https://developer.apple.com/documentation/appstoreserverapi/subscriptionextensionineligibleerror
"""
SUBSCRIPTION_MAX_EXTENSION = 4030005
"""
An error that indicates the subscription doesn’t qualify for a renewal-date extension because it has already received the maximum extensions.
https://developer.apple.com/documentation/appstoreserverapi/subscriptionmaxextensionerror
"""
FAMILY_SHARED_SUBSCRIPTION_EXTENSION_INELIGIBLE = 4030007
"""
An error that indicates a subscription isn't directly eligible for a renewal date extension because the user obtained it through Family Sharing.
https://developer.apple.com/documentation/appstoreserverapi/familysharedsubscriptionextensionineligibleerror
"""
MAXIMUM_NUMBER_OF_IMAGES_REACHED = 4030014
"""
An error that indicates when you reach the maximum number of uploaded images.
https://developer.apple.com/documentation/retentionmessaging/maximumnumberofimagesreachederror
"""
MAXIMUM_NUMBER_OF_MESSAGES_REACHED = 4030016
"""
An error that indicates when you reach the maximum number of uploaded messages.
https://developer.apple.com/documentation/retentionmessaging/maximumnumberofmessagesreachederror
"""
MESSAGE_NOT_APPROVED = 4030017
"""
An error that indicates the message isn't in the approved state, so you can't configure it as a default message.
https://developer.apple.com/documentation/retentionmessaging/messagenotapprovederror
"""
IMAGE_NOT_APPROVED = 4030018
"""
An error that indicates the image isn't in the approved state, so you can't configure it as part of a default message.
https://developer.apple.com/documentation/retentionmessaging/imagenotapprovederror
"""
IMAGE_IN_USE = 4030019
"""
An error that indicates the image is currently in use as part of a message, so you can't delete it.
https://developer.apple.com/documentation/retentionmessaging/imageinuseerror
"""
ACCOUNT_NOT_FOUND = 4040001
"""
An error that indicates the App Store account wasn’t found.
https://developer.apple.com/documentation/appstoreserverapi/accountnotfounderror
"""
ACCOUNT_NOT_FOUND_RETRYABLE = 4040002
"""
An error response that indicates the App Store account wasn’t found, but you can try again.
https://developer.apple.com/documentation/appstoreserverapi/accountnotfoundretryableerror
"""
APP_NOT_FOUND = 4040003
"""
An error that indicates the app wasn’t found.
https://developer.apple.com/documentation/appstoreserverapi/appnotfounderror
"""
APP_NOT_FOUND_RETRYABLE = 4040004
"""
An error response that indicates the app wasn’t found, but you can try again.
https://developer.apple.com/documentation/appstoreserverapi/appnotfoundretryableerror
"""
ORIGINAL_TRANSACTION_ID_NOT_FOUND = 4040005
"""
An error that indicates an original transaction identifier wasn't found.
https://developer.apple.com/documentation/appstoreserverapi/originaltransactionidnotfounderror
"""
ORIGINAL_TRANSACTION_ID_NOT_FOUND_RETRYABLE = 4040006
"""
An error response that indicates the original transaction identifier wasn’t found, but you can try again.
https://developer.apple.com/documentation/appstoreserverapi/originaltransactionidnotfoundretryableerror
"""
SERVER_NOTIFICATION_URL_NOT_FOUND = 4040007
"""
An error that indicates that the App Store server couldn’t find a notifications URL for your app in this environment.
https://developer.apple.com/documentation/appstoreserverapi/servernotificationurlnotfounderror
"""
TEST_NOTIFICATION_NOT_FOUND = 4040008
"""
An error that indicates that the test notification token is expired or the test notification status isn’t available.
https://developer.apple.com/documentation/appstoreserverapi/testnotificationnotfounderror
"""
STATUS_REQUEST_NOT_FOUND = 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.
https://developer.apple.com/documentation/appstoreserverapi/statusrequestnotfounderror
"""
TRANSACTION_ID_NOT_FOUND = 4040010
"""
An error that indicates a transaction identifier wasn't found.
https://developer.apple.com/documentation/appstoreserverapi/transactionidnotfounderror
"""
IMAGE_NOT_FOUND = 4040014
"""
An error that indicates the system can't find the image identifier.
https://developer.apple.com/documentation/retentionmessaging/imagenotfounderror
"""
MESSAGE_NOT_FOUND = 4040015
"""
An error that indicates the system can't find the message identifier.
https://developer.apple.com/documentation/retentionmessaging/messagenotfounderror
"""
APP_TRANSACTION_DOES_NOT_EXIST_ERROR = 4040019
"""
An error response that indicates an app transaction doesn’t exist for the specified customer.
https://developer.apple.com/documentation/appstoreserverapi/apptransactiondoesnotexisterror
"""
IMAGE_ALREADY_EXISTS = 4090000
"""
An error that indicates the image identifier already exists.
https://developer.apple.com/documentation/retentionmessaging/imagealreadyexistserror
"""
MESSAGE_ALREADY_EXISTS = 4090001
"""
An error that indicates the message identifier already exists.
https://developer.apple.com/documentation/retentionmessaging/messagealreadyexistserror
"""
RATE_LIMIT_EXCEEDED = 4290000
"""
An error that indicates that the request exceeded the rate limit.
https://developer.apple.com/documentation/appstoreserverapi/ratelimitexceedederror
"""
GENERAL_INTERNAL = 5000000
"""
An error that indicates a general internal error.
https://developer.apple.com/documentation/appstoreserverapi/generalinternalerror
"""
GENERAL_INTERNAL_RETRYABLE = 5000001
"""
An error response that indicates an unknown error occurred, but you can try again.
https://developer.apple.com/documentation/appstoreserverapi/generalinternalretryableerror
"""
@define
class APIException(Exception):
http_status_code: int
api_error: Optional[APIError]
raw_api_error: Optional[int]
error_message: Optional[str]
def __init__(self, http_status_code: int, raw_api_error: Optional[int] = None, error_message: Optional[str] = None):
self.http_status_code = http_status_code
self.raw_api_error = raw_api_error
self.api_error = None
self.error_message = error_message
try:
if raw_api_error is not None:
self.api_error = APIError(raw_api_error)
except ValueError:
pass
class GetTransactionHistoryVersion(str, Enum):
V1 = "v1"
"""
.. deprecated:: 1.3.0
"""
V2 = "v2"
class BaseAppStoreServerAPIClient:
def __init__(self, signing_key: bytes, key_id: str, issuer_id: str, bundle_id: str, environment: Environment):
if environment == Environment.XCODE:
raise ValueError("Xcode is not a supported environment for an AppStoreServerAPIClient")
if environment == Environment.PRODUCTION:
self._base_url = "https://api.storekit.itunes.apple.com"
elif environment == Environment.LOCAL_TESTING:
self._base_url = "https://local-testing-base-url"
elif environment == Environment.SANDBOX:
self._base_url = "https://api.storekit-sandbox.itunes.apple.com"
else:
raise ValueError("Invalid environment provided")
self._signing_key = serialization.load_pem_private_key(signing_key, password=None, backend=default_backend())
self._key_id = key_id
self._issuer_id = issuer_id
self._bundle_id = bundle_id
def _generate_token(self) -> str:
future_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=5)
return jwt.encode(
{
"bid": self._bundle_id,
"iss": self._issuer_id,
"aud": "appstoreconnect-v1",
"exp": calendar.timegm(future_time.timetuple()),
},
self._signing_key,
algorithm="ES256",
headers={"kid": self._key_id},
)
def _get_full_url(self, path) -> str:
return self._base_url + path
def _get_headers(self) -> Dict[str, str]:
return {
'User-Agent': "app-store-server-library/python/3.0.0",
'Authorization': f'Bearer {self._generate_token()}',
'Accept': 'application/json'
}
def _get_request_json(self, body) -> Dict[str, Any]:
c = _get_cattrs_converter(type(body)) if body is not None else None
return c.unstructure(body) if body is not None else None
def _parse_response(self, status_code: int, headers: MutableMapping, json_supplier, destination_class: Type[T]) -> T:
if 200 <= status_code < 300:
if destination_class is None:
return
c = _get_cattrs_converter(destination_class)
response_body = json_supplier()
return c.structure(response_body, destination_class)
else:
# Best effort parsing of the response body
if not 'content-type' in headers or headers['content-type'] != 'application/json':
raise APIException(status_code)
try:
response_body = json_supplier()
raise APIException(status_code, response_body['errorCode'], response_body['errorMessage'])
except APIException as e:
raise e
except Exception as e:
raise APIException(status_code) from e
class AppStoreServerAPIClient(BaseAppStoreServerAPIClient):
def __init__(self, signing_key: bytes, key_id: str, issuer_id: str, bundle_id: str, environment: Environment):
super().__init__(signing_key=signing_key, key_id=key_id, issuer_id=issuer_id, bundle_id=bundle_id, environment=environment)
def _make_request(self, path: str, method: str, queryParameters: Dict[str, Union[str, List[str]]], body, destination_class: Type[T], content_type: Optional[str] = None) -> T:
url = self._get_full_url(path)
headers = self._get_headers()
if isinstance(body, bytes):
if content_type:
headers['Content-Type'] = content_type
response = self._execute_request(method, url, queryParameters, headers, None, body)
else:
json = self._get_request_json(body)
response = self._execute_request(method, url, queryParameters, headers, json, None)
return self._parse_response(response.status_code, response.headers, lambda: response.json(), destination_class)
def _execute_request(self, method: str, url: str, params: Dict[str, Union[str, List[str]]], headers: Dict[str, str], json: Optional[Dict[str, Any]], data: Optional[bytes]) -> requests.Response:
return requests.request(method, url, params=params, headers=headers, json=json, data=data, timeout=30)
def extend_renewal_date_for_all_active_subscribers(self, mass_extend_renewal_date_request: MassExtendRenewalDateRequest) -> MassExtendRenewalDateResponse:
"""
Uses a subscription's product identifier to extend the renewal date for all of its eligible active subscribers.
https://developer.apple.com/documentation/appstoreserverapi/extend_subscription_renewal_dates_for_all_active_subscribers
:param mass_extend_renewal_date_request: The request body for extending a subscription renewal date for all of its active subscribers.
:return: A response that indicates the server successfully received the subscription-renewal-date extension request.
:throws APIException: If a response was returned indicating the request could not be processed
"""
return self._make_request("/inApps/v1/subscriptions/extend/mass", "POST", {}, mass_extend_renewal_date_request, MassExtendRenewalDateResponse, None)
def extend_subscription_renewal_date(self, original_transaction_id: str, extend_renewal_date_request: ExtendRenewalDateRequest) -> ExtendRenewalDateResponse:
"""
Extends the renewal date of a customer's active subscription using the original transaction identifier.
https://developer.apple.com/documentation/appstoreserverapi/extend_a_subscription_renewal_date
:param original_transaction_id: The original transaction identifier of the subscription receiving a renewal date extension.
:param extend_renewal_date_request: The request body containing subscription-renewal-extension data.
:return: A response that indicates whether an individual renewal-date extension succeeded, and related details.
:throws APIException: If a response was returned indicating the request could not be processed
"""
return self._make_request(f"/inApps/v1/subscriptions/extend/{original_transaction_id}", "PUT", {}, extend_renewal_date_request, ExtendRenewalDateResponse, None)
def get_all_subscription_statuses(self, transaction_id: str, status: Optional[List[Status]] = None) -> StatusResponse:
"""
Get the statuses for all of a customer's auto-renewable subscriptions in your app.
https://developer.apple.com/documentation/appstoreserverapi/get_all_subscription_statuses
:param transaction_id: The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
:param status: An optional filter that indicates the status of subscriptions to include in the response. Your query may specify more than one status query parameter.
:return: A response that contains status information for all of a customer's auto-renewable subscriptions in your app.
:throws APIException: If a response was returned indicating the request could not be processed
"""
queryParameters: Dict[str, List[str]] = dict()
if status is not None:
queryParameters["status"] = [s.value for s in status]
return self._make_request(f"/inApps/v1/subscriptions/{transaction_id}", "GET", queryParameters, None, StatusResponse, None)
def get_refund_history(self, transaction_id: str, revision: Optional[str]) -> RefundHistoryResponse:
"""
Get a paginated list of all of a customer's refunded in-app purchases for your app.
https://developer.apple.com/documentation/appstoreserverapi/get_refund_history
:param transaction_id: The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
:param 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.
:return: A response that contains status information for all of a customer's auto-renewable subscriptions in your app.
:throws APIException: If a response was returned indicating the request could not be processed
"""
queryParameters: Dict[str, List[str]] = dict()
if revision is not None:
queryParameters["revision"] = [revision]
return self._make_request(f"/inApps/v2/refund/lookup/{transaction_id}", "GET", queryParameters, None, RefundHistoryResponse, None)
def get_status_of_subscription_renewal_date_extensions(self, request_identifier: str, product_id: str) -> MassExtendRenewalDateStatusResponse:
"""
Checks whether a renewal date extension request completed, and provides the final count of successful or failed extensions.
https://developer.apple.com/documentation/appstoreserverapi/get_status_of_subscription_renewal_date_extensions
:param request_identifier: The UUID that represents your request to the Extend Subscription Renewal Dates for All Active Subscribers endpoint.
:param product_id: The product identifier of the auto-renewable subscription that you request a renewal-date extension for.
:return: A response that indicates the current status of a request to extend the subscription renewal date to all eligible subscribers.
:throws APIException: If a response was returned indicating the request could not be processed
"""
return self._make_request(f"/inApps/v1/subscriptions/extend/mass/{product_id}/{request_identifier}", "GET", {}, None, MassExtendRenewalDateStatusResponse, None)
def get_test_notification_status(self, test_notification_token: str) -> CheckTestNotificationResponse:
"""
Check the status of the test App Store server notification sent to your server.
https://developer.apple.com/documentation/appstoreserverapi/get_test_notification_status
:param test_notification_token: The test notification token received from the Request a Test Notification endpoint
:return: A response that contains the contents of the test notification sent by the App Store server and the result from your server.
:throws APIException: If a response was returned indicating the request could not be processed
"""
return self._make_request(f"/inApps/v1/notifications/test/{test_notification_token}", "GET", {}, None, CheckTestNotificationResponse, None)
def get_notification_history(self, pagination_token: Optional[str], notification_history_request: NotificationHistoryRequest) -> NotificationHistoryResponse:
"""
Get a list of notifications that the App Store server attempted to send to your server.
https://developer.apple.com/documentation/appstoreserverapi/get_notification_history
:param 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.
:param notification_history_request: The request body that includes the start and end dates, and optional query constraints.
:return: A response that contains the App Store Server Notifications history for your app.
:throws APIException: If a response was returned indicating the request could not be processed
"""
queryParameters: Dict[str, List[str]] = dict()
if pagination_token is not None:
queryParameters["paginationToken"] = [pagination_token]
return self._make_request("/inApps/v1/notifications/history", "POST", queryParameters, notification_history_request, NotificationHistoryResponse, None)
def get_transaction_history(self, transaction_id: str, revision: Optional[str], transaction_history_request: TransactionHistoryRequest, version: GetTransactionHistoryVersion = GetTransactionHistoryVersion.V1) -> HistoryResponse:
"""
Get a customer's in-app purchase transaction history for your app.
https://developer.apple.com/documentation/appstoreserverapi/get_transaction_history
:param transaction_id: The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
:param 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.
:param transaction_history_request: The request parameters that includes the startDate,endDate,productIds,productTypes and optional query constraints.
:param version: The version of the Get Transaction History endpoint to use. V2 is recommended.
:return: A response that contains the customer's transaction history for an app.
:throws APIException: If a response was returned indicating the request could not be processed
"""
queryParameters: Dict[str, List[str]] = dict()
if revision is not None:
queryParameters["revision"] = [revision]
if transaction_history_request.startDate is not None:
queryParameters["startDate"] = [str(transaction_history_request.startDate)]
if transaction_history_request.endDate is not None:
queryParameters["endDate"] = [str(transaction_history_request.endDate)]
if transaction_history_request.productIds is not None:
queryParameters["productId"] = transaction_history_request.productIds
if transaction_history_request.productTypes is not None:
queryParameters["productType"] = [product_type.value for product_type in transaction_history_request.productTypes]
if transaction_history_request.sort is not None:
queryParameters["sort"] = [transaction_history_request.sort.value]
if transaction_history_request.subscriptionGroupIdentifiers is not None:
queryParameters["subscriptionGroupIdentifier"] = transaction_history_request.subscriptionGroupIdentifiers
if transaction_history_request.inAppOwnershipType is not None:
queryParameters["inAppOwnershipType"] = [transaction_history_request.inAppOwnershipType.value]
if transaction_history_request.revoked is not None:
queryParameters["revoked"] = [str(transaction_history_request.revoked)]
return self._make_request("/inApps/{}/history/{}".format(version.value, transaction_id), "GET", queryParameters, None, HistoryResponse, None)
def get_transaction_info(self, transaction_id: str) -> TransactionInfoResponse:
"""
Get information about a single transaction for your app.
https://developer.apple.com/documentation/appstoreserverapi/get_transaction_info
:param transaction_id The identifier of a transaction that belongs to the customer, and which may be an original transaction identifier.
:return: A response that contains signed transaction information for a single transaction.
:throws APIException: If a response was returned indicating the request could not be processed
"""
return self._make_request(f"/inApps/v1/transactions/{transaction_id}", "GET", {}, None, TransactionInfoResponse, None)
def look_up_order_id(self, order_id: str) -> OrderLookupResponse:
"""
Get a customer's in-app purchases from a receipt using the order ID.
https://developer.apple.com/documentation/appstoreserverapi/look_up_order_id
:param order_id: The order ID for in-app purchases that belong to the customer.
:return: A response that includes the order lookup status and an array of signed transactions for the in-app purchases in the order.
:throws APIException: If a response was returned indicating the request could not be processed
"""
return self._make_request(f"/inApps/v1/lookup/{order_id}", "GET", {}, None, OrderLookupResponse, None)
def request_test_notification(self) -> SendTestNotificationResponse:
"""
Ask App Store Server Notifications to send a test notification to your server.
https://developer.apple.com/documentation/appstoreserverapi/request_a_test_notification
:return: A response that contains the test notification token.
:throws APIException: If a response was returned indicating the request could not be processed
"""
return self._make_request("/inApps/v1/notifications/test", "POST", {}, None, SendTestNotificationResponse, None)
def send_consumption_data(self, transaction_id: str, consumption_request: ConsumptionRequest):
"""
Send consumption information about a consumable in-app purchase to the App Store after your server receives a consumption request notification.
https://developer.apple.com/documentation/appstoreserverapi/send_consumption_information
:param transaction_id: The transaction identifier for which you're providing consumption information. You receive this identifier in the CONSUMPTION_REQUEST notification the App Store sends to your server.
:param consumption_request: The request body containing consumption information.
:raises APIException: If a response was returned indicating the request could not be processed
"""
self._make_request(f"/inApps/v1/transactions/consumption/{transaction_id}", "PUT", {}, consumption_request, None, None)
def set_app_account_token(self, original_transaction_id: str, update_app_account_token_request: UpdateAppAccountTokenRequest):
"""
Sets the app account token value for a purchase the customer makes outside your app, or updates its value in an existing transaction.
https://developer.apple.com/documentation/appstoreserverapi/set-app-account-token
:param original_transaction_id The original transaction identifier of the transaction to receive the app account token update.
:param update_app_account_token_request The request body that contains a valid app account token value.
:raises APIException: If a response was returned indicating the request could not be processed
"""
self._make_request(f"/inApps/v1/transactions/{original_transaction_id}/appAccountToken", "PUT", {}, update_app_account_token_request, None, None)
def upload_image(self, image_identifier: UUID, image: bytes):
"""
Upload an image to use for retention messaging.
:param image_identifier: A UUID you provide to uniquely identify the image you upload.
:param image: The image file to upload.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/upload-image
"""
self._make_request(f"/inApps/v1/messaging/image/{image_identifier}", "PUT", {}, image, None, "image/png")
def delete_image(self, image_identifier: UUID):
"""
Delete a previously uploaded image.
:param image_identifier: The identifier of the image to delete.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/delete-image
"""
self._make_request(f"/inApps/v1/messaging/image/{image_identifier}", "DELETE", {}, None, None, None)
def get_image_list(self) -> GetImageListResponse:
"""
Get the image identifier and state for all uploaded images.
:return: A response that contains status information for all images.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/get-image-list
"""
return self._make_request("/inApps/v1/messaging/image/list", "GET", {}, None, GetImageListResponse, None)
def upload_message(self, message_identifier: UUID, upload_message_request_body: UploadMessageRequestBody):
"""
Upload a message to use for retention messaging.
:param message_identifier: A UUID you provide to uniquely identify the message you upload.
:param upload_message_request_body: The message text to upload.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/upload-message
"""
self._make_request(f"/inApps/v1/messaging/message/{message_identifier}", "PUT", {}, upload_message_request_body, None, None)
def delete_message(self, message_identifier: UUID):
"""
Delete a previously uploaded message.
:param message_identifier: The identifier of the message to delete.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/delete-message
"""
self._make_request(f"/inApps/v1/messaging/message/{message_identifier}", "DELETE", {}, None, None, None)
def get_message_list(self) -> GetMessageListResponse:
"""
Get the message identifier and state of all uploaded messages.
:return: A response that contains status information for all messages.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/get-message-list
"""
return self._make_request("/inApps/v1/messaging/message/list", "GET", {}, None, GetMessageListResponse, None)
def configure_default_message(self, product_id: str, locale: str, default_configuration_request: DefaultConfigurationRequest):
"""
Configure a default message for a specific product in a specific locale.
:param product_id: The product identifier for the default configuration.
:param locale: The locale for the default configuration.
:param default_configuration_request: The request body that includes the message identifier to configure as the default message.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/configure-default-message
"""
self._make_request(f"/inApps/v1/messaging/default/{product_id}/{locale}", "PUT", {}, default_configuration_request, None, None)
def delete_default_message(self, product_id: str, locale: str):
"""
Delete a default message for a product in a locale.
:param product_id: The product ID of the default message configuration.
:param locale: The locale of the default message configuration.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/retentionmessaging/delete-default-message
"""
self._make_request(f"/inApps/v1/messaging/default/{product_id}/{locale}", "DELETE", {}, None, None, None)
def get_app_transaction_info(self, transaction_id: str) -> AppTransactionInfoResponse:
"""
Get a customer's app transaction information for your app.
:param transaction_id Any originalTransactionId, transactionId or appTransactionId that belongs to the customer for your app.
:return: A response that contains signed app transaction information for a customer.
:raises APIException: If a response was returned indicating the request could not be processed
:see: https://developer.apple.com/documentation/appstoreserverapi/get-app-transaction-info
"""
return self._make_request(f"/inApps/v1/transactions/appTransactions/{transaction_id}", "GET", {}, None, AppTransactionInfoResponse, None)
class AsyncAppStoreServerAPIClient(BaseAppStoreServerAPIClient):
def __init__(self, signing_key: bytes, key_id: str, issuer_id: str, bundle_id: str, environment: Environment):
super().__init__(signing_key=signing_key, key_id=key_id, issuer_id=issuer_id, bundle_id=bundle_id, environment=environment)
try:
import httpx
self.http_client = httpx.AsyncClient()
except:
raise ModuleNotFoundError("httpx not found but attempting to instantiate an async client")
async def async_close(self):
await self.http_client.aclose()
async def _make_request(self, path: str, method: str, queryParameters: Dict[str, Union[str, List[str]]], body, destination_class: Type[T], content_type: Optional[str] = None) -> T:
url = self._get_full_url(path)
headers = self._get_headers()
if isinstance(body, bytes):
# For binary data like images
if content_type:
headers['Content-Type'] = content_type
response = await self._execute_request(method, url, queryParameters, headers, None, body)
else:
# For JSON data
json = self._get_request_json(body)
response = await self._execute_request(method, url, queryParameters, headers, json, None)
return self._parse_response(response.status_code, response.headers, lambda: response.json(), destination_class)