Bläddra i källkod

IAP苹果内购 -- App Store服务器通知代码

linhaohong 1 år sedan
förälder
incheckning
dc02ae6ecb
1 ändrade filer med 46 tillägg och 3 borttagningar
  1. 46 3
      Controller/InAppPurchaseController.py

+ 46 - 3
Controller/InAppPurchaseController.py

@@ -3,18 +3,21 @@
 # @Time      : 2024/6/21 9:10
 import logging
 import time
-
+import json
 from appstoreserverlibrary.api_client import AppStoreServerAPIClient, GetTransactionHistoryVersion
 from appstoreserverlibrary.models.Environment import Environment
 from appstoreserverlibrary.receipt_utility import ReceiptUtility
 from appstoreserverlibrary.models.HistoryResponse import HistoryResponse
 from appstoreserverlibrary.models.TransactionHistoryRequest import TransactionHistoryRequest, ProductType, Order
 from appstoreserverlibrary.signed_data_verifier import SignedDataVerifier
+
 from cryptography.hazmat.backends import default_backend
 from cryptography.hazmat.primitives.serialization import load_pem_private_key
 
 from django.db.models import Q
 from django.views import View
+from django.http import HttpResponse
+
 from Ansjer.config import LOGGER, CONFIG_INFO, CONFIG_TEST, PAY_TYPE_IN_APP_PURCHASE, BASE_DIR
 from Controller.CheckUserData import DataValid
 from Model.models import Order_Model, Store_Meal, Device_Info, UID_Bucket, Unused_Uid_Meal, AiService, Device_User, \
@@ -293,6 +296,46 @@ class InAppPurchaseView(View):
         ali_sms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_ms, temp_msg=temp_msg)
 
     @staticmethod
-    def app_store_server_notifications(request_dict):
+    def app_store_server_notifications(request):
         logger = logging.getLogger('apple_pay')
-        logger.info('App Store服务器通知参数:{}'.format(request_dict))
+        logger.info('App Store服务器通知参数:{}'.format(request.POST))
+        if request.method == 'POST':
+            try:
+                payload = json.loads(request.body.decode('utf-8'))
+                # 获取 signedPayload
+                signed_payload = payload.get('signedPayload')
+                if not signed_payload:
+                    return HttpResponse(status=400)
+
+                bundle_id = 'com.ansjer.zccloud'
+                environment = ENV
+                root_certificates = []
+                for cert_name in [
+                    'AppleIncRootCertificate.cer', 'AppleComputerRootCertificate.cer',
+                    'AppleRootCA-G2.cer', 'AppleRootCA-G3.cer'
+                ]:
+                    cert_path = '{}/Ansjer/file/in_app_purchase/{}'.format(BASE_DIR, cert_name)
+                    with open(cert_path, 'rb') as file:
+                        # 读取文件内容
+                        root_certificates.append(file.read())
+
+                enable_online_checks = True
+                app_apple_id = None  # 生产环境必需
+
+                # 验证签名并解码 payload
+                verifier = SignedDataVerifier(
+                    root_certificates, enable_online_checks, environment, bundle_id, app_apple_id)
+                decoded_payload = verifier.verify_and_decode_notification(signed_payload)
+
+                LOGGER.info(f"打印decoded_payload{decoded_payload}")
+
+                if decoded_payload.notificationType == "DID_RENEW":
+                    # 处理订阅续费
+                    pass
+
+                return HttpResponse(status=200)
+
+            except Exception as e:
+                LOGGER.info('App Store服务器通知异常:{}'.
+                            format('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e))))
+                return HttpResponse(status=500)