__init__.py 14.2 KB
import json
import base64
import logging

# Import Library (Mandatory)
from datetime import datetime, timedelta

from opensipkd.base import get_settings
from opensipkd.base.models import Partner

from . import Nicepay
from ..vendor import VendorClass

log = logging.getLogger(__name__)

# setMandatoryParameter


class Vendor(VendorClass): #VendorClass
    # def __init__(self, vendor_produk, **kwargs):
    # def __init__(self, vendor_produk, **kwargs):
    #     # VendorClass.__init__(self, vendor_produk, bill_no, **kwargs)
    #     if not vendor_produk or kwargs is None or not "values" in kwargs:
    #         return
    #
    #     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
    #     Nicepay.merchantKey = self.key
    #     Nicepay.iMid = self.mid
    #
    #     self.customer = dict(
    #         barang='GOODSNM',
    #         nama='BILLING NAME',
    #         phone='08123456789',
    #         email='ADETEST01@GMAIL.COM',
    #         kota='JAKARTA',
    #         provinsi='JAKARTA',
    #         kd_pos='14350',
    #         negara='INDONESIA',
    #     )
    #

    def __init__(self, vendor_produk, invoice_det, **kwargs):
        VendorClass.__init__(self, vendor_produk, invoice_det=invoice_det)
        # id_pel, customer_id, cust_trx, row
        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()

        # args = kwargs
        # self.values = args["values"]
        self.v_produk_kd = vendor_produk.kode

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

        # self.cust_trx = 'REFERENCENO'
        # self.pay_method = '01'

        self.bank_cd, self.pay_method = self.v_produk_kd.split('-')
        self.va_typ = None
        # self.notify_url = "dev.agratek.co.id/api/np/notify"
        # self.callback_url = "dev.agratek.co.id/api/np/calllback"
        self.reccuring = False
        self.amt = str(self.invoice_det.amt_sell)
        # now = datetime.now()
        # self.time_stamp = now.strftime("%Y%m%d%H%M%S")
        # tommorow = now + timedelta(days=1)
        # self.valid_date = tommorow.strftime("%Y%m%d")
        # self.valid_time = "235500"
        # self.ip = Nicepay.userIp()

    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", "ko-KR,en-US;q=0.8,ko;q=0.6,en;q=0.4")
        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)
        Nicepay.set('vat', str(self.invoice_det.vat))
        Nicepay.set('fee', str(self.invoice_det.fee))
        Nicepay.set('notaxAmt', str(self.invoice_det.notax_amt))
        Nicepay.set('reqDt', self.invoice_det.req_dt)   # Format (YYYYMMDD)
        Nicepay.set('reqTm', self.invoice_det.req_tm)   # Format (HHiiss)\
        Nicepay.set('reqClientVer', '')
        Nicepay.set('recurrOpt', str(self.invoice_det.recurr_opt))
        Nicepay.set('instmntMon', self.invoice_det.instmnt_mon)
        Nicepay.set('instmntType', self.invoice_det.instmnt_type)
        Nicepay.set('mRefNo', self.invoice_det.m_ref_no)
        Nicepay.set('payValidDt', self.invoice_det.pay_valid_dt)
        Nicepay.set('payValidTm', self.invoice_det.pay_valid_tm)
        Nicepay.set('tXid', self.invoice_det.tx_id)
        Nicepay.set('transDt', self.invoice_det.trans_dt)
        Nicepay.set('transTm', self.invoice_det.trans_tm)

    def register(self):
        Nicepay.requestData = {}
        if not self.set_billing_param() or not self.set_static_params():
            return
        # f9d30f6c972e2b5718751bd087b178534673a91bbac845f8a24e60e8e4abbbc5
        # Nicepay.set('merchantToken', 'a20e500ecd7eb786fcda1761765ca59f344a25716ff0b576f3b42ff4ac9f7224')
        data = str(json.dumps(self.invoice_det.cart))
        # Nicepay.set('cartData', self.invoice_det.cart)
        Nicepay.set('cartData', '{}'.format(data))
        self.set_optional_param()
        # For Credit Card (Don't forgot change payMethod to '01')
        if self.pay_method == '01':
            Nicepay.set('instmntType', self.invoice_det.instmnt_type)
            Nicepay.set('instmntMon', self.invoice_det.instmnt_mon)
            # if self.reccuring:
            #     # For Credit Card Reccuring Only
            Nicepay.set('recurrOpt', '2')

        # 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.valid_date)  # Format (YYYYMMDD)
            # Nicepay.set('vacctValidTm', self.valid_time)  # Format (HHiiss)
            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)

            # if self.va_typ == "fixed":
            #     # For Virtual Account Fix Account
            #     Nicepay.set('merFixAcctId', '12345679')
            #     # length value of merFixAcctId setting By Mid. Contact
            #     # Nicepay IT for Information
            else:
                self.va_typ = 'float'
                Nicepay.set('merFixAcctId', '')

        elif self.pay_method in ['03', '04', '05']:
            # For CVS,ClickPay or E-Wallet
            # (Don't forgot change payMethod to '03'/'04'/'05')
            Nicepay.set('mitraCd', self.bank_cd)
            if self.pay_method == '03':
                # 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':
                # For ClickPay Only
                Nicepay.set('mRefNo', self.cust_inv_no)

        self.set_optional_param()
        self.request = Nicepay.requestData
        log.info("REQUEST: {}".format(json.dumps(self.request)))
        self.save_log('inquiry')
        result_data = Nicepay.niceRegister()
        response = json.loads(result_data)
        self.response = response
        log.info("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!"
            )
            return
        else:
            result = dict()

        result_code = int(response['resultCd'])
        result["code"] = result_code
        result["message"] = response['resultMsg']
        if result_code == 0:
            result["tx_id"] = response['tXid']
            result['trans_dt'] = response['transDt']
            result['trans_tm'] = response['transTm']
            # Jika kartu kredit
            # if self.pay_method == '01':
            #     # C-Card
            #     # payment = self.request_payment(response)
            # elif response['payMethod'] == "02":
            if response['payMethod'] == "02":
                # VA
                result["vacct_no"]=response['vacctNo']
                # result["vacct_valid_dt"]=response['vacctValidDt']
                # result["vacct_valid_tm"]=response['vacctValidTm']
                # result["mer_fix_acct_id"]=response['merFixAcctId']
            elif response['payMethod'] == "03":
                # CVS
                result["pay_no"]=response['payNo']
                # result["pay_valid_dt"]=response['payValidDt']
                # result["pay_valid_tm"]=response['payValidTm']
            elif result['payMethod'] == "04":
                # clickpay
                result["receipt_code"]=response['receiptCode']
            elif result['payMethod'] == "05":
                # e-wallet
                result["receipt_code"]='receiptCode' in response and response['receiptCode'] or ''
            elif result['payMethod'] == "06":
                # akulaku
                pass

        # else:
        #     result["resultCd"]=response['resultCd']
        #     result["resultMsg"]=response['resultMsg']
        self.result = result
        # self.save_log('inquiry')
        return dict(data=result)

# 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
     ….
    }  

"""