import json
from applepay import payment as apple
from Ansjer.config import BASE_DIR, LOGGER


class ApplePayObject:
    def __init__(self):
        self.certificate_pem = open('{}/Ansjer/file/applepay/merchant_cert.pem'.format(BASE_DIR), 'rb').read()
        self.private_key_pem = open('{}/Ansjer/file/applepay/merchant_private_key'.format(BASE_DIR), 'rb').read()
        self.root_ca_der = open('{}/Ansjer/file/applepay/AppleRootCA-G3.cer'.format(BASE_DIR), 'rb').read()
        self.aai_ca_der = open('{}/Ansjer/file/applepay/AppleAAICAG3.cer'.format(BASE_DIR), 'rb').read()

    def verify(self, receipt_data):
        # receipt_data = receipt_data.split(',')[1].replace('bytes = ', '').replace(' ', '').replace('}', '')
        # byte_string = bytes.fromhex(receipt_data)
        # payment_str = byte_string.decode("utf-8")
        try:
            payment_json = json.loads(receipt_data)
            payment = apple.Payment(self.certificate_pem, self.private_key_pem, self.root_ca_der, self.aai_ca_der)
            decrypted_str = payment.decrypt(payment_json['header']['ephemeralPublicKey'], payment_json['data'])
            decrypted_json = json.loads(decrypted_str)
            decrypted_json['transactionId'] = payment_json['header']['transactionId']
            return decrypted_json
        except Exception as e:
            LOGGER.info('apple验证失败，错误行数：{},报错：{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return False
