Debian Codegraph @

addons/l10n_tw_edi_ecpay/utils.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import base64
4 import datetime
5 import json
6 import pytz
7 import urllib.parse
8 import requests
9 from cryptography.hazmat.primitives import padding
10 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
11
12
13 PRODUCTION_URL = "https://einvoice.ecpay.com.tw/"
14 STAGING_URL = "https://einvoice-stage.ecpay.com.tw/"
15 TIMEOUT = 20
16
17
18 def transfer_time(time_before):
19 ecpay_time = datetime.datetime.strptime(time_before, "%Y-%m-%d %H:%M:%S")
20 ecpay_time = pytz.timezone('Asia/Taipei').localize(ecpay_time)
21 return ecpay_time.astimezone(pytz.UTC).strftime("%Y-%m-%d %H:%M:%S")
22
23
24 def convert_utc_time_to_tw_time(utc_datetime):
25 """
26 Converts UTC datetime object to a TW date string.
27
28 :param utc_datetime: datetime.datetime(2026, 1, 23, 18, 0, 0)
29 :return: "2026-01-24"
30 """
31 if utc_datetime.tzinfo is None:
32 utc_datetime = pytz.utc.localize(utc_datetime)
33
34 tw_tz = pytz.timezone('Asia/Taipei')
35 tw_time = utc_datetime.astimezone(tw_tz)
36
37 return tw_time.strftime("%Y-%m-%d")
38
39
40 def encrypt(data, cipher):
41 padder = padding.PKCS7(128).padder()
42 padded_data = padder.update(data.encode("utf-8")) + padder.finalize()
43 encryptor = cipher.encryptor()
44 return encryptor.update(padded_data) + encryptor.finalize()
45
46
47 def decrypt(data, cipher):
48 decryptor = cipher.decryptor()
49 decrypted_data = decryptor.update(base64.b64decode(data)) + decryptor.finalize()
50 unpadder = padding.PKCS7(128).unpadder()
51 return unpadder.update(decrypted_data) + unpadder.finalize()
52
53
54 def call_ecpay_api(endpoint, json_data, company_id, is_b2b=False):
55 """
56 Function for interacting with the ECPay e-invoice API.
57
58 This function provides a structured way to configure and prepare requests
59 for ECPay's B2B or B2C invoice services
60
61 AES-CBC encryption is used for hashashkey and hashIV:
62 https://developers.ecpay.com.tw/?p=22160
63 """
64 url = STAGING_URL if company_id.l10n_tw_edi_ecpay_staging_mode else PRODUCTION_URL
65 request_url = url + ("B2BInvoice" if is_b2b else "B2CInvoice")
66 hashkey = company_id.sudo().l10n_tw_edi_ecpay_hashkey
67 hashIV = company_id.sudo().l10n_tw_edi_ecpay_hashIV
68 try:
69 cipher = Cipher(algorithms.AES(hashkey.encode('utf-8')), modes.CBC(hashIV.encode('utf-8')))
70 # Encode the JSON string firstly then do AES encryption
71 urlencode_data = urllib.parse.quote(json.dumps(json_data))
72 encrypted_data = encrypt(urlencode_data, cipher)
73 json_body = {
74 "MerchantID": company_id.sudo().l10n_tw_edi_ecpay_merchant_id,
75 "RqHeader": {
76 "Timestamp": round(datetime.datetime.now().timestamp()),
77 },
78 "Data": base64.b64encode(encrypted_data).decode('utf-8'),
79 }
80 response = requests.post(request_url + endpoint, json=json_body, timeout=TIMEOUT)
81 response_json = response.json()
82 if response.status_code != 200:
83 return {
84 "RtnCode": 0,
85 "RtnMsg": company_id.env._("ECPay API Error: %(error_message)s.", error_message=response_json.get("TransMsg")),
86 }
87
88 if not response_json.get("Data"):
89 return {
90 "RtnCode": 0,
91 "RtnMsg": company_id.env._("ECPay API Error: %(error_message)s, Error Code: %(error_code)s", error_message=response_json.get("TransMsg"), error_code=response_json.get("TransCode")),
92 }
93 # AES decryption to the Data firstly then decode
94 decrypted_response_data = decrypt(response_json["Data"], cipher)
95 unquoted_data = urllib.parse.unquote(decrypted_response_data)
96 json_data = json.loads(unquoted_data)
97 except ValueError as e:
98 if "key" in str(e):
99 error_message = company_id.env._("ECPay API Error: Invalid Hashkey. Please check your ECPay configuration.")
100 elif "IV" in str(e):
101 error_message = company_id.env._("ECPay API Error: Invalid HashIV. Please check your ECPay configuration.")
102 else:
103 error_message = company_id.env._("ECPay API Error: %(error_message)s", error_message=str(e))
104 return {
105 "RtnCode": 0,
106 "RtnMsg": error_message,
107 }
108 return json_data