paddle verify signature

mail@pastecode.io avatar
unknown
python
a year ago
2.6 kB
6
Indexable
Never
import hmac
import hashlib
import json
import typing


def verify_signature(key: str, data: typing.Union[bytes, str, dict], paddle_signature_header: str) -> bool:
    ts, h1 = paddle_signature_header.split(";")
    ts, h1 = ts.split("=")[1], h1.split("=")[1]
    data_ = None
    if isinstance(data, str):
        # in case someone passed json including spaces
        data_ = json.dumps(json.loads(data), separators=(",", ":"))
    if isinstance(data, dict):
        data_ = json.dumps(data, separators=(",", ":"))
    if isinstance(data, bytes):
        data_ = data.decode("utf-8")
    signature = hmac.new(
        key=key.encode("utf-8"), msg=f"{ts}:{data_}".encode("utf-8"), digestmod=hashlib.sha256
    ).hexdigest()
    return h1 == signature


if __name__ == '__main__':
    assert verify_signature(
        key="ENTER YOUR KEY",
        data='{"data": {"id": "sub_01gzxp3yt0a2q39c86961zqj03", "items": [{"price": {"id": "pri_01gzc006492hq2y74ne8g646sr", "tax_mode": "account_setting", "product_id": "pro_01gyerkt4qkb81ppj070v1gy6a", "unit_price": {"amount": "1000", "currency_code": null}, "description": "my first price", "trial_period": null, "billing_cycle": {"interval": "month", "frequency": 1}}, "status": "active", "quantity": 1, "recurring": true, "created_at": "2023-05-08T12:41:55.264511Z", "updated_at": "2023-05-08T12:41:55.264511Z", "next_billed_at": "2023-06-08T12:41:53.900542Z", "previously_billed_at": "2023-05-08T12:41:53.900542Z"}], "status": "active", "paused_at": null, "address_id": "add_01gzxp1y7rw3gf1gammz9805er", "created_at": "2023-05-08T12:41:55.26451Z", "started_at": "2023-05-08T12:41:53.900542Z", "updated_at": "2023-05-08T12:41:55.26451Z", "business_id": null, "canceled_at": null, "custom_data": {"seat_object_id": 11, "seat_content_type": 123}, "customer_id": "ctm_01gzxp1y5wg81exhgjxcdnsn2f", "billing_cycle": {"interval": "month", "frequency": 1}, "currency_code": "EUR", "next_billed_at": "2023-06-08T12:41:53.900542Z", "billing_details": null, "collection_mode": "automatic", "first_billed_at": "2023-05-08T12:41:53.900542Z", "next_transaction": null, "scheduled_change": null, "current_billing_period": {"ends_at": "2023-06-08T12:41:53.900542Z", "starts_at": "2023-05-08T12:41:53.900542Z"}, "recurring_transaction_details": null}, "event_id": "evt_01gzxp3z2wthxxgdkc0gfy5yrm", "event_type": "subscription.activated", "occurred_at": "2023-05-08T12:41:55.319797Z", "notification_id": "ntf_01gzxp3z4zxb9x0kphajmcjwr2"}',
        paddle_signature_header="ts=1683549715;h1=dec8665cfede7e3878dfddb035e3494de4d7b6587b69dc4f37c718e3a8f88ad6"
    )