__init__.py 16 KB
import json
import base64
import logging
from opensipkd.base import get_settings
from pyramid.httpexceptions import HTTPFound
from . import Nicepay
from ..vendor import VendorClass

log = logging.getLogger(__name__)


class Vendor(VendorClass): #VendorClass
    def __init__(self, vendor_produk, invoice_det, **kwargs):
        VendorClass.__init__(self, vendor_produk, invoice_det=invoice_det, **kwargs)
        settings = get_settings()
        self.mid = 'np_mid' in settings and settings['np_mid'] or None
        self.key = 'np_key' in settings and settings['np_key'] or None
        self.url = 'np_url' in settings and settings['np_url'] or None
        self.callback_url = 'np_callback' in settings and settings['np_callback'] or \
                            'https://www.merchant.com/Notification'
        self.notify_url = 'np_notify' in settings and settings['np_notify'] or \
                            'https://www.merchant.com/Notification'
        key = ":".join([self.mid, self.key]).encode()
        self.auth = base64.b64encode(key).decode()
        self.v_produk_kd = vendor_produk.kode
        if "ccard" in kwargs:
            ccard = kwargs["ccard"]
            if ccard:
                self.card_cvv = ccard["card_cvv"]
                self.card_exp = ccard["card_exp"]
                self.card_name = ccard["card_name"]

        customer = self.invoice_det.customer
        if customer:
            self.cust_kd = customer.kode
            self.cust_inv_no = self.invoice_det.cust_inv_no

        self.bank_cd, self.pay_method = self.v_produk_kd.split('-')
        self.va_typ = None
        self.reccuring = False
        self.amt = str(self.invoice_det.amt_sell)

    # setMandatoryParameter
    def request_payment(self, response):
        Nicepay.requestData={}
        Nicepay.set('timeStamp', self.invoice_det.time_stamp)
        Nicepay.set('referenceNo', self.cust_inv_no)
        Nicepay.set('tXid', response["tXid"])
        Nicepay.set('cardNo', self.invoice_det.card_no)
        Nicepay.set('cardExpYymm', self.invoice_det.card_exp)  # format Yymm '2012'
        Nicepay.set('cardCvv', self.invoice_det.card_cvv)
        Nicepay.set('recurringToken', '')
        Nicepay.set('preauthToken', '')
        Nicepay.set('clickPayNo', '')
        Nicepay.set('dataField3', '')
        Nicepay.set('clickPayToken', '')
        Nicepay.set('callBackUrl', self.callback_url)
        result = Nicepay.nicePayment()
        return result

    def set_static_params(self):
        if not self.cust_inv_no:
            return
        Nicepay.set('timeStamp', self.invoice_det.inv_time_stamp) #
        Nicepay.set('iMid', self.mid)
        Nicepay.set('payMethod', self.pay_method)
        Nicepay.set('currency', 'IDR')
        # Nicepay.set('amt', self.amt)
        Nicepay.set('referenceNo', self.cust_inv_no)
        Nicepay.set('userIP', self.invoice_det.inv_cust_ip)
        Nicepay.set('dbProcessUrl', self.notify_url)
        # Nicepay.set('merchantKey', self.key)
        Nicepay.merchantKey = self.key
        Nicepay.set('merchantToken', Nicepay.merchantToken())
        # Nicepay.set("userLanguage", "en-US")
        Nicepay.set("userLanguage", "")
        Nicepay.set('reqClientVer', '2.0')
        return True

    def set_billing_param(self):
        if not self.invoice_det:
            return
        Nicepay.set('goodsNm', self.invoice_det.notes)
        Nicepay.set('billingNm', self.invoice_det.inv_cust_nm)
        Nicepay.set('billingPhone', self.invoice_det.inv_cust_phone)
        Nicepay.set('billingEmail', self.invoice_det.inv_cust_email)
        Nicepay.set('billingCity', self.invoice_det.inv_cust_city)
        Nicepay.set('billingState', self.invoice_det.inv_cust_state)
        Nicepay.set('billingPostCd', self.invoice_det.inv_cust_pos)
        Nicepay.set('billingCountry', self.invoice_det.inv_cust_country)
        Nicepay.set('amt', str(self.invoice_det.amt_sell))

        Nicepay.set('billingAddr', self.invoice_det.inv_cust_addr)
        Nicepay.set('description', self.invoice_det.notes)
        Nicepay.set('reqDomain', self.invoice_det.domain)
        Nicepay.set('reqServerIP', self.invoice_det.server_ip)
        Nicepay.set('userAgent', self.invoice_det.inv_cust_agent)
        Nicepay.set('userIP', self.invoice_det.inv_cust_ip)
        Nicepay.set('userSessionID', self.invoice_det.inv_cust_session)

        return True

    def set_optional_param(self):
        # pass
        # setOptionalParameter
        Nicepay.set('deliveryNm', self.invoice_det.delivery_nm)
        Nicepay.set('deliveryPhone', self.invoice_det.delivery_phone)
        Nicepay.set('deliveryAddr', self.invoice_det.delivery_addr)
        Nicepay.set('deliveryCity', self.invoice_det.delivery_city)
        Nicepay.set('deliveryState', self.invoice_det.delivery_state)
        Nicepay.set('deliveryPostCd', self.invoice_det.delivery_pos)
        Nicepay.set('deliveryCountry', self.invoice_det.delivery_country)
        # print('>>> INVOICE DET:', self.invoice_det.vat, type(self.invoice_det.vat),
        #       self.invoice_det.fee, type(self.invoice_det.fee),
        #       self.invoice_det.notax_amt, type(self.invoice_det.notax_amt))
        Nicepay.set('vat', self.invoice_det.vat and int(self.invoice_det.vat) > 0 and \
                    str(self.invoice_det.vat) or '')
        Nicepay.set('fee', self.invoice_det.fee and int(self.invoice_det.fee) > 0 and \
                    str(self.invoice_det.fee) or '')
        no_tax_amt = self.invoice_det.notax_amt and int(self.invoice_det.notax_amt) > 0 and\
                     str(self.invoice_det.notax_amt) or ''
        Nicepay.set('notaxAmt', no_tax_amt)
        # Nicepay.set('reqDt', self.invoice_det.req_dt)   # Format (YYYYMMDD)
        # Nicepay.set('reqTm', self.invoice_det.req_tm)   # Format (HHiiss)
        Nicepay.set('reqDt', '')  # Format (YYYYMMDD)
        Nicepay.set('reqTm', '')   # Format (HHiiss)
        Nicepay.set('reqClientVer', '')
        Nicepay.set('instmntType', '')
        Nicepay.set('instmntMon', '')
        Nicepay.set('mRefNo', '')
        # result dari nicepay
        # Nicepay.set('tXid', '')
        # Nicepay.set('transDt', '')
        # Nicepay.set('transTm', '')

        Nicepay.set('payValidDt', '')
        Nicepay.set('payValidTm', '')
        Nicepay.set('recurrOpt', '')

    def register(self):
        Nicepay.requestData = {}
        if not self.set_billing_param() or not self.set_static_params():
            return

        data = str(json.dumps(self.invoice_det.cart))
        cart_data = data and '{}'.format(data) or '{}'
        Nicepay.set('cartData', cart_data)
        self.set_optional_param()
        # For Credit Card (Don't forgot change payMethod to '01')
        if self.pay_method == '01':
            Nicepay.set('recurrOpt', str(self.invoice_det.recurr_opt))
            Nicepay.set('instmntMon', str(self.invoice_det.instmnt_mon) or '')
            Nicepay.set('instmntType', str(self.invoice_det.instmnt_type) or '')

        # For Virtual Account (Don't forgot change payMethod to '02')
        elif self.pay_method == '02':
            Nicepay.set('bankCd', self.bank_cd)
            Nicepay.set('vacctValidDt', self.invoice_det.inv_valid_date)
            Nicepay.set('vacctValidTm', self.invoice_det.inv_valid_time)
            if self.invoice_det.inv_cust_va:
                self.va_typ = 'fixed'
                Nicepay.set('merFixAcctId', self.invoice_det.inv_cust_va)

            else:
                self.va_typ = 'float'
                Nicepay.set('merFixAcctId', '')

        # For CVS
        # (Don't forgot change payMethod to '03'/'04'/'05')
        elif self.pay_method in ['03']:
            Nicepay.set('mitraCd', self.bank_cd)
            # For CVS Only
            Nicepay.set('payValidDt', self.invoice_det.inv_valid_date)  # Format (YYYYMMDD)
            Nicepay.set('payValidTm', self.invoice_det.inv_valid_time)  # Format (HHiiss)

        elif self.pay_method == '04':
            Nicepay.set('mRefNo', self.cust_inv_no)
            Nicepay.set('bankCd', self.bank_cd)

        elif self.pay_method == '05':
            Nicepay.set('mitraCd', self.bank_cd)

        elif self.pay_method == '06':
            Nicepay.set('recurrOpt', str(self.invoice_det.recurr_opt))
            Nicepay.set('instmntMon', str(self.invoice_det.instmnt_mon) or '')
            Nicepay.set('instmntType', str(self.invoice_det.instmnt_type) or '')
            Nicepay.set('mitraCd', self.bank_cd)
            Nicepay.set('payValidDt', self.invoice_det.inv_valid_date)  # Format (YYYYMMDD)
            Nicepay.set('payValidTm', self.invoice_det.inv_valid_time)  # Format (HHiiss)

        # Process to nice pay register
        self.request = Nicepay.requestData
        log.info("NP REQUEST: {}".format(json.dumps(self.request)))
        self.save_log('inquiry')
        result_data = Nicepay.niceRegister()
        response = json.loads(result_data)
        self.response = response
        log.info("NP RESPONSE: {}".format(json.dumps(self.response)))
        self.response = response
        # # Payment Response String Format
        if 'resultCd' not in response:
            self.result = dict(
                error="Connection Timeout. Please Try Again!"
            )
            self.save_log(typ="inquiry")
            return
        else:
            result = dict()

        result_code = int(response['resultCd'])
        result["code"] = result_code
        result["message"] = response['resultMsg']
        if result_code == 0: # or self.pay_method == '01':
            result["currency"] = response['currency']
            # result["tx_id"] = response['tXid']
            # result['trans_dt'] = response['transDt']
            # result['trans_tm'] = response['transTm']
            result["amount"] = response['amt']
            result["invoice_no"] = response['referenceNo']
            result["description"] = response['description']
            # result['pay_method'] = self.pay_method
            if self.pay_method == "01":
                result["code"] = 0
                result["message"] = 'SUCCESS'
                request_data = Nicepay.requestData
                settings = get_settings()
                call_back_url = settings['switcher_call_back_url']
                result.update(dict(
                    time_stamp=request_data['timeStamp'],
                    tx_id=self.invoice_det.tx_id,
                    merchant_token=request_data['merchantToken'],
                    call_back_url=call_back_url,
                ))
                # todo result harus html
                settings = get_settings()
                form = """<!DOCTYPE html>
                <html lang="en-us">
                <head>
                    <meta http-equiv="content-type" content="text/html; charset=utf-8">
                    <title>Payment</title>
                </head>
                <body>
                <form action="{url}/api/merchant/payment" method="post" name="payment">
                 <input type="text" name="timeStamp" value="{time_stamp}">
                 <input type="text" name="tXid" value="{tx_id}">
                 <input type="text" name="merchantToken" value="{merchant_token}">
                 <input type="text" name="cardNo" value="{card_no}">
                 <input type="text" name="cardExpYymm" value="{card_exp}">
                 <input type="text" name="cardCvv" value="{card_cvv}">
                 <input type="text" name="cardHolderNm" value="{card_holder_nm}">
                 <input type="text" name="callBackUrl" value="{call_back_url}">
                 <button type="submit" value="Submit" name="submit">Submit</button>
                </form>
                <script>
                    //document.write("Hello World!")
                </script>
                <noscript>Your browser does not support JavaScript!</noscript> 
                </body>
                </html>
                """.format(
                     url=settings["_host"],
                     time_stamp=request_data['timeStamp'],
                     tx_id=result['tx_id'],
                     merchant_token=request_data['merchantToken'],
                     card_no=self.invoice_det.card_no,
                     card_exp=self.card_exp,
                     card_cvv=self.card_cvv,
                     card_holder_nm=self.card_name,
                     call_back_url=call_back_url,
                )
                result['form'] = form
            elif self.pay_method == "02":
                result["va"] = dict(
                    vacct_no=response['vacctNo'],
                    valid_date=response['vacctValidDt'],
                    valid_time=response['vacctValidTm'],

                )
                self.invoice_det.card_no = response['vacctNo']

            elif self.pay_method == "03":
                # CVS
                result["cvs"] = dict(
                    pay_no=response['payNo'],
                    valid_date=response['payValidDt'],
                    valid_time=response['payValidTm'],

                )
                self.invoice_det.card_no = response['payNo']
            elif self.pay_method == "04":
                # clickpay
                result["receipt_code"]=response['receiptCode']
            elif self.pay_method == "05":
                # e-wallet
                result["receipt_code"]='receiptCode' in response and response['receiptCode'] or ''
            elif self.pay_method == "06":
                # akulaku
                pass


        self.result = result
        # self.save_log('inquiry')
        self.invoice_det.tx_id=response["tXid"]
        self.invoice_det.trans_dt=response["transDt"]
        self.invoice_det.trans_tm=response["transTm"]
        self.save_log(typ="inquiry")

        return dict(data=result)

    def payment(self):
        url = "{}/payment".format(self.url)
        return HTTPFound(url)

# https://api.nicepay.co.id/nicepay/direct/v2/registration
# Request Body
"""
{
     "deliveryPhone": "62-21-0000-0000",
     "mitraCd": "ALMA",
     "fee": "0",
     "amt": "1000",
     "description": "this is test transaction!!",
     "notaxAmt": "0",
     "reqDomain": "localhost",
     "userLanguage": "ko-KR,en-US;q=0.8,ko;q=0.6,en;q=0.4",
     "vacctValidDt": "",
     "billingEmail": "no-reply@ionpay.net",
     "merFixAcctId": "",
     "payMethod": "01",
     "deliveryAddr": "Jalan Jenderal Gatot Subroto Kav.57",
     "billingCountry": "ID",
     "userIP": "0:0:0:0:0:0:0:1",
     "instmntMon": "1",
     "currency": "IDR",
     "payValidDt": "",
     "deliveryCity": "Jakarta",
     "merchantToken": "b5149659e1a2f1271fb0833f8ea20e174b6fd389db26bc6ad036cc0dae6fa797",
     "goodsNm": "T-1000",
     "referenceNo": "OrdNo2017717942577",
     "vat": "0",
     "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/60.0.3112.101 Safari/537.36",
     "billingState": "Jakarta",
     "userSessionID": "697D6922C961070967D3BA1BA5699C2C",
     "instmntType": "1",
     "deliveryNm": "HongGilDong",
     "deliveryPostCd": "12950",
     "reqClientVer": "",
     "iMid": "IONPAYTEST",
     "billingNm": "HongGilDong",
     "timeStamp": "20170822170942",
     "dbProcessUrl": "http://127.0.0.1:8080/nicepay/test3/dbProcess.do",
     "payValidTm": "",
     "cartData": "{“count”: “1”,
        “item”: [{“img_url”: “https://www.lecs.com/image/introduction/img_vmd020101.jpg”,
                  “goods_name”: “Jam Tangan Army - Strap Kulit - Hitam”,
                  “goods_detail”: “jumlah 1”,
                  “goods_amt”: “400”}]}",
    "deliveryState": "Jakarta",
    "deliveryCountry": "ID",
    "bankCd": "",
    "billingPostCd": "12950",
    "billingAddr": "Jalan Jenderal Gatot Subroto Kav.57",
    "reqServerIP": "172.29.2.178",
    "vacctValidTm": "",
    "billingPhone": "021-579-00000",
    "billingCity": "Jakarta"
    }  
     // Response Body  
    {
    "resultCd": "0000",
    "resultMsg": "SUCCESS",
    "tXid": "IONPAYTEST01201708221510237472",
    "referenceNo": "OrdNo2017717942577",
    "payMethod": "01",
    "amt": "1000",
    "transDt": "20170822",
    "transTm": "171029",
    "description": "this is test transaction!!",
    "bankCd": null,
    "vacctNo": null,
    "mitraCd": null,
    "payNo": null
     ….
    }  

"""