Commit 26951636 by Solo Group

cc

1 parent d5170a73
kode,path,nama,status,type
api-merchant-home,/api/merchant/home,Api Merchant Home,1,0
api-merchant,/api/merchant,Api Merchant,1,1
api-vendor-notify,/api/vendor/{name}/notify,Api Vendor Notify,1,0
api-merchant-register,/api/merchant/register,Api Merchant Payment,1,0
api-merchant-payment,/api/merchant/payment,Api Merchant Payment,1,0
api-vendor-notify,/api/vendor/{name}/notify,Api Vendor Notify,1,0
api-vendor-callback,/api/vendor/{name}/callback,Api Vendor Callback,1,0
api-merchant-list,/api/merchant/list,Test Api Merchant,1,0
api-merchant-add,/api/merchant/add,Add Api Merchant,1,0
......
......@@ -12,7 +12,7 @@ from ..tools import JsonRpcInvoiceFoundError, JsonRpcError
log = logging.getLogger(__name__)
def build_request(typ, vendor_produk, partner_log=None):
def build_request(typ, vendor_produk, partner_log=None, **kwargs):
# produk_id = values['produk_id']
# vendor_id = values['vendor_id']
# bill_no = values['destination']
......@@ -28,7 +28,7 @@ def build_request(typ, vendor_produk, partner_log=None):
log.info("Module: %s Pckgs: %s" % (modul, pckgs))
modul = '.' + modul
modules = import_module(modul, pckgs)
cls_module = modules.Vendor(vendor_produk, partner_log)
cls_module = modules.Vendor(vendor_produk, partner_log, **kwargs)
cls = hasattr(cls_module, typ) and getattr(cls_module, typ) or None
if cls:
result = cls()
......
......@@ -6,25 +6,88 @@ from opensipkd.base.models import Partner, flush_row
from opensipkd.base.tools.api import (auth_from_rpc,
JsonRpcProdukNotFoundError, JsonRpcCustomerNotFoundError,
JsonRpcParameterNotFound)
from opensipkd.base.views import BaseView
from opensipkd.pasar.models import Produk, PartnerProduk
from opensipkd.pasar.models.produk import H2hArInvoice, H2hArInvoiceDet, PartnerLog, PartnerPay
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from pyramid_rpc.jsonrpc import jsonrpc_method
from ..tools import JsonRpcInvoiceFoundError, JsonRpcError
from ..tools import JsonRpcInvoiceFoundError, JsonRpcError, get_settings
log = logging.getLogger(__name__)
def save_partner_pay(values, vendor_produk):
partner_pay = PartnerPay()
partner_pay.from_dict(values)
partner_pay.vendor_id = vendor_produk.partner_id
partner_pay.produk_id = vendor_produk.produk.id
flush_row(partner_pay)
return partner_pay
def save_partner_pay(values, vendor_produk, row=None):
if not row:
row = PartnerPay()
row.from_dict(values)
row.vendor_id = vendor_produk.partner_id
row.produk_id = vendor_produk.produk.id
flush_row(row)
return row
def build_register(vendor_produk, partner_log=None):
return build_request('register', vendor_produk, partner_log)
def build_register(vendor_produk, partner_log=None, **kwargs):
return build_request('register', vendor_produk, partner_log, **kwargs)
def set_register_values(dat, customer):
billing = dat["customer"]
deliver_to = dat["deliver_to"]
server = dat["server"]
produk = 'produk' in dat and dat["produk"] or ''
values = dict(
customer_id=customer.id,
# id_pel=dat['id_pel'],
cart=produk or '{}',
cust_inv_no=dat["invoice_no"],
amt_sell=dat['amount'],
notes=dat['description'],
inv_cust_nm=billing['name'],
inv_cust_phone=billing['phone'],
inv_cust_email=billing['email'],
inv_cust_city=billing['city'],
inv_cust_state=billing['state'],
inv_cust_pos=billing['post_code'],
inv_cust_country=billing['country'],
inv_cust_addr=billing['address'],
inv_cust_agent=billing['agent'],
inv_cust_ip=billing['ip'],
inv_cust_session=billing['session_id'],
domain=server['domain'],
server_ip=server['ip'],
description=dat['description'],
delivery_addr=deliver_to['address'],
delivery_city=deliver_to['city'],
delivery_country=deliver_to['country'],
delivery_nm=deliver_to['name'],
delivery_phone=deliver_to['phone'],
delivery_pos=deliver_to['post_code'],
delivery_state=deliver_to['state'],
fee=dat['fee'],
vat=dat['vat'],
req_dt=dat['req_dt'],
req_tm=dat['req_tm'],
inv_time_stamp=dat['time_stamp'] or '',
# va
inv_valid_date='valid_date' in dat and dat['valid_date'] or '',
inv_valid_time='valid_time' in dat and dat['valid_time'] or '',
inv_cust_va='cust_va' in dat and dat['cust_va'] or '',
# m_ref_no=dat['m_ref_no'] or '',
# notax_amt=dat['notax_amt'],
# pay_valid_dt=dat['pay_valid_dt'],
# pay_valid_tm=dat['pay_valid_tm'],
# out
# tx_id=dat['tx_id'],
# trans_dt=dat['trans_dt'],
# trans_tm=dat['trans_tm'],
)
return values
@jsonrpc_method(method='register', endpoint='api-merchant')
......@@ -57,11 +120,13 @@ def register(request, data, **kwargs):
i = 0
if not data:
raise JsonRpcParameterNotFound
is_list = type(data) == list
data = is_list and data or [data]
customer = Partner.query_user(user).first()
if not customer:
raise JsonRpcCustomerNotFoundError
r_data = []
log.info("%s Payment Request: %s" % (customer.kode, data))
for dat in data:
......@@ -72,72 +137,51 @@ def register(request, data, **kwargs):
dat['code'] = -1
else:
inv_no = dat["invoice_no"]
produk = 'produk' in dat and dat["produk"] or ''
# todo cek apakah invoice sudah ada atau belum
ar_invoice = PartnerPay.query().filter_by(cust_inv_no=inv_no).first()
if ar_invoice:
row = PartnerPay.query().filter_by(cust_inv_no=inv_no).first()
if row and row.status>0:
raise JsonRpcInvoiceFoundError()
vendor_kd = "vendor_kd" in dat and dat["vendor_kd"] or None
produk_kd = 'denom' in dat and dat['denom'] or None
vendor_produk = get_vendor_produk(produk_kd)
vendor_produk = get_vendor_produk(produk_kd, vendor_kd=vendor_kd)
if not vendor_produk:
raise JsonRpcProdukNotFoundError
values = dict(
customer_id=customer.id,
id_pel=dat['id_pel'],
cart=produk or '{}',
cust_inv_no=inv_no,
amt_sell=dat['amount'],
notes=dat['goods_nm'],
inv_cust_nm=dat['cust_nm'],
inv_cust_phone=dat['cust_phone'],
inv_cust_email=dat['cust_email'],
inv_cust_city=dat['cust_city'],
inv_cust_state=dat['cust_state'],
inv_cust_pos=dat['cust_pos'],
inv_cust_country=dat['cust_country'],
inv_cust_addr=dat['cust_addr'],
domain=dat['domain'],
server_ip=dat['server_ip'],
inv_cust_agent=dat['cust_agent'],
inv_cust_ip=dat['cust_ip'],
inv_cust_session=dat['cust_session_id'],
description=dat['description'],
delivery_addr=dat['delivery_addr'],
delivery_city=dat['delivery_city'],
delivery_country=dat['delivery_country'],
delivery_nm=dat['delivery_nm'],
delivery_phone=dat['delivery_phone'],
delivery_pos=dat['delivery_pos'],
delivery_state=dat['delivery_state'],
fee=dat['fee'],
vat=dat['vat'],
req_dt=dat['req_dt'],
req_tm=dat['req_tm'],
inv_time_stamp=dat['time_stamp'] or '',
# va
inv_valid_date='valid_date' in dat and dat['valid_date'] or '',
inv_valid_time='valid_time' in dat and dat['valid_time'] or '',
inv_cust_va='cust_va' in dat and dat['cust_va'] or '',
# cc
instmnt_mon='instmnt_mon' in dat and dat['instmnt_mon'] or '',
instmnt_type='instmnt_type' in dat and dat['instmnt_type'] or '',
recurr_opt='recurr_opt' in dat and dat['recurr_opt'] or 0,
# m_ref_no=dat['m_ref_no'] or '',
# notax_amt=dat['notax_amt'],
# pay_valid_dt=dat['pay_valid_dt'],
# pay_valid_tm=dat['pay_valid_tm'],
# out
# tx_id=dat['tx_id'],
# trans_dt=dat['trans_dt'],
# trans_tm=dat['trans_tm'],
)
ar_invoice = save_partner_pay(values, vendor_produk)
values = set_register_values(dat, customer)
credit_card = "credit_card" in dat and dat["credit_card"] or {}
if credit_card:
values.update(dict(
instmnt_mon = 'instmnt_mon' in credit_card and credit_card['instmnt_mon'] or '',
instmnt_type = 'instmnt_type' in credit_card and credit_card['instmnt_type'] or '',
recurr_opt = 'recurr_opt' in credit_card and credit_card['recurr_opt'] or 0,
card_no = 'card_no' in credit_card and credit_card['card_no'] or 0,
))
ccard = (dict(
card_cvv=credit_card["card_cvv"],
card_exp=credit_card["card_exp"],
card_name=credit_card["card_name"]
))
else:
ccard = None
va = "va" in dat and dat["va"] or {}
if va:
values.update(dict(
inv_valid_date='valid_date' in va and va['valid_date'] or '',
inv_valid_time='valid_time' in va and va['valid_time'] or '',
inv_cust_va='fix_acct_id' in va and va['fix_acct_id'] or '',
))
ar_invoice = save_partner_pay(values, vendor_produk, row)
result = build_register(vendor_produk, ar_invoice, ccard=ccard)
#table payment di update lagi
result = build_register(vendor_produk, ar_invoice)
dat.update(result["f_result"])
if "form" in result:
dat.update(dict(form=result["form"]))
# request.environ["application"]="text/html"
# request.response()
# return request.response
r_data.append(dat)
......@@ -146,6 +190,34 @@ def register(request, data, **kwargs):
return data
class ViewData(BaseView):
@view_config(route_name='api-merchant-payment',
renderer='templates/form-clean.pt')
def view_form(self):
# request = self.req
# flash = request.session.flash
# print(">>>>>", request.environ)
# print(">>>>", request.POST, request)
# if request.POST:
# data = dict(request.POST.items())
# if "tXid" in "data":
# row = PartnerPay.query_id(data["tXid"]).first()
# if not row:
# flash('Pembayaran tidak ditemukan', "error")
# return dict()
# vendor = row.vendor
# produk_vendor = PartnerProduk.query()\
# .filter_by(partner_id=row.vendor_id,
# produk_id = row.produk_id,)\
# .first()
#
# else:
# flash('Method POST Required', "error")
# return dict()
settings = get_settings()
url = settings["np_url"]+'/payment'
return HTTPFound(url)
# @jsonrpc_method(method='advice', endpoint='api-merchant')
# def advice(request, data):
# """
......@@ -397,3 +469,4 @@ def register(request, data, **kwargs):
# data[i]=r_data
# i += 1
# return data
import json
import socket
from datetime import datetime, timedelta
import colander
from deform import widget, Form, ValidationFailure
from deform import widget, Form, ValidationFailure, Button
from opensipkd.base import get_host
from opensipkd.base.models import Partner, flush_row
from opensipkd.base.views import BaseView
from opensipkd.pasar.models import Produk, PartnerLog, PartnerProduk, H2hArInvoice, H2hArInvoiceDet
from opensipkd.pasar.models.views import (deferred_produk, deferred_vendor,
deferred_customer)
from paste.httpexceptions import HTTPFound
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from ..tools import get_settings, btn_purchase, ymd, hms, json_rpc_header
from requests import Response
from ..tools import get_settings, btn_purchase, ymd, hms, json_rpc_header, get_random_number
from ..tools import btn_inquiry, btn_reset, btn_payment, btn_advice, btn_next, btn_register, btn_cancel
from .api_merchant import build_request, qry_vendor_produk, save_partner_log
......@@ -231,7 +235,7 @@ class RegisterSchema(colander.Schema):
colander.Integer(), title='Vendor',
oid="vendor_id", widget=deferred_vendor)
amt = colander.SchemaNode(
amount = colander.SchemaNode(
colander.Integer(),
default=10000,
widget=widget.TextInputWidget()
......@@ -322,11 +326,11 @@ class RegisterSchema(colander.Schema):
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
# db_process_url Y AN 255 Payment Notification url (Async notification)
db_proses_url = colander.SchemaNode(
colander.String(),
default='https://merchant.com/notification',
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
# db_proses_url = colander.SchemaNode(
# colander.String(),
# default='https://merchant.com/notification',
# widget=widget.TextInputWidget(attributes={'maxlength': 255})
# )
vat = colander.SchemaNode(
colander.Integer(),
default=0,
......@@ -347,41 +351,43 @@ class RegisterSchema(colander.Schema):
default='Transaction Description',
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
req_domain = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 100})
)
req_server_ip = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 128})
)
req_client_ver = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
user_ip = colander.SchemaNode(
colander.String(),
missing=colander.drop,
default='127.0.0.1',
widget=widget.TextInputWidget(attributes={'maxlength': 128})
)
user_session_id = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
user_agent = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
# req_domain = colander.SchemaNode(
# colander.String(),
# missing=colander.drop,
# widget=widget.TextInputWidget(attributes={'maxlength': 100})
# )
# req_server_ip = colander.SchemaNode(
# colander.String(),
# missing=colander.drop,
# widget=widget.TextInputWidget(attributes={'maxlength': 128})
# )
# req_client_ver = colander.SchemaNode(
# colander.String(),
# missing=colander.drop,
# widget=widget.TextInputWidget(attributes={'maxlength': 50})
# )
# user_ip = colander.SchemaNode(
# colander.String(),
# missing=colander.drop,
# default='127.0.0.1',
# widget=widget.TextInputWidget(attributes={'maxlength': 128})
# )
# user_session_id = colander.SchemaNode(
# colander.String(),
# missing=colander.drop,
# widget=widget.TextInputWidget(attributes={'maxlength': 255})
# )
# user_agent = colander.SchemaNode(
# colander.String(),
# missing=colander.drop,
# widget=widget.TextInputWidget(attributes={'maxlength': 255})
# )
user_language = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 2})
widget=widget.TextInputWidget(attributes={'maxlength': 2}),
default='us-EN',
)
cart_data = colander.SchemaNode(
colander.String(),
......@@ -406,44 +412,14 @@ class RegisterSchema(colander.Schema):
widget=widget.TextAreaWidget(attributes={'maxlength': 4000})
)
# CC
instmnt_type = colander.SchemaNode(
colander.String(),
default='2',
widget=widget.TextInputWidget(attributes={'maxlength': 2})
)
instmnt_mon = colander.SchemaNode(
colander.String(),
default='1',
widget=widget.TextInputWidget(attributes={'maxlength': 2})
)
recurr_opt = colander.SchemaNode(
colander.Integer(),
default=2,
widget=widget.SelectWidget(values=recurring_opts)
)
# VA
bank_cd = colander.SchemaNode(
colander.String(),
default='CENA',
widget=widget.TextInputWidget(attributes={'maxlength': 4})
)
vacct_valid_dt = colander.SchemaNode(
colander.String(),
default=(datetime.now() + timedelta(days=1)).strftime('%Y%m%d'),
widget=widget.TextInputWidget(attributes={'maxlength': 8})
)
# date(YYYYMMDD)
vacct_valid_tm = colander.SchemaNode(
colander.String(),
default=datetime.now().strftime('%H%M%S'),
widget=widget.TextInputWidget(attributes={'maxlength': 6})
)
# time(HH24MISS)
mer_fix_acct_id = colander.SchemaNode(
colander.String(),
default='001122',
widget=widget.TextInputWidget(attributes={'maxlength': 40})
)
# bank_cd = colander.SchemaNode(
# colander.String(),
# default='CENA',
# widget=widget.TextInputWidget(attributes={'maxlength': 4})
# )
# # (E - Wallet, CVS, Payloan)
# mitra_cd = colander.SchemaNode(
# colander.String(),
......@@ -485,16 +461,16 @@ callBackUrl=http://merchant.com/callbackUrl
class CCardPayment(colander.Schema):
time_stamp = colander.SchemaNode(
colander.String(),
default="20180123100505",
widget=widget.TextInputWidget(attributes={'maxlength': 14})
)
tx_id = colander.SchemaNode(
colander.String(),
default="IONPAYTEST01201804191202084760",
widget=widget.TextInputWidget(attributes={'maxlength': 30})
)
# time_stamp = colander.SchemaNode(
# colander.String(),
# default="20180123100505",
# widget=widget.TextInputWidget(attributes={'maxlength': 14})
# )
# tx_id = colander.SchemaNode(
# colander.String(),
# default="IONPAYTEST01201804191202084760",
# widget=widget.TextInputWidget(attributes={'maxlength': 30})
# )
card_no = colander.SchemaNode(
colander.String(),
default="4222222222222222",
......@@ -510,89 +486,143 @@ class CCardPayment(colander.Schema):
default="123",
widget=widget.TextInputWidget(attributes={'maxlength': 4})
)
card_holder_nm = colander.SchemaNode(
card_name = colander.SchemaNode(
colander.String(),
default="Thomas Alfa Edison",
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
merchant_token = colander.SchemaNode(
instmnt_type = colander.SchemaNode(
colander.String(),
default="f9d30f6c972e2b5718751bd087b178534673a91bbac845f8a24e60e8e4abbbc5",
widget=widget.TextInputWidget(attributes={'maxlength': 255})
default='2',
widget=widget.TextInputWidget(attributes={'maxlength': 2})
)
call_back_url = colander.SchemaNode(
instmnt_mon = colander.SchemaNode(
colander.String(),
default="http://merchant.com/callbackUrl",
widget=widget.TextInputWidget(attributes={'maxlength': 255})
default='1',
widget=widget.TextInputWidget(attributes={'maxlength': 2})
)
recurr_opt = colander.SchemaNode(
colander.Integer(),
default=2,
widget=widget.SelectWidget(values=recurring_opts)
)
class VAPayment(colander.Schema):
code= colander.SchemaNode(
callback_url = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 4})
#default = "{}/api/merchant/agratek/callback".format(get_host()),
default="http://merchant.com/callback",
widget=widget.TextInputWidget(max_len=255)
)
message= colander.SchemaNode(
class VAPayment(colander.Schema):
valid_date = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 255})
default=(datetime.now() + timedelta(days=1)).strftime('%Y%m%d'),
widget=widget.TextInputWidget(attributes={'maxlength': 8})
)
tx_id= colander.SchemaNode(
valid_time= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 30})
default=datetime.now().strftime('%H%M%S'),
widget=widget.TextInputWidget(attributes={'maxlength': 6})
)
invoice_no= colander.SchemaNode(
fix_acct_id = colander.SchemaNode(
colander.String(),
default='001122',
widget=widget.TextInputWidget(attributes={'maxlength': 40})
)
pay_method= colander.SchemaNode(
class VAResult(colander.Schema):
vacct_no = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 2})
widget=widget.TextInputWidget(readonly=True)
)
amount= colander.SchemaNode(
colander.Integer(),
widget=widget.TextInputWidget()
)
trans_dt= colander.SchemaNode(
valid_date = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 8})
widget=widget.TextInputWidget(readonly=True)
)
trans_tm= colander.SchemaNode(
valid_time = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 6})
widget=widget.TextInputWidget(readonly=True)
)
description= colander.SchemaNode(
class CPPayment(colander.Schema):
"""
clickPayNo Y N 16 ClickPay number
dataField3 Y N 16 Token input 3 for clickpay
clickPayToken Y N 6 Code response from token
merchantToken Y AN 255 merchantToken
callBackUrl Y AN 255 Payment result forward url (on browser)
"""
click_pay_no = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 100})
missing=colander.drop,
widget=widget.TextInputWidget(max_len=16)
)
bank_cd= colander.SchemaNode(
item3 = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 4})
missing=colander.drop,
widget=widget.TextInputWidget(max_len=3)
)
vacct_no= colander.SchemaNode(
click_pay_token = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 20})
missing=colander.drop,
widget=widget.TextInputWidget(max_len=6)
)
currency= colander.SchemaNode(
callback_url = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 3})
#default = "{}/api/merchant/agratek/callback".format(get_host()),
default="http://merchant.com/callback",
widget=widget.TextInputWidget(max_len=255)
)
goods_nm= colander.SchemaNode(
class WLPayment(colander.Schema):
m_ref_no = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 100})
missing=colander.drop,
widget=widget.TextInputWidget()
)
cust_nm= colander.SchemaNode(
callback_url = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 30})
#default = "{}/api/merchant/agratek/callback".format(get_host()),
default="http://merchant.com/callback",
widget=widget.TextInputWidget(max_len=255)
)
valid_date= colander.SchemaNode(
class CVSPayment(colander.Schema):
valid_date = colander.SchemaNode(
colander.String(),
default=(datetime.now() + timedelta(days=1)).strftime('%Y%m%d'),
widget=widget.TextInputWidget(attributes={'maxlength': 8})
)
valid_time= colander.SchemaNode(
colander.String(),
default=datetime.now().strftime('%H%M%S'),
widget=widget.TextInputWidget(attributes={'maxlength': 6})
)
class CVSResult(colander.Schema):
pay_no = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(readonly=True)
)
valid_date = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(readonly=True)
)
valid_time = colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(readonly=True)
)
class PLPayment(colander.Schema):
callback_url = colander.SchemaNode(
colander.String(),
#default = "{}/api/merchant/agratek/callback".format(get_host()),
default="http://merchant.com/callback",
widget=widget.TextInputWidget(max_len=255)
)
def form_validator(form, value):
pass
......@@ -606,182 +636,200 @@ def get_form(request, class_form, buttons=None, row=None):
schema.request = request
if row:
schema.deserialize(row)
return Form(schema, buttons=buttons or ())
return Form(schema, buttons=(buttons) or ())
def route_register(request):
return HTTPFound(location=request.route_url('api-merchant-register'))
def route_payment(request):
return HTTPFound(location=request.route_url('api-merchant-payment'))
def query_id(id):
# id = request.matchdict['id']
return H2hArInvoiceDet.query_id(id)
btn_proses = Button('proses', title='Proses', css_class="btn-warning")
def set_data(request, denom, dat):
env = request.environ
return dict(
time_stamp=datetime.now().strftime('%Y%m%d%H%M%S'),
denom=denom,
currency="IDR",
amount=dat['amount'],
invoice_no=dat['invoice_no'],
description=dat['description'],
req_dt=(datetime.now() + timedelta(days=1)).strftime('%Y%m%d'),
req_tm=datetime.now().strftime('%H%M%S'),
fee=dat['fee'],
vat=dat['vat'],
notax_amt=dat['notax_amt'],
server=dict(
domain=request._host,
ip=socket.gethostbyname(socket.gethostname()),
),
customer=dict(
name=dat['billing_nm'],
phone=dat['billing_phone'],
email=dat['billing_email'],
address=dat['billing_addr'],
city=dat['billing_city'],
state=dat['billing_state'],
post_code=dat['billing_post_cd'],
country=dat['billing_country'],
agent=env['HTTP_USER_AGENT'],
ip=env['REMOTE_ADDR'],
session_id=request.session.id,
),
deliver_to=dict(
name=dat['billing_nm'],
phone=dat['billing_phone'],
email=dat['billing_email'],
address=dat['billing_addr'],
city=dat['billing_city'],
state=dat['billing_state'],
post_code=dat['billing_post_cd'],
country=dat['billing_country'],
),
produk=json.loads(dat['cart_data']),
)
def payment(request, data, form=None):
row = Produk.query_id(data['produk_id']).first()
denom = row and row.kode or ''
if denom == 'CC':
form = get_form(request, CCardPayment, (btn_cancel, btn_proses))
elif denom[:2] == 'VA':
form = get_form(request, VAPayment, (btn_cancel, btn_proses))
elif denom[:2] == 'CP':
form = get_form(request, CPPayment, (btn_cancel,))
elif denom[:2] == 'WL':
form = get_form(request, WLPayment, (btn_cancel,))
elif denom[:3] == 'CVS':
form = get_form(request, CVSPayment, (btn_cancel, btn_proses))
elif denom[:2] == 'PL':
form = get_form(request, PLPayment, (btn_cancel, btn_proses))
return form
def proses(request):
values = dict(request.POST.items())
session = request.session
dat = session['payment']
row = Produk.query_id(dat['produk_id']).first()
denom = row and row.kode or ''
data = set_data(request, denom, dat)
customer = Partner.query_id(dat['customer_id']).first()
user = customer.users
header = json_rpc_header(user.user_name, user.api_key)
request.environ['HTTP_USERID'] = user.user_name
request.environ['HTTP_SIGNATURE'] = header['signature']
request.environ['HTTP_KEY'] = header['key']
if denom[:2] == "CC":
data.update(dict(credit_card=dict(
instmnt_type=values["instmnt_type"],
instmnt_mon=values["instmnt_mon"],
recurr_opt=values["recurr_opt"],
card_no=values["card_no"],
card_exp=values["card_exp"],
card_cvv=values["card_cvv"],
card_name=values["card_name"],
)))
result = register(request, data=data)
if result['code'] != 0:
form = get_form(request, RegisterSchema, (btn_cancel, btn_payment))
form.render(dat)
session.flash(result['message'], "error")
return dict(form=form, params=dict(scripts=""))
session.flash("Proses data berhasil")
if "form" in result:
response = request.response
response.text = result["form"]
response.content_type = 'text/html'
return response
# Virtual Account
elif denom[:2] == "VA":
data.update(dict(va=dict(
valid_date=values['valid_date'],
valid_time=values['valid_time'],
fix_acct_id=values['fix_acct_id'],
)))
result = register(request, data=data)
if result['code'] != 0:
form = get_form(request, RegisterSchema, (btn_cancel, btn_payment))
form.render(dat)
request.session.flash(result['message'], "error")
return dict(form=form, params=dict(scripts=""))
form = get_form(request, VAResult, (btn_cancel))
session.flash("Proses data berhasil")
values = result["va"]
form.render(values)
return dict(form=form, params=dict(scripts=""))
# def save_ar_invoice(values, vendor_produk):
# invoice = H2hArInvoice.query() \
# .filter_by(cust_inv_no=values['cust_inv_no']).first()
# if not invoice:
# invoice = H2hArInvoice()
# invoice.from_dict(values)
# flush_row(invoice)
# invoice_det = H2hArInvoiceDet.query() \
# .filter_by(ar_invoice_id=invoice.id, produk_id=values['produk_id'],
# id_pel=values["id_pel"]).first()
# if not invoice_det:
# invoice_det = H2hArInvoiceDet()
# invoice_det.ar_invoice_id = invoice.id
# invoice_det.vendor_id = values["vendor_id"]
# invoice_det.produk_id = values["produk_id"]
# invoice_det.id_pel = values["id_pel"]
# invoice_det.amt_sell = vendor_produk.produk.harga
# flush_row(invoice_det)
# return invoice_det
# CVS
elif denom[:3] == "CVS":
data.update(dict(va=dict(
valid_date=values['valid_date'],
valid_time=values['valid_time'],
)))
result = register(request, data=data)
if result['code'] != 0:
form = get_form(request, RegisterSchema, (btn_cancel, btn_payment))
form.render(dat)
request.session.flash(result['message'], "error")
return dict(form=form, params=dict(scripts=""))
form = get_form(request, CVSResult, (btn_cancel, ))
session.flash("Proses data berhasil")
values = result["cvs"]
form.render(values)
return dict(form=form, params=dict(scripts=""))
class ViewHome(BaseView):
@view_config(route_name='api-merchant-register',
permission="api-merchant-register",
renderer='templates/payment/form-register.pt')
renderer='templates/form.pt')
def form_merchant_register(self):
request = self.req
session = self.ses
form = get_form(request, RegisterSchema, (btn_cancel, btn_register))
form = get_form(request, RegisterSchema, (btn_cancel, btn_payment))
if request.POST:
controls = request.POST.items()
if 'register' in request.POST:
if 'payment' in request.POST:
try:
c = form.validate(controls)
except ValidationFailure as e:
form.set_appstruct(e.cstruct)
return dict(form=form)
# call api
# isi form payment dari api result
# return route_payment(request)
env = request.environ
dat = dict(request.POST.items())
row = Produk.query_id(dat['produk_id']).first()
denom = row and row.kode or ''
data = dict(
invoice_no=dat['invoice_no'],
produk=json.loads(dat['cart_data']),
amount=dat['amt'],
denom=denom,
id_pel=dat['customer_id'],
# cust_inv_no=inv_no,
# amt_sell=dat['amt'],
goods_nm=dat['goods_nm'],
cust_nm=dat['billing_nm'],
cust_phone=dat['billing_phone'],
cust_email=dat['billing_email'],
cust_city=dat['billing_city'],
cust_state=dat['billing_state'],
cust_pos=dat['billing_post_cd'],
cust_country=dat['billing_country'],
cust_addr=dat['billing_addr'],
domain=dat['req_domain'],
server_ip=dat['req_server_ip'],
cust_agent=env['HTTP_USER_AGENT'],
cust_ip=env['REMOTE_ADDR'],
cust_session_id=request.session.id,
description=dat['description'],
# valid_date=dat['pay_valid_dt'],
# valid_time=dat['pay_valid_time'],
time_stamp=datetime.now().strftime('%Y%m%d%H%M%S'),
# inv_cust_va=dat['cust_va'],
delivery_addr=dat['delivery_addr'],
delivery_city=dat['delivery_city'],
delivery_country=dat['delivery_country'],
delivery_nm=dat['delivery_nm'],
delivery_phone=dat['delivery_phone'],
delivery_pos=dat['delivery_post_cd'],
delivery_state=dat['delivery_state'],
fee=dat['fee'],
req_dt=(datetime.now() + timedelta(days=1)).strftime('%Y%m%d'),
req_tm=datetime.now().strftime('%H%M%S'),
vat=dat['vat'],
notax_amt=dat['notax_amt'],
#
# pay_valid_dt=dat['pay_valid_dt'],
# pay_valid_tm=dat['pay_valid_tm'],
# recurr_opt=dat['recurr_opt'],
# tx_id=dat['tx_id'],
# trans_dt=dat['trans_dt'],
# trans_tm=dat['trans_tm'],
)
customer = Partner.query_id(dat['customer_id']).first()
user = customer.users
header = json_rpc_header(user.user_name, user.api_key)
request.environ['HTTP_USERID'] = user.user_name
request.environ['HTTP_SIGNATURE'] = header['signature']
request.environ['HTTP_KEY'] = header['key']
if denom[:2] == 'VA':
data.update(dict(
# va
valid_date=dat['vacct_valid_dt'],
valid_time=dat['vacct_valid_tm'],
bank_cd=dat['bank_cd'],
cust_va=dat['mer_fix_acct_id'],
))
form = get_form(request, VAPayment, (btn_cancel,))
elif denom == 'CRC':
data.update(dict(
# cc
instmnt_mon=dat['instmnt_mon'],
instmnt_type=dat['instmnt_type'],
recurr_opt=dat['recurr_opt'],
# m_ref_no=dat['m_ref_no'],
))
form = get_form(request, CCardPayment, (btn_cancel, btn_payment))
print('>>>> MERCHANT PAYMENT:', data)
result = register(request, data=data)
if result['code'] != 0:
form = get_form(request, RegisterSchema, (btn_cancel, btn_register))
form.render(dat)
request.session.flash(result['message'])
return dict(form=form, params=dict(scripts=""))
form.render(result)
return dict(form=form, params=dict(scripts=""))
else:
return route_register(request)
data = dict(request.POST.items())
vendor = Partner.query_id(data["vendor_id"]).first()
if vendor:
data.update({"vendor_kd": vendor.kode})
return dict(form=form, params=dict(scripts=""))
session['payment'] = data
form = payment(request, data, form)
@view_config(route_name='api-merchant-payment',
permission="api-merchant-payment",
renderer='templates/payment/form-payment.pt')
def form_merchant_payment(self):
request = self.req
session = self.ses
elif 'proses' in request.POST:
if 'payment' not in session:
form = get_form(request, RegisterSchema, (btn_cancel, btn_payment))
session.flash("Payment Tidak Ditemukan")
return dict(form=form, params=dict(scripts="") )
form = get_form(request, CCardPayment, (btn_cancel, btn_payment))
if request.POST:
controls = request.POST.items()
if 'payment' in request.POST:
try:
c = form.validate(controls)
except ValidationFailure as e:
form.set_appstruct(e.cstruct)
return dict(form=form)
return route_register(request)
result = proses(request)
if result:
return result
form.render(result)
return dict(form=form, params=dict(scripts=""))
else:
return route_register(request)
values = dict(invoice_no=get_random_number(16))
form.render(values)
return dict(form=form, params=dict(scripts=""))
......
......@@ -8,6 +8,7 @@ import xmltodict
from agratek.api.merchant.views.vendor import sha256
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import PartnerProduk, H2hArInvoiceDet
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from ..tools import get_settings, get_jsonrpc
......@@ -31,10 +32,13 @@ def update_harga(p, k, v):
return True
def callback_merchant(order):
def purchase_notify(order):
# Callback to merchant
invoice = order.invoice
customer = invoice.customer
if hasattr(order, "customer_id"):
customer = order.customer
else:
invoice = order.invoice
customer = invoice.customer
if customer and customer.website:
url = customer.website
......@@ -69,6 +73,27 @@ def callback_merchant(order):
except:
pass
def payment_notify(order):
customer = order.customer
if customer and customer.website:
url = customer.website
users = customer.users
typ = "PAYMENT"
key = order.cust_inv_no + users.user_name + users.api_key + typ
signature = sha256(key)
data = dict(
invoice_no=order.cust_inv_no,
signature=signature,
type=typ
)
data.update(order.notify["result"])
js = get_jsonrpc(method="notify", params=dict(data=data))
log.info("Notify: %s %s" % (url, js))
try:
requests.post(url, data=js, timeout=20)
except:
pass
def proses_np(data):
# todo:
......@@ -78,22 +103,29 @@ def proses_np(data):
@view_config(route_name='api-vendor-notify', renderer='json')
def api_vendor_notify(request):
vendor_nm = request.matchdict['name']
if vendor_nm == "odeo":
data = json.loads(request.text)
elif vendor_nm == "np":
data = json.loads(request.text)
data = json.loads(request.text)
modul = '.notify'
pckgs = 'agratek.api.merchant.views.{}'.format(vendor_nm)
moduls = import_module(modul, pckgs)
typ = 'proses'
# moduls(data)
cls = hasattr(moduls, typ) and getattr(moduls, typ) or None
if cls:
order = cls(data)
@view_config(route_name='api-vendor-callback')
def api_vendor_callback(request):
vendor_nm = request.matchdict['name']
modul = '.callback'
pckgs = 'agratek.api.merchant.views.{}'.format(vendor_nm)
moduls = import_module(modul, pckgs)
typ = 'callback'
cls = hasattr(moduls, typ) and getattr(moduls, typ) or None
if cls:
cb = cls(request)
return HTTPFound(cb)
@view_config(route_name='api-vendor-test', renderer="string")
def vendor_test(request):
params = request.params
......
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 pyramid.httpexceptions import HTTPFound
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
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
......@@ -55,33 +22,25 @@ class Vendor(VendorClass): #VendorClass
'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
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.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()
# setMandatoryParameter
def request_payment(self, response):
Nicepay.requestData={}
Nicepay.set('timeStamp', self.invoice_det.time_stamp)
......@@ -182,48 +141,33 @@ class Vendor(VendorClass): #VendorClass
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)
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':
# if self.reccuring:
# # For Credit Card Reccuring Only
# Nicepay.set('recurrOpt', '2')
# cc
print('>>>> NP INIT:', self.invoice_det.to_dict())
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('payValidDt', self.invoice_det.pay_valid_dt or '')
# Nicepay.set('payValidTm', self.invoice_det.pay_valid_tm or '')
# Nicepay.set('mRefNo', self.invoice_det.m_ref_no 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.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)
Nicepay.set('vacctValidDt', '')
Nicepay.set('vacctValidTm', '')
else:
self.va_typ = 'float'
Nicepay.set('merFixAcctId', '')
elif self.pay_method in ['03', '05']:
# For CVS,ClickPay or E-Wallet
# (Don't forgot change payMethod to '03'/'04'/'05')
# 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)
......@@ -244,20 +188,21 @@ class Vendor(VendorClass): #VendorClass
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("REQUEST: {}".format(json.dumps(self.request)))
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("RESPONSE: {}".format(json.dumps(self.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()
......@@ -267,20 +212,14 @@ class Vendor(VendorClass): #VendorClass
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["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']
# Jika kartu kredit
# if self.pay_method == '01':
# # C-Card
# # payment = self.request_payment(response)
# elif response['payMethod'] == "02":
result['pay_method'] = self.pay_method
if result['pay_method'] == "01":
# result['pay_method'] = self.pay_method
if self.pay_method == "01":
result["code"] = 0
result["message"] = 'SUCCESS'
request_data = Nicepay.requestData
......@@ -288,60 +227,90 @@ class Vendor(VendorClass): #VendorClass
call_back_url = settings['switcher_call_back_url']
result.update(dict(
time_stamp=request_data['timeStamp'],
tx_id=result['tx_id'],
tx_id=self.invoice_det.tx_id,
merchant_token=request_data['merchantToken'],
call_back_url=call_back_url,
))
# form = """
# <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_yymm}">
# <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}">
# """.format(
# time_stamp=request_data['timeStamp'],
# tx_id=result['tx_id'],
# merchant_token=request_data['merchantToken'],
# card_no='',
# card_exp_yymm='',
# card_cvv='',
# card_holder_nm='',
# call_back_url=call_back_url,
# )
# result['form'] = form
elif response['payMethod'] == "02":
# VA
result["vacct_no"]=response['vacctNo']
result["bank_cd"]=response['bankCd']
# result["vacct_valid_dt"]=response['vacctValidDt']
# result["vacct_valid_tm"]=response['vacctValidTm']
# result["mer_fix_acct_id"]=response['merFixAcctId']
elif response['payMethod'] == "03":
# 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["pay_no"]=response['payNo']
# result["pay_valid_dt"]=response['payValidDt']
# result["pay_valid_tm"]=response['payValidTm']
elif response['payMethod'] == "04":
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 response['payMethod'] == "05":
elif self.pay_method == "05":
# e-wallet
result["receipt_code"]='receiptCode' in response and response['receiptCode'] or ''
elif response['payMethod'] == "06":
elif self.pay_method == "06":
# akulaku
pass
# else:
# result["resultCd"]=response['resultCd']
# result["resultMsg"]=response['resultMsg']
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
"""
......
from _sha256 import sha256
import logging
from agratek.api.merchant.views.notify_vendor import purchase_notify, update_harga
from opensipkd.base import get_settings
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import H2hArInvoiceDet
from opensipkd.pasar.models.produk import PartnerPay
log = logging.getLogger(__name__)
def callback(request):
data = dict(request.POST.items())
tx_id = data["tXid"]
if tx_id:
row = PartnerPay.query_txid(tx_id).first()
return row.callback_url
from _sha256 import sha256
import logging
from agratek.api.merchant.views.notify_vendor import callback_merchant, update_harga
from agratek.api.merchant.views.notify_vendor import purchase_notify, update_harga, payment_notify
from opensipkd.base import get_settings
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import H2hArInvoiceDet
from opensipkd.pasar.models.produk import PartnerPay
log = logging.getLogger(__name__)
def proses(data):
# todo:
"""
change settig from odeo to np
"""
settings = get_settings()
mid = 'odeo_mid' in settings and settings["odeo_mid"] or None
key = 'odeo_key' in settings and settings["odeo_key"] or None
partner = Partner.query_kode("ODEO").first()
mid = 'np_mid' in settings and settings["np_mid"] or None
key = 'np_key' in settings and settings["np_key"] or None
partner = Partner.query_kode("NP").first()
status = str(data["status"])
if status == "BROADCAST_NEW_PRICE":
signature = sha256("{mid}{key}{status}".format(
mid=mid, key=key, status=status))
amount = data["amt"]
tx_id = data["tXid"]
merchant_token = data["merchantToken"]
ref_no = data["referenceNo"]
signature = sha256("{mid}{tx_id}{amount}{key}"\
.format(mid=mid, key=key, amount=str(amount),
tx_id=tx_id))
if merchant_token!=signature:
return
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature different")
pay = PartnerPay.query_txid(tx_id).filter(cust_inv_no=ref_no).first()
if not pay:
return
new_price = data["new_prices"]
for k in new_price:
v = new_price[k]
update_harga(partner, k, v)
return dict(success=True)
result=dict()
pay.notify= dict(response=data,
result=result)
pay.status = 1
flush_row(pay)
payment_notify(pay)
else:
order_id = str(data["order_id"])
signature = sha256("{order_id}{mid}{key}{status}".format(
order_id=order_id, mid=mid, key=key, status=status))
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature Different")
order = H2hArInvoiceDet.query() \
.filter(H2hArInvoiceDet.vendor_id == partner.id,
H2hArInvoiceDet.vend_inv_no == str(order_id)).first()
return pay
if order:
if status == "COMPLETED":
order.status = 1
else:
order.status = -3
order.notify = dict(post=data)
if "sn" in data and data["sn"]:
order.serial_number = data["sn"]
else:
message = 'message' in data and data["message"] or ""
if message:
loc = message.find("SN: ")
if loc>-1:
sn = message[loc+4:loc+28]
order.serial_number=sn
"""
Common Parameter for Notification
flush_row(order)
# todo: add to customer notify table
# todo: create cron for notify
# proses jika status 1 notify ada isinya tapi belum ada field result
# todo: create cron torecurring order to other vendor
# jika status = -2 proses vendor yang lain
callback_merchant(order)
return order
Parameter Type Size Description
tXid N 30 Transaction ID
merchantToken AN 255 Merchant Token
referenceNo N 40 Merchant Order No
payMethod N 2 Payment method. Refer Code at Here
amt N 12 Payment amount
transDt N 8 Transaction date
transTm N 6 Transaction time
currency N 3 Currency
goodsNm N 100 Goods name
billingNm N 30 Billing name
matchCl N 1 Payment amount match flag. Refer Code at Here
status AN 1 Deposit Status
0: Deposit
1: Reversal
Additional Parameter for Credit Card Notification
Parameter Type Size Description
authNo N 10 Approval number
IssueBankCd A 4 Issue bank code. Refer Code at Here
IssueBankNm A Issue bank name.
acquBankCd A Acquire bank code. Refer Code at Here
acquBankNm A Acquire bank name.
cardNo AN 20 Card no with masking
cardExpYymm N Card expiry (YYMM)
instmntMon N 2 Installment month
instmntType N 2 Installment Type. Refer Code at Here
preauthToken AN 255 Preauth Token
recurringToken AN 255 Recurring token
ccTransType AN 2 Credit card transaction type
1: Normal
2: Recurring
3: Pre-auth
4: Captured
vat N 12 Vat number
fee N 12 service fee
notaxAmt N 12 tax free amount
Additional Parameter for Virtual Account Notification
Parameter Type Size Description
bankCd N 4 Bank Code. Refer Code at Here
vacctNo N 16 Bank Virtual Account number
vacctValidDt N 8 VA expiry date
vacctValidTm N 6 VA expiry time
depositDt N Deposit date
depositTm N Deposit time
Additional Parameter for Others Payment Method Notification
Parameter Type Size Description
mitraCd A 4 Mitra Code. Refer Code at Here
payNo N 12 Pay number to mitra
payValidDt N 8 CVS expiry date
payValidTm N 6 CVS expiry time
receiptCode ANS 20 Authorization number
mRefNo AN 18 Bank reference No
depositDt N Deposit date
depositTm N Deposit time
"""
from _sha256 import sha256
import logging
from agratek.api.merchant.views.notify_vendor import callback_merchant, update_harga
from agratek.api.merchant.views.notify_vendor import purchase_notify, update_harga
from opensipkd.base import get_settings
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import H2hArInvoiceDet
......@@ -64,5 +64,5 @@ def proses(data):
# proses jika status 1 notify ada isinya tapi belum ada field result
# todo: create cron torecurring order to other vendor
# jika status = -2 proses vendor yang lain
callback_merchant(order)
purchase_notify(order)
return order
"""
Module proses:
Save
Invoice To Vendor
Invoice To Customer
"""
import hashlib
import json
import logging
import re
from datetime import datetime
from importlib import import_module
import colander
import requests
import xmltodict
from deform import widget, Form, ValidationFailure
# from opensipkd.pasar.models import PartnerLog
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from . import BaseView # , save_file_upload
from ..models import (DBSession, flush_row, Partner, PartnerProduk)
from ..models import (Produk, ProdukKategori)
from ..tools import (btn_next, date_from_str, get_settings, btn_reset,
btn_inquiry, btn_advice, btn_payment)
log = logging.getLogger(__name__)
from ..views import deferred_vendor, deferred_customer, deferred_produk
def build_request(typ, values):
produk_id = values['produk_id']
vendor_id = values['vendor_id']
# bill_no = values['destination']
# customer_id = 'customer_id' in values and values['customer_id'] or None
# cust_trx_id = 'cust_trx_id' in values and values['cust_trx_id'] or None
vendor_product = PartnerProduk.query() \
.join(Produk, PartnerProduk.produk_id == Produk.id) \
.filter(PartnerProduk.partner_id == vendor_id,
PartnerProduk.produk_id == produk_id).first()
if not vendor_product:
return dict(data=dict(error='Data Tidak Ditemukan'))
modules = import_module('.' + vendor_product.modules, 'agratek.api.merchant.views')
cls_module = modules.Vendor(vendor_product, values=values)
cls = hasattr(cls_module, typ) and getattr(cls_module, typ) or None
if cls:
data = cls()
result = dict(data=data)
result["f_request"] = cls_module.request
result["f_response"] = cls_module.response
result["url"] = cls_module.url
else:
result = dict(data=dict(error='Fungsi %s tidak ada' % typ,
code=9999))
return result
class AddSchema(colander.Schema):
customer_id = colander.SchemaNode(
colander.Integer(), title='Payment Type',
oid="customer_id", widget=deferred_customer)
cust_inv_no = colander.SchemaNode(
colander.String(), title='No Invoice',
missing=colander.drop,
oid="destination")
produk_id = colander.SchemaNode(
colander.Integer(), title='Payment Type',
oid="produk_id", widget=deferred_produk)
amount = colander.SchemaNode(
colander.Integer(), title='Jumlah',
oid="amount")
vendor_id = colander.SchemaNode(
colander.Integer(), title='Vendor',
missing = colander.drop,
oid="vendor_id", widget=deferred_vendor)
card_no = colander.SchemaNode(
colander.String(), title='No. Kartu',
missing=colander.drop,
oid="card_no")
card_exp = colander.SchemaNode(
colander.String(), title='Expire (YYMM)',
missing=colander.drop,
widget = widget.TextInputWidget(min_len=4, max_len=4),
oid="card_exp")
card_cvv = colander.SchemaNode(
colander.String(), title='Valid',
missing=colander.drop,
widget=widget.TextInputWidget(min_len=3, max_len=3),
oid="card_cvv")
f_result = colander.SchemaNode(
colander.String(), title='Result to Merchant',
missing=colander.drop,
oid="f_result",
widget=widget.TextAreaWidget(rows=10, css_class="readonly")
)
f_request = colander.SchemaNode(
colander.String(), title='Request',
missing=colander.drop,
oid="f_request",
widget=widget.TextAreaWidget(rows=10, css_class="readonly")
)
f_response = colander.SchemaNode(
colander.String(), title='Response',
missing=colander.drop,
oid="f_response",
widget=widget.TextAreaWidget(rows=10, css_class="readonly")
)
class EditSchema(AddSchema):
id = colander.SchemaNode(
colander.Integer(), title='ID',
missing=colander.drop,
oid="id", widget=widget.HiddenWidget())
def form_validator(form, value):
pass
def get_form(request, class_form, buttons=None, row=None):
schema = class_form(validator=form_validator)
schema = schema.bind(vendor=Produk.get_vendor_payment_list(),
produk=Produk.get_payment_list(),
customer=Partner.get_customer_list())
schema.request = request
if row:
schema.deserialize(row)
if not buttons:
buttons = (btn_inquiry, btn_reset)
return Form(schema, buttons=buttons)
def route_list(request):
return HTTPFound(location=request.route_url('simkel-permohonan'))
def save(values, row):
if not row:
row = PartnerLog()
row.create_uid = values['uid']
row.created = datetime.now()
else:
row.update_uid = values['uid']
row.updated = datetime.now()
row.from_dict(values)
flush_row(row)
return row
def save_request(request, values, row=None):
values['tgl_lahir'] = date_from_str(values['tgl_lahir'])
values['uid'] = request.user.id
row = save(values, row)
request.session.flash('Data %s Berhasil disimpan' % values['nama'])
return row
form_params_edit = dict(scripts="""
$(document).ready(function(){
$(".tanggal").datepicker({format:"dd-mm-yyyy"});
$(".tanggal").attr("readonly", true);
$(".readonly").attr("readonly", true);
});
""")
form_params_view = dict(scripts="""
$(document).ready(function(){
$("#nip_penerima, #nopel").attr("readonly", true);
$(".readonly").attr("readonly", true);
});
""")
def query_id(request):
id = request.matchdict['id']
return PartnerProduk.query_id(id)
class ViewHome(BaseView):
@view_config(route_name='api-payment-doc',
permission="api-payment",
renderer='templates/payment_doc.pt')
def view_merchant_doc(self):
return dict()
@view_config(route_name='api-payment-add',
permission="api-payment-add",
renderer='templates/form.pt')
def view_home(self):
request = self.req
session = self.ses
form = get_form(request, AddSchema, (btn_inquiry, btn_payment, btn_advice, btn_next))
settings = get_settings()
if request.POST:
controls = request.POST.items()
try:
c = form.validate(controls)
except ValidationFailure as e:
form.set_appstruct(e.cstruct)
return dict(form=form, params=form_params_edit)
values = dict(c.items())
result = None
if 'inquiry' in request.POST:
result = build_request('inquiry', values)
# if product_kd == "crc" or product_kd[:3]=="EWL":
# return HTTPFound('api-cc-form', params=result["params"])
elif 'payment' in request.POST:
result = build_request('payment', values)
elif 'advice' in request.POST:
result = build_request('advice', values)
elif 'info' in request.POST:
result = build_request('info', values)
if result and 'data' in result and result["data"]:
data = result['data']
values['f_request'] = 'f_request' in result \
and json.dumps(result['f_request'], indent=4) or ''
values['f_response'] = 'f_response' in result \
and json.dumps(result['f_response'], indent=4) or ''
values['f_result'] = 'data' in result \
and json.dumps(result['data'], indent=4) or ''
values['ref_no'] = 'ref_no' in data and data["ref_no"] or ""
values['trx_id'] = 'trx_id' in data and data['trx_id'] or ""
values['vend_trx'] = 'vend_trx' in data and data['vend_trx'] or ""
if 'error' in data and data['error']:
session.flash(data['error'], 'error')
else:
session.flash("No Result Data")
form.render(values)
return dict(form=form, params=form_params_view)
values = dict(card_no="5409120028181901",
card_exp="2012",
card_cvv="111",
amount=1000,
produk_id=51,
cust_inv_no="123456789")
form.render(values)
return dict(form=form, params=form_params_edit)
def sha256(hash_string):
return hashlib.sha256(hash_string.encode()).hexdigest()
def proses_nice_pay(request):
pass
......@@ -18,12 +18,15 @@
<span class="menu-item-parent">Biller Invoice</span>
</a>
</li>
<!--
<li>
<a href="${request._host}/api/vendor/list">
<i class="fa fa-lg fa-fw fa-home"></i>
<span class="menu-item-parent">List Vendor Invoice</span>
</a>
</li>
<li>
<a href="${request._host}/api/payment/add">
<i class="fa fa-lg fa-fw fa-home"></i>
......@@ -37,6 +40,22 @@
<span class="menu-item-parent">List Payment</span>
</a>
</li>
-->
<li>
<a href="${request._host}/api/merchant/register">
<i class="fa fa-lg fa-fw fa-home"></i>
<span class="menu-item-parent">Test Payment</span>
</a>
</li>
<li>
<a href="${request._host}/api/integrated/add">
<i class="fa fa-lg fa-fw fa-home"></i>
<span class="menu-item-parent">Integrated Test</span>
</a>
</li>
<li>
<a href="${request._host}/api/integrated/add">
<i class="fa fa-lg fa-fw fa-home"></i>
......
<html metal:use-macro="load: base-no-menu.pt">
</html>
......@@ -22,9 +22,9 @@ class Vendor(VendorClass):
VendorClass.__init__(self, vendor_produk, invoice_det=invoice_det)
# id_pel, customer_id, cust_trx, row
settings = get_settings()
self.mid = 'test_mid' in settings and settings['odeo_mid'] or None
self.key = 'test_key' in settings and settings['odeo_key'] or None
self.url = 'test_url' in settings and settings['odeo_url'] or None
self.mid = 'test_mid' in settings and settings['test_mid'] or None
self.key = 'test_key' in settings and settings['test_key'] or None
self.url = 'test_url' in settings and settings['test_url'] or None
key = ":".join([self.mid, self.key]).encode()
self.auth = base64.b64encode(key).decode()
......@@ -356,3 +356,7 @@ class Vendor(VendorClass):
# self.amt_sell = result["total"]
result['rincian'] = rincian
return result
# def payment(self):
# url = "{}/payment".format(self.url)
# return HTTPFound(url)
import base64
from opensipkd.base.tools import get_random_number
from pyramid.view import view_config
import logging
log = logging.getLogger(__name__)
"""
test-purchase http://server/api/test/prepaid/purchase
"""
def validate_header(request):
env = request.environ
# http_header = env["HTTP_HEADER"]
# log.info(env)
# if 'HTTP_AUTHORIZATION' not in env:
# log.info("HTTP_AUTHORIZATION tidak ditemukan")
# return
#
# auth = env['HTTP_AUTHORIZATION'].split()
# log.info(auth)
# if len(auth) < 2 or auth[0] != "Bearer":
# log.info('Error Auth')
# return
#
# key = ":".join(['agratek', '4444444']).encode()
# key_encoded = base64.b64encode(key).decode()
# log.info(key_encoded)
# if auth[1] != key_encoded:
# return
return True
def anauthorized(request):
request.response.status = 401
result = {
"status": "UNAUTHORIZED",
"data": {
"errors": [
"Unauthorized"
]
},
"message": ""
}
return result
def bad_request(request, message=None):
if not message:
message = "Paramter(s) Expected"
request.response.status = 400
result = {
"status": "BAD_REQUEST",
"data": {
"errors": [
"ERROR_MESSAGE_1",
"ERROR_MESSAGE_2",
"ERROR_MESSAGE_ETC"
]
},
"message": message
}
return result
def produk_not_found(request):
return bad_request(request, "Prduk Not Found")
# @view_config(route_name='test-purchase', renderer='json', request_method="POST")
def view_test_purchase(request):
denom=""
if denom[:2] == "CC":
tx_id = get_random_number(32)
return {
'resultCd': '0000',
'resultMsg': 'SUCCESS',
'tXid': 'AGRATEK{}'.format(tx_id),
'referenceNo': '2669739141972781',
'payMethod': '01',
'amt': ' 10000',
'transDt': '20190906',
'transTm': '110857',
'description': 'Transaction Description',
'bankCd': None,
'vacctNo': None,
'mitraCd': None,
'payNo': None,
'currency': None,
'goodsNm': None,
'billingNm': None,
'vacctValidDt': None,
'vacc tValidTm': None,
'payValidDt': None,
'payValidTm': None,
'requestURL': None
}
return produk_not_found(request)
# @view_config(route_name='test-order', renderer='json', request_method="GET")
# def view_test_pln_pre(request):
# if not validate_header(request):
# return anauthorized(request)
# matchdict = request.matchdict
# id = "id" in matchdict and matchdict["id"] or ""
# return {
# "order_id": 123,
# "name": "Telkomsel 5",
# "msisdn": "08xx",
# "serial_number": "XXX",
# "status": "COMPLETED",
# "price": 5000
# }
......@@ -353,6 +353,32 @@ def view_test_postpaid(request):
},
"message": ""
}
elif denom[:2] == "CC":
tx_id = get_random_number(32)
return {
'resultCd': '0000',
'resultMsg': 'SUCCESS',
'tXid': 'AGRATEK{}'.format(tx_id),
'referenceNo': '2669739141972781',
'payMethod': '01',
'amt': ' 10000',
'transDt': '20190906',
'transTm': '110857',
'description': 'Transaction Description',
'bankCd': None,
'vacctNo': None,
'mitraCd': None,
'payNo': None,
'currency': None,
'goodsNm': None,
'billingNm': None,
'vacctValidDt': None,
'vacc tValidTm': None,
'payValidDt': None,
'payValidTm': None,
'requestURL': None
}
return produk_not_found(request)
# @view_config(route_name='test-order', renderer='json', request_method="GET")
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!