File size: 3,891 Bytes
98fe40b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
diff --git a/inapppy/appstore.py b/inapppy/appstore.py
index 84bbc2e..96599c1 100644
--- a/inapppy/appstore.py
+++ b/inapppy/appstore.py
@@ -3,7 +3,8 @@ from inapppy.errors import InAppPyValidationError
 from requests.exceptions import RequestException
 import requests
 
-
+# https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html
+# `Table 2-1  Status codes`
 api_result_ok = 0
 api_result_errors = {
     21000: InAppPyValidationError('Bad json'),
@@ -12,6 +13,8 @@ api_result_errors = {
     21004: InAppPyValidationError('Shared secret mismatch'),
     21005: InAppPyValidationError('Server is unavailable'),
     21006: InAppPyValidationError('Subscription has expired'),
+
+    # two following errors can use auto_retry_wrong_env_request.
     21007: InAppPyValidationError('Sandbox receipt was sent to the production env'),
     21008: InAppPyValidationError('Production receipt was sent to the sandbox env'),
 }
@@ -21,14 +24,23 @@ class AppStoreValidator(object):
     bundle_id = None
     sandbox = None
     url = None
+    auto_retry_wrong_env_request = False
 
-    def __init__(self, bundle_id, sandbox=False):
+    def __init__(self, bundle_id, sandbox=False, auto_retry_wrong_env_request=False):
+        """ Constructor for AppStoreValidator
+
+        :param bundle_id: apple bundle id
+        :param sandbox: sandbox mode ?
+        :param auto_retry_wrong_env_request: auto retry on wrong env ?
+        """
         self.bundle_id = bundle_id
         self.sandbox = sandbox
 
         if not self.bundle_id:
             raise InAppPyValidationError('`bundle_id` cannot be empty')
 
+        self.auto_retry_wrong_env_request = auto_retry_wrong_env_request
+
         self._change_url_by_sandbox()
 
     def _change_url_by_sandbox(self):
@@ -38,21 +50,35 @@ class AppStoreValidator(object):
     def post_json(self, request_json):
         self._change_url_by_sandbox()
 
-        return requests.post(self.url, json=request_json).json()
-
-    def validate(self, receipt, shared_secret=None):
-        receipt_json = {'receipt-data': receipt}
-
-        # if shared secret is provided, attach it as `password`.
-        if shared_secret:
-            receipt_json['password'] = shared_secret
-
         try:
-            api_response = self.post_json(receipt_json)
+            return requests.post(self.url, json=request_json).json()
         except (ValueError, RequestException):
             raise InAppPyValidationError('HTTP error')
 
+    def validate(self, receipt, shared_secret=None):
+        """ Validates receipt against apple services.
+
+        :param receipt: receipt
+        :param shared_secret: optional shared secret.
+        :return: validation result or exception.
+        """
+        receipt_json = {'receipt-data': receipt}
+
+        if shared_secret:
+            receipt_json['password'] = shared_secret
+
+        # Do a request.
+        api_response = self.post_json(receipt_json)
         status = api_response['status']
+
+        # Check retry case.
+        if self.auto_retry_wrong_env_request and status in [21007, 21008]:
+            # switch environment
+            self.sandbox = not self.sandbox
+
+            api_response = self.post_json(receipt_json)
+            status = api_response['status']
+
         if status != api_result_ok:
             error = api_result_errors.get(status, InAppPyValidationError('Unknown API status'))
             error.raw_response = api_response
diff --git a/setup.py b/setup.py
index 8fab1fd..df0ca90 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ from setuptools import setup
 
 setup(
     name='inapppy',
-    version='0.4',
+    version='0.5',
     packages=['inapppy'],
     install_requires=['rsa', 'requests'],
     description="In-app purchase validation library for Apple AppStore and GooglePlay.",