__init__.py 11.8 KB
import json

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

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

from . import Nicepay


# setMandatoryParameter


class Vendor(object): #VendorClass
    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

        args = kwargs
        self.values = args["values"]
        self.v_produk_kd = vendor_produk.kode
        customer = Partner.query_id(self.values["customer_id"]).first()
        if customer:
            self.cust_kd = customer.kode
            self.cust_inv_no = "cust_inv_no" in self.values \
                           and self.values["cust_inv_no"] or None
            self.agra_cust_inv_no = self.cust_kd and self.cust_inv_no \
                                    and self.cust_kd + self.cust_inv_no or None
        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.ip = Nicepay.userIp()
        self.customer = dict(
            barang='GOODSNM',
            nama='BILLING NAME',
            phone='08123456789',
            email='ADETEST01@GMAIL.COM',
            kota='JAKARTA',
            provinsi='JAKARTA',
            kd_pos='14350',
            negara='INDONESIA',
        )

        # self.cust_trx = 'REFERENCENO'
        # self.pay_method = '01'
        self.url = 'https://www.merchant.com/Notification'

        self.bank_cd, self.pay_method = self.v_produk_kd.split('-')
        self.va_typ = "float"
        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.values["amount"])
        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"


    def request_payment(self, response):
        Nicepay.requestData={}
        Nicepay.set('timeStamp', self.time_stamp)
        # '20180109181300'
        # Nicepay.set('reffenceNo', self.time_stamp)  #'20180109181300'
        Nicepay.set('referenceNo', self.agra_cust_inv_no)
        #'5a44213129be40320ef1a4b57095bfa61cd3ff0436bc442a9d82232e62203f37')
        Nicepay.set('tXid', response["tXid"])  # 'IONPAYTEST02201802051512483907'get tXid from register first
        Nicepay.set('cardNo', self.values["card_no"]) #'5409120028181901'
        Nicepay.set('cardExpYymm', self.values["card_exp"])  # format Yymm '2012'
        Nicepay.set('cardCvv', self.values["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.agra_cust_inv_no:
            return
        Nicepay.set('timeStamp', self.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.agra_cust_inv_no)
        Nicepay.set('userIP', self.ip)
        Nicepay.set('dbProcessUrl', self.url)
        Nicepay.set('merchantToken', Nicepay.merchantToken())
        return True

    def set_billing_param(self):
        if not self.customer:
            return
        Nicepay.set('goodsNm', self.customer['barang'])
        Nicepay.set('billingNm', self.customer['nama'])
        Nicepay.set('billingPhone', self.customer['phone'])
        Nicepay.set('billingEmail', self.customer['email'])
        Nicepay.set('billingCity', self.customer['kota'])
        Nicepay.set('billingState', self.customer['provinsi'])
        Nicepay.set('billingPostCd', self.customer['kd_pos'])
        Nicepay.set('billingCountry', self.customer['negara'])
        return True

    def set_optional_param(self):
        pass
        # setOptionalParameter
        # Nicepay.set('billingAddr', 'Billing Address')
        # Nicepay.set('deliveryNm', 'Buyer Name')
        # Nicepay.set('deliveryPhone', '02112345678')
        # Nicepay.set('deliveryAddr', 'Billing Address')
        # Nicepay.set('deliveryCity', 'Jakarta')
        # Nicepay.set('deliveryState', 'Jakarta')
        # Nicepay.set('deliveryPostCd', '12345')
        # Nicepay.set('deliveryCountry', 'Indonesia')
        # Nicepay.set('vat', '0')
        # Nicepay.set('fee', '0')
        # Nicepay.set('notaxAmt', '0')
        # Nicepay.set('description', 'Description')
        # Nicepay.set('reqDt', '20160301')   # Format (YYYYMMDD)
        # Nicepay.set('reqTm', '135959')   # Format (HHiiss)
        # Nicepay.set('reqDomain', 'merchant.com')
        # Nicepay.set('reqServerIP', '127.0.0.1')
        # Nicepay.set('reqClientVer', '1.0')
        # Nicepay.set('userSessionID', 'userSessionID')
        # Nicepay.set('userAgent', 'Mozilla')
        # Nicepay.set('userLanguage', 'en-US')


    def inquiry(self):
        Nicepay.requestData = {}
        if not self.set_static_params() or not self.set_billing_param():
            return
        Nicepay.set('cartData', '{}')
        # For Credit Card (Don't forgot change payMethod to '01')
        if self.pay_method == '01':
            Nicepay.set('instmntType', '2')
            Nicepay.set('instmntMon', '1')
            if (self.reccuring):
                # For Credit Card Reccuring Only
                Nicepay.set('recurrOpt', '0')

        # 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)
            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

        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.valid_date)  # Format (YYYYMMDD)
                Nicepay.set('payValidTm', self.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
        # self.save_log('inquiry')

        # result = {}
        resultData = Nicepay.niceRegister()
        response = json.loads(resultData)

        # Jika kartu kredit
        if self.pay_method == '01':
            payment = self.request_payment(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()
        #
        if response['resultCd'] == '0000':
            result["resultCd"]=response['resultCd']
            result["resultMsg"]=response['resultMsg']
            result["tXid"]=response['tXid']
            result["referenceNo"]=response['referenceNo']
            result["payMethod"]=response['payMethod']
            result["amount"]=response['amt']
            result["transDt"]=response['transDt']
            result["transTm"]=response['transTm']
            if response['goodsNm']:
                result["goodsNm"]=response['goodsNm']
            if response['billingNm']:
                result["billingNm"]=response['billingNm']
            if response['currency']:
                result["currency"]=response['currency']
            elif response['payMethod'] == "02":
                result["bankCd"]=response['bankCd']
                result["vacctNo"]=response['vacctNo']
                result["vacctValidDt"]=response['vacctValidDt']
                result["vacctValidTm"]=response['vacctValidTm']
            elif response['payMethod'] == "03":
                result["mitraCd"]=response['mitraCd']
                result["payNo"]=response['payNo']
                result["vacctValidDt"]=response['payValidDt']
                result["vacctValidTm"]=response['payValidTm']
            elif result['payMethod'] == "04":
                result["mitraCd"]=response['mitraCd']
                result["receiptCode"]=response['receiptCode']
            elif result['payMethod'] == "05":
                result["mitraCd"]=response['mitraCd']
                result["receiptCode"]='receiptCode' in response and response['receiptCode'] or ''
        else:
            result["resultCd"]=response['resultCd']
            result["resultMsg"]=response['resultMsg']
        self.result = response
        # 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
     ….
    }  

"""