va.py 1.54 KB
# Winpay Create Virtual Account
from base64 import b64encode
from datetime import timedelta
from logging import getLogger
import requests
from opensipkd.waktu import create_now
from .signature import (
    generator,
    time_to_str,
    )


class HttpErr(Exception):
    pass


def create(
        url: str, private_key: bytes, partner_id: str, customer_no: str,
        va_name: str, amount: int, channel: str, trx_id: str, expired_days=1):
    log = getLogger('create_va()')
    timestamp = create_now()
    timestamp_str = time_to_str(timestamp)
    expired_timestamp = timestamp + timedelta(expired_days)
    expired_str = time_to_str(expired_timestamp)
    data = dict(
        customerNo=customer_no,
        virtualAccountName=va_name,
        trxId=trx_id,
        totalAmount=dict(value=amount, currency='IDR'),
        virtualAccountTrxType='c',
        expiredDate=expired_str,
        additionalInfo=dict(channel=channel))
    signature = generator(private_key, data, timestamp)
    signature_b64 = b64encode(signature)
    signature_b64 = signature_b64.decode('utf-8')
    headers = {
        'X-TIMESTAMP': timestamp_str,
        'X-SIGNATURE': signature_b64,
        'X-PARTNER-ID': partner_id,
        'X-EXTERNAL-ID': trx_id,
        'CHANNEL-ID': channel}
    log.info(f'Request: Headers {headers}, Data {data}')
    r = requests.post(url, headers=headers, json=data)
    if r.status_code != 200:
        log.error(f'HTTP {r.status_code}, {[r.text]}')
        raise HttpErr(r.status_code, r.text)
    d = r.json()
    log.info(f'Response: {d}')
    return d