Commit 4bb08032 by solo
2 parents fbf2423c 05afc654
...@@ -2,7 +2,8 @@ kode,path,nama,status,type ...@@ -2,7 +2,8 @@ kode,path,nama,status,type
api-merchant-home,/api/merchant/home,Api Merchant Home,1,0 api-merchant-home,/api/merchant/home,Api Merchant Home,1,0
api-merchant,/api/merchant,Api Merchant,1,1 api-merchant,/api/merchant,Api Merchant,1,1
api-vendor-notify,/api/vendor/{name}/notify,Api Vendor Notify,1,0 api-vendor-notify,/api/vendor/{name}/notify,Api Vendor Notify,1,0
api-merchant/payment,/api/merchant/payment,Api Merchant Payment,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-merchant-list,/api/merchant/list,Test Api Merchant,1,0 api-merchant-list,/api/merchant/list,Test Api Merchant,1,0
api-merchant-add,/api/merchant/add,Add Api Merchant,1,0 api-merchant-add,/api/merchant/add,Add Api Merchant,1,0
......
# from datetime import datetime
#
# import colander
# from agratek.api.merchant.views.api_merchant import get_vendor_produk
# from datatables import ColumnDT
# from deform import widget, Form, ValidationFailure
# from opensipkd.base.views import DataTables
# from pyramid.httpexceptions import HTTPFound
# from pyramid.view import view_config
#
# from . import BaseView # , save_file_upload
# from ..models import (DBSession, flush_row, Satuan)
# # from ..models import (H2hArInvoice, H2hArInvoiceDet)
# from ..models import (Produk, Partner, PartnerLog, PartnerProduk, H2hArInvoice, H2hArInvoiceDet)
# from ..tools import (btn_reset,
# btn_cancel, btn_delete, btn_save, auth_from_rpc, get_settings, os)
# from opensipkd.pasar.models.views import (deferred_produk, deferred_vendor,
# deferred_customer)
#
# class Payment(colander.Schema):
# """
# timeStamp Y N 14 API Request Date
# tXid Y AN 30 Transaction ID
# callBackUrl Y AN 255 Payment result forward url (on browser) direplace oleh systen
# merchantToken Y AN 255 merchantToken (dibuat oleh system)
# """
#
# time_stamp = colander.SchemaNode(
# colander.String(),
# oid="time_stamp",
# )
#
# tx_id = colander.SchemaNode(
# colander.String(), title='Customer',
# oid="tx_id",
# widget=widget.PasswordWidget(min_length=30, max_length=30)
# )
#
# callback_url = colander.SchemaNode(
# colander.String(), title='Callback URL',
# oid="callback_url",
# widget=widget.TextInputWidget()
# )
#
# class CcPay(Payment):
# """
# cardNo Y N 20 Full card number
# cardExpYymm Y N 4 card expiry(YYMM)
# cardCvv Y N 4 card CVV
# cardHolderNm Y (CIMB) AN 50 Card Holder Name
# :return:
# """
# card_name = colander.SchemaNode(
# colander.String(), title='Card Expired',
# oid="card_no",
# widget=widget.TextInputWidget(min_length=30, max_length=30)
# )
# card_no = colander.SchemaNode(
# colander.String(), title='Card Number',
# oid="card_no",
# widget=widget.TextInputWidget(min_length=16, max_length=16)
# )
# card_exp = colander.SchemaNode(
# colander.String(), title='Card Expired',
# oid="card_no",
# widget=widget.TextInputWidget(min_length=4, max_length=4)
# )
# card_cvv = colander.SchemaNode(
# colander.String(), title='Card Expired',
# oid="card_no",
# widget=widget.PasswordWidget(min_length=3, max_length=3)
# )
#
# class ClickPay(Payment):
# """
# clickPayNo Y N 16 ClickPay number
# dataField3 Y N 16 Token input 3 for clickpay
# clickPayToken Y N 6 Code response from token
# :return:
# """
# pay_no = colander.SchemaNode(
# colander.String(), title='Click Pay No',
# oid="pay_no",
# widget=widget.TextInputWidget(min_length=16, max_length=16)
# )
#
# data_field_3 = colander.SchemaNode(
# colander.String(), title='Click Pay No',
# oid="data_field_3",
# widget=widget.TextInputWidget(min_length=16, max_length=16)
# )
# token = colander.SchemaNode(
# colander.String(), title='Click Pay No',
# oid="token",
# widget=widget.TextInputWidget(min_length=6, max_length=6)
# )
#
# class AddSchema(Payment):
# customer_id = colander.SchemaNode(
# colander.Integer(), title='Customer',
# oid="customer_id", widget=deferred_customer)
#
# produk_id = colander.SchemaNode(
# colander.Integer(), title='Produk',
# oid="produk_id", widget=deferred_produk)
#
#
# def WalletPay(Payment):
# pass
#
#
#
# def payment_validator(form, values):
# pass
#
# def get_form(request, class_form, buttons=None, row=None, validator=payment_validator):
# schema = class_form(validator=validator)
# schema = schema.bind(vendor=Partner.get_vendor_list(),
# produk=Produk.get_e_list(),
# customer=Partner.get_customer_list())
# schema.request = request
# if row:
# schema.deserialize(row)
# if not buttons:
# buttons = (btn_save, btn_reset)
# return Form(schema, buttons=buttons)
#
#
# def route_list(request):
# return HTTPFound(location=request.route_url('api-customer-list'))
#
#
# def save(values, row):
# # if not row:
# # row = H2hArInvoice()
# # 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, values_det, row=None):
# # if not row:
# # row = H2hArInvoice()
# # values['uid'] = request.user.id
# # values['status'] = 'status' in values and values['status'] and 1 or 0
# # else:
# # values['update_uid'] = request.user.id
# # values['updated'] = datetime.now()
# # DBSession.query(H2hArInvoiceDet).filter(H2hArInvoiceDet.ar_invoice_id == row.id).delete()
# #
# # row = save(values, row)
# #
# # row_det = H2hArInvoiceDet()
# # row_det.id_pel = values['id_pel']
# # row_det.ar_invoice_id = row.id
# # row_det = save(values_det, row_det)
# # request.session.flash('Data %s Berhasil disimpan' % values['kode'])
# # # return row
# #
# #
# # form_params_edit = dict(scripts="""
# # $(document).ready(function(){
# # });
# # """)
# #
# # form_params_view = dict(scripts="""
# # $(document).ready(function(){
# # });
# # """)
# #
# # def session_failed(request, session_name):
# # r = dict(form=request.session[session_name])
# # del request.session[session_name]
# # return r
# #
# # def id_not_found(request):
# # id = request.matchdict['id']
# # request.session.flash('Data %s Tidak Ditemukan' % id, 'error')
# # return route_list(request)
# #
# #
# # def query_id(request):
# # id = request.matchdict['id']
# # return H2hArInvoice.query_id(id)
# #
# #
#
#
# class ViewData(BaseView):
# @view_config(route_name='api-merchant-payment',
# # permission="api-customer-admin",
# renderer='templates/form.pt')
# def view_payment(self):
# request = self.req
# # form = get_form(request, AddSchema)
# # form_params = dict(scripts=None)
# form = get_form(request, Payment)
# 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())
# registrasi = PartnerPay.query_tx_id(values["tx_id"]).first()
# if not registrasi:
# request.session.flash("Registrasi Payment Tidak Ditemukan", "error")
# return
#
# vendor_produk = PartnerProduk.get_produk(registrasi.vendor_id, registrasi.produk_id).first()
# if not vendor_produk:
# request.session.flash("Produk Tidak Ditemukan", "error")
# return
# url = os.path.join(settings["np_url"], "payment")
# return HTTPFound(location=url, par)
#
# return dict(form=form, params=form_params_edit)
#
...@@ -65,13 +65,14 @@ def register(request, data, **kwargs): ...@@ -65,13 +65,14 @@ def register(request, data, **kwargs):
r_data = [] r_data = []
log.info("%s Payment Request: %s" % (customer.kode, data)) log.info("%s Payment Request: %s" % (customer.kode, data))
for dat in data: for dat in data:
if "invoice_no" not in dat or "produk" not in dat or not dat["produk"] or \ if "invoice_no" not in dat or \
'amount' not in dat or not dat['amount']: 'amount' not in dat or not dat['amount']:
dat["status"] = "FAILED" dat["status"] = "FAILED"
dat["message"] = "Parameter tidak lengkap" dat["message"] = "Parameter tidak lengkap"
dat['code'] = -1
else: else:
inv_no = dat["invoice_no"] inv_no = dat["invoice_no"]
produk = dat["produk"] produk = 'produk' in dat and dat["produk"] or ''
# todo cek apakah invoice sudah ada atau belum # todo cek apakah invoice sudah ada atau belum
ar_invoice = PartnerPay.query().filter_by(cust_inv_no=inv_no).first() ar_invoice = PartnerPay.query().filter_by(cust_inv_no=inv_no).first()
if ar_invoice: if ar_invoice:
...@@ -86,10 +87,10 @@ def register(request, data, **kwargs): ...@@ -86,10 +87,10 @@ def register(request, data, **kwargs):
values = dict( values = dict(
customer_id=customer.id, customer_id=customer.id,
id_pel=dat['id_pel'], id_pel=dat['id_pel'],
cart=produk, cart=produk or '{}',
cust_inv_no=inv_no, cust_inv_no=inv_no,
amt_sell=dat['amount'], amt_sell=dat['amount'],
notes=dat['notes'], notes=dat['goods_nm'],
inv_cust_nm=dat['cust_nm'], inv_cust_nm=dat['cust_nm'],
inv_cust_phone=dat['cust_phone'], inv_cust_phone=dat['cust_phone'],
inv_cust_email=dat['cust_email'], inv_cust_email=dat['cust_email'],
...@@ -104,10 +105,6 @@ def register(request, data, **kwargs): ...@@ -104,10 +105,6 @@ def register(request, data, **kwargs):
inv_cust_ip=dat['cust_ip'], inv_cust_ip=dat['cust_ip'],
inv_cust_session=dat['cust_session_id'], inv_cust_session=dat['cust_session_id'],
description=dat['description'], description=dat['description'],
inv_valid_date=dat['valid_date'],
inv_valid_time=dat['valid_time'],
inv_time_stamp=dat['time_stamp'],
inv_cust_va=dat['cust_va'],
delivery_addr=dat['delivery_addr'], delivery_addr=dat['delivery_addr'],
delivery_city=dat['delivery_city'], delivery_city=dat['delivery_city'],
delivery_country=dat['delivery_country'], delivery_country=dat['delivery_country'],
...@@ -116,25 +113,34 @@ def register(request, data, **kwargs): ...@@ -116,25 +113,34 @@ def register(request, data, **kwargs):
delivery_pos=dat['delivery_pos'], delivery_pos=dat['delivery_pos'],
delivery_state=dat['delivery_state'], delivery_state=dat['delivery_state'],
fee=dat['fee'], fee=dat['fee'],
instmnt_mon=dat['instmnt_mon'], vat=dat['vat'],
instmnt_type=dat['instmnt_type'],
m_ref_no=dat['m_ref_no'],
notax_amt=dat['notax_amt'],
pay_valid_dt=dat['pay_valid_dt'],
pay_valid_tm=dat['pay_valid_tm'],
recurr_opt=dat['recurr_opt'],
req_dt=dat['req_dt'], req_dt=dat['req_dt'],
req_tm=dat['req_tm'], req_tm=dat['req_tm'],
vat=dat['vat'], inv_time_stamp=dat['time_stamp'] or '',
tx_id=dat['tx_id'], # va
trans_dt=dat['trans_dt'], inv_valid_date='valid_date' in dat and dat['valid_date'] or '',
trans_tm=dat['trans_tm'], 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) ar_invoice = save_partner_pay(values, vendor_produk)
result = build_register(vendor_produk, ar_invoice) result = build_register(vendor_produk, ar_invoice)
dat.update(result["f_result"]) dat.update(result["f_result"])
r_data.append(dat) r_data.append(dat)
data = is_list and r_data or r_data[0] data = is_list and r_data or r_data[0]
log.info("%s Payment Response: %s " % (customer.kode, data)) log.info("%s Payment Response: %s " % (customer.kode, data))
return data return data
......
import json
from datetime import datetime, timedelta
import colander
from deform import widget, Form, ValidationFailure
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.view import view_config
from ..tools import get_settings, btn_purchase, ymd, hms, json_rpc_header
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
import logging
from .api_payment import register
log = logging.getLogger(__name__)
"""
timeStamp Y N 14 API Request Date
iMid Y AN 10 Merchant Id
payMethod Y AN 2 Payment Method
currency Y AN 3 currency
amt Y N 12 Payment Amount
referenceNo Y ANS 40 Merchant Order No (Key from merchant)
goodsNm Y AN 100 Goods Name
billingNm Y A 30 Buyer name
billingPhone Y N 40 Buyer Phone Number
billingEmail Y AN 15 Buyer email
billingAddr N AN 100 Buyer address
billingCity Y A 50 Buyer city
billingState Y A 50 Billing state
billingPostCd Y N 10 Billing Post number
billingCountry Y A 10 Billing Country
deliveryNm N A 30 delivery name
deliveryPhone N N 15 delivery phone number
deliveryAddr N AN 100 delivery address
deliveryCity N A 50 delivery city
deliveryState N A 50 delivery state
deliveryPostCd N N 10 delivery post number
deliveryCountry N A 10 delivery country
dbProcessUrl Y AN 255 Payment Notification url (Async notification)
vat N N 12 Vat
fee N N 12 service fee
notaxAmt N N 12 tax free amount
description N AN 100 Transaction description
merchantToken Y AN 255 merchantToken
reqDt N N 8 Request date (YYYYMMDD)
reqTm N N 6 request time (HH24MISS)
reqDomain N AN 100 request domain
reqServerIP N AN 15 request server IP
reqClientVer N AN 50 request client version
userIP Y AN 15 user IP (customer)
userSessionID N AN 100 user session ID
userAgent N AN 100 user agent information
userLanguage N A 2 user language
cartData Y AN 4000 cart data
instmntType CC N 2 Installment Type, refer Code at Here
instmntMon CC N 2 Installment month
recurrOpt CC Recurring N 2 Recurring option
0: Automatic Cancel
1: Do not cancel
2: Do not make token
bankCd VA A 4 bank code, refer Code at Here
vacctValidDt VA N 8 VA expiry date (YYYYMMDD)
vacctValidTm VA N 6 VA expiry time (HH24MISS)
merFixAcctId VA AN 40 Merchant Reserved VA ID (Fix VA)
mitraCd CVS A 4 Mitra code, refer Code at Here
mRefNo Y (CIMB) AN 18 ClickPay CIMB reference No
payValidDt Y N 8 20170313 expiry date (YYYYMMDD)
payValidTm Y N 6 135959 expiry time (HH24MISS)
"""
"""
# time_stamp Y N 14 API Request Date
# i_mid Y AN 10 Merchant Id
# currency Y AN 3 currency
# merchant_token Y AN 255 merchantToken
pay_method Y AN 2 Payment Method
amount Y N 12 Payment Amount
invoice_no Y ANS 40 Merchant Order No (Key from merchant)
goods_nm Y AN 100 Goods Name
billing_nm Y A 30 Buyer name
billing_phone Y N 40 Buyer Phone Number
billing_email Y AN 15 Buyer email
billing_addr N AN 100 Buyer address
billing_city Y A 50 Buyer city
billing_state Y A 50 Billing state
billing_post_cd Y N 10 Billing Post number
billing_country Y A 10 Billing Country
delivery_nm N A 30 delivery name
delivery_phone N N 15 delivery phone number
delivery_addr N AN 100 delivery address
delivery_city N A 50 delivery city
delivery_state N A 50 delivery state
delivery_post_cd N N 10 delivery post number
delivery_country N A 10 delivery country
# db_process_url Y AN 255 Payment Notification url (Async notification)
vat N N 12 Vat
fee N N 12 service fee
notax_amt N N 12 tax free amount
description N AN 100 Transaction description
req_domain N AN 100 request domain
req_server_ip N AN 15 request server IP
req_client_ver N AN 50 request client version
user_ip Y AN 15 user IP (customer)
user_session_id N AN 100 user session ID
user_agent N AN 100 user agent information
user_language N A 2 user language
cart_data Y AN 4000 cart data
instmnt_type CC N 2 Installment Type, refer Code at Here
instmnt_mon CC N 2 Installment month
recurr_opt CC Recurring N 2 Recurring option
0: Automatic Cancel
1: Do not cancel
2: Do not make token
bank_cd VA A 4 bank code, refer Code at Here
vacct_valid_dt VA N 8 VA expiry date (YYYYMMDD)
vacct_valid_tm VA N 6 VA expiry time (HH24MISS)
mer_fix_acct_id VA AN 40 Merchant Reserved VA ID (Fix VA)
mitra_cd CVS A 4 Mitra code, refer Code at Here (E-Wallet, CVS, Payloan)
m_ref_no Y (CIMB) AN 18 ClickPay CIMB reference No
pay_valid_dt Y N 8 20170313 expiry date (YYYYMMDD) (Payloan)
pay_valid_tm Y N 6 135959 expiry time (HH24MISS) (Payloan)
"""
payment_methods = [
('01', 'Credit Card'),
('02', 'Virtual Account (VA)'),
('03', 'Convenience Store (CVS)'),
('04', 'ClickPay'),
('05', 'E-Wallet'),
('06', 'Payloan')
]
recurring_opts = [
(0, 'Automatic Cancel'),
(1, 'Do not cancel'),
(2, 'Do not make token'),
]
form_register_methods = dict(scripts="""
$(document).ready(function(){
function HideNotGeneral() {
$(".f-instmnt_type").hide();
$(".f-instmnt_mon").hide();
$(".f-recurr_opt").hide();
$(".f-bank_cd").hide();
$(".f-vacct_valid_dt").hide();
$(".f-vacct_valid_tm").hide();
$(".f-mer_fix_acct_id").hide();
$(".f-mitra_cd").hide();
$(".f-pay_valid_dt").hide();
$(".f-pay_valid_tm").hide();
$(".f-m_ref_no").hide();
}
$("select[name=pay_method]").on("change", function(e) {
HideNotGeneral();
var v = $(this).val();
if (v == "01") {
$(".f-instmnt_type").show();
$(".f-instmnt_mon").show();
$(".f-recurr_opt").show();
}
else if (v == "02") {
$(".f-bank_cd").show();
$(".f-vacct_valid_dt").show();
$(".f-vacct_valid_tm").show();
$(".f-mer_fix_acct_id").show();
}
else if (v == "03") {
$(".f-mitra_cd").show();
$(".f-pay_valid_dt").show();
$(".f-pay_valid_tm").show();
}
else if (v == "04") {
$(".f-bank_cd").show();
$(".f-m_ref_no").show();
}
else if (v == "05") {
$(".f-mitra_cd").show();
}
else if (v == "06") {
$(".f-instmnt_type").show();
$(".f-instmnt_mon").show();
$(".f-recurr_opt").show();
$(".f-mitra_cd").show();
$(".f-pay_valid_dt").show();
$(".f-pay_valid_tm").show();
}
}).change();
});
""")
class RegisterSchema(colander.Schema):
# time_stamp Y N 14 API Request Date
# i_mid Y AN 10 Merchant Id
# currency Y AN 3 currency
# merchant_token Y AN 255 merchantToken
# pay_method = colander.SchemaNode(
# colander.String(),
# widget=widget.SelectWidget(values=payment_methods)
# )
# denom = colander.SchemaNode(
# colander.String(),
# default='CRC',
# widget=widget.TextInputWidget(attributes={'maxlength': 100})
# )
# id_pel = colander.SchemaNode(
# colander.String(),
# default='123456789',
# widget=widget.TextInputWidget(attributes={'maxlength': 100})
# )
produk_id = colander.SchemaNode(
colander.Integer(), title='Produk',
oid="produk_id", widget=deferred_produk)
customer_id = colander.SchemaNode(
colander.Integer(), title='Customer',
oid="customer_id", widget=deferred_customer)
vendor_id = colander.SchemaNode(
colander.Integer(), title='Vendor',
oid="vendor_id", widget=deferred_vendor)
amt = colander.SchemaNode(
colander.Integer(),
default=10000,
widget=widget.TextInputWidget()
)
invoice_no = colander.SchemaNode(
colander.String(),
default='20190724120359',
widget=widget.TextInputWidget(attributes={'maxlength': 40})
)
goods_nm = colander.SchemaNode(
colander.String(),
default='NICEPay API v2 Enterprise',
widget=widget.TextInputWidget(attributes={'maxlength': 100})
)
billing_nm = colander.SchemaNode(
colander.String(),
default='John Doe',
widget=widget.TextInputWidget(attributes={'maxlength': 100})
)
billing_phone = colander.SchemaNode(
colander.String(),
default='08123456789',
widget=widget.TextInputWidget(attributes={'maxlength': 40})
)
billing_email = colander.SchemaNode(
colander.String(),
default='customer@email.com',
widget=widget.TextInputWidget(attributes={'maxlength': 100})
)
billing_addr = colander.SchemaNode(
colander.String(),
default='Jalan Jend. Soedirman',
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
billing_city = colander.SchemaNode(
colander.String(),
default='Jakarta',
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
billing_state = colander.SchemaNode(
colander.String(),
default='Jakarta Selatan',
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
billing_post_cd = colander.SchemaNode(
colander.String(),
default='12345',
widget=widget.TextInputWidget(attributes={'maxlength': 10})
)
billing_country = colander.SchemaNode(
colander.String(),
default='Indonesia',
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
delivery_nm = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 100})
)
delivery_phone = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 15})
)
delivery_addr = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
delivery_city = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
delivery_state = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
delivery_post_cd = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 10})
)
delivery_country = colander.SchemaNode(
colander.String(),
missing=colander.drop,
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})
)
vat = colander.SchemaNode(
colander.Integer(),
default=0,
widget=widget.TextInputWidget()
)
fee = colander.SchemaNode(
colander.Integer(),
default=0,
widget=widget.TextInputWidget()
)
notax_amt = colander.SchemaNode(
colander.Integer(),
default=0,
widget=widget.TextInputWidget()
)
description = colander.SchemaNode(
colander.String(),
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})
)
user_language = colander.SchemaNode(
colander.String(),
missing=colander.drop,
widget=widget.TextInputWidget(attributes={'maxlength': 2})
)
cart_data = colander.SchemaNode(
colander.String(),
# default="""{
# "count": "2",
# "item": [
# {
# "img_url": "http://img.aaa.com/ima1.jpg",
# "goods_name": "Item 1 Name",
# "goods_detail": "Item 1 Detail",
# "goods_amt": "700"
# },
# {
# "img_url": "http://img.aaa.com/ima2.jpg",
# "goods_name": "Item 2 Name",
# "goods_detail": "Item 2 Detail",
# "goods_amt": "300"
# }
# ]
# }""",
default="{}",
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})
)
# # (E - Wallet, CVS, Payloan)
# mitra_cd = colander.SchemaNode(
# colander.String(),
# widget=widget.TextInputWidget()
# )
# m_ref_no = colander.SchemaNode(
# colander.String(),
# widget=widget.TextInputWidget(attributes={'maxlength': 18})
# )
# pay_valid_dt = colander.SchemaNode(
# colander.String(),
# widget=widget.TextInputWidget(attributes={'maxlength': 8})
# )
# # expire date(YYYYMMDD)(Payloan)
# pay_valid_tm = colander.SchemaNode(
# colander.String(),
# widget=widget.TextInputWidget(attributes={'maxlength': 6})
# )
# expiry time(HH24MISS)(Payloan)
class EditSchema(RegisterSchema):
id = colander.SchemaNode(
colander.Integer(), title='ID',
missing=colander.drop,
oid="id")
"""
timeStamp=20180123100505&
tXid=IONPAYTEST01201804191202084760&
merchantToken=f9d30f6c972e2b5718751bd087b178534673a91bbac845f8a24e60e8e4abbbc5&
cardNo=4222222222222222&
cardExpYymm=2006&
cardCvv=123&
cardHolderNm=Thomas Alfa Edison&
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})
)
card_no = colander.SchemaNode(
colander.String(),
default="4222222222222222",
widget=widget.TextInputWidget(attributes={'maxlength': 20})
)
card_exp = colander.SchemaNode(
colander.String(),
default="2006",
widget=widget.TextInputWidget(attributes={'maxlength': 4})
)
card_cvv = colander.SchemaNode(
colander.String(),
default="123",
widget=widget.TextInputWidget(attributes={'maxlength': 4})
)
card_holder_nm = colander.SchemaNode(
colander.String(),
default="Thomas Alfa Edison",
widget=widget.TextInputWidget(attributes={'maxlength': 50})
)
merchant_token = colander.SchemaNode(
colander.String(),
default="f9d30f6c972e2b5718751bd087b178534673a91bbac845f8a24e60e8e4abbbc5",
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
call_back_url = colander.SchemaNode(
colander.String(),
default="http://merchant.com/callbackUrl",
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
class VAPayment(colander.Schema):
code= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 4})
)
message= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 255})
)
tx_id= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 30})
)
invoice_no= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 40})
)
pay_method= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 2})
)
amount= colander.SchemaNode(
colander.Integer(),
widget=widget.TextInputWidget()
)
trans_dt= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 8})
)
trans_tm= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 6})
)
description= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 100})
)
bank_cd= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 4})
)
vacct_no= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 20})
)
currency= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 3})
)
goods_nm= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 100})
)
cust_nm= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 30})
)
valid_date= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 8})
)
valid_time= colander.SchemaNode(
colander.String(),
widget=widget.TextInputWidget(attributes={'maxlength': 6})
)
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=Partner.get_vendor_list(),
produk=Produk.get_pay_list(),
customer=Partner.get_customer_list())
schema.request = request
if row:
schema.deserialize(row)
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)
# 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
class ViewHome(BaseView):
@view_config(route_name='api-merchant-register',
permission="api-merchant-register",
renderer='templates/payment/form-register.pt')
def form_merchant_register(self):
request = self.req
session = self.ses
form = get_form(request, RegisterSchema, (btn_cancel, btn_register))
if request.POST:
controls = request.POST.items()
if 'register' 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)
return dict(form=form, params=dict(scripts=""))
@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
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)
else:
return route_register(request)
return dict(form=form, params=dict(scripts=""))
def get_row(id):
return PartnerLog.query().filter_by(id=id).first()
# todo:
"""
"""
import json import json
import logging import logging
from datetime import datetime from datetime import datetime
from importlib import import_module
import requests import requests
import xmltodict import xmltodict
...@@ -30,65 +31,6 @@ def update_harga(p, k, v): ...@@ -30,65 +31,6 @@ def update_harga(p, k, v):
return True return True
def proses_odeo(data):
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()
status = str(data["status"])
if status == "BROADCAST_NEW_PRICE":
signature = sha256("{mid}{key}{status}".format(
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")
new_price = data["new_prices"]
for k in new_price:
v = new_price[k]
update_harga(partner, k, v)
return dict(success=True)
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()
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
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
def callback_merchant(order): def callback_merchant(order):
# Callback to merchant # Callback to merchant
invoice = order.invoice invoice = order.invoice
...@@ -121,19 +63,35 @@ def callback_merchant(order): ...@@ -121,19 +63,35 @@ def callback_merchant(order):
dat.update(produk=produk) dat.update(produk=produk)
data.append(dat) data.append(dat)
js = get_jsonrpc(method="notify", params=dict(data=data)) js = get_jsonrpc(method="notify", params=dict(data=data))
log.info("Notify: %s %s" %(url, js)) log.info("Notify: %s %s" % (url, js))
try: try:
requests.post(url, data=js, timeout=10) requests.post(url, data=js, timeout=10)
except: except:
pass pass
def proses_np(data):
# todo:
pass
@view_config(route_name='api-vendor-notify', renderer='json') @view_config(route_name='api-vendor-notify', renderer='json')
def api_vendor_notify(request): def api_vendor_notify(request):
vendor_nm = request.matchdict['name'] vendor_nm = request.matchdict['name']
if vendor_nm == "odeo": if vendor_nm == "odeo":
data = json.loads(request.text) data = json.loads(request.text)
order = proses_odeo(data) elif vendor_nm == "np":
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-test', renderer="string") @view_config(route_name='api-vendor-test', renderer="string")
......
...@@ -113,7 +113,8 @@ class Vendor(VendorClass): #VendorClass ...@@ -113,7 +113,8 @@ class Vendor(VendorClass): #VendorClass
# Nicepay.set('merchantKey', self.key) # Nicepay.set('merchantKey', self.key)
Nicepay.merchantKey = self.key Nicepay.merchantKey = self.key
Nicepay.set('merchantToken', Nicepay.merchantToken()) 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("userLanguage", "en-US")
Nicepay.set("userLanguage", "")
Nicepay.set('reqClientVer', '2.0') Nicepay.set('reqClientVer', '2.0')
return True return True
...@@ -150,21 +151,32 @@ class Vendor(VendorClass): #VendorClass ...@@ -150,21 +151,32 @@ class Vendor(VendorClass): #VendorClass
Nicepay.set('deliveryState', self.invoice_det.delivery_state) Nicepay.set('deliveryState', self.invoice_det.delivery_state)
Nicepay.set('deliveryPostCd', self.invoice_det.delivery_pos) Nicepay.set('deliveryPostCd', self.invoice_det.delivery_pos)
Nicepay.set('deliveryCountry', self.invoice_det.delivery_country) Nicepay.set('deliveryCountry', self.invoice_det.delivery_country)
Nicepay.set('vat', str(self.invoice_det.vat)) # print('>>> INVOICE DET:', self.invoice_det.vat, type(self.invoice_det.vat),
Nicepay.set('fee', str(self.invoice_det.fee)) # self.invoice_det.fee, type(self.invoice_det.fee),
Nicepay.set('notaxAmt', str(self.invoice_det.notax_amt)) # self.invoice_det.notax_amt, type(self.invoice_det.notax_amt))
Nicepay.set('reqDt', self.invoice_det.req_dt) # Format (YYYYMMDD) Nicepay.set('vat', self.invoice_det.vat and int(self.invoice_det.vat) > 0 and \
Nicepay.set('reqTm', self.invoice_det.req_tm) # Format (HHiiss)\ 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('reqClientVer', '')
Nicepay.set('recurrOpt', str(self.invoice_det.recurr_opt)) Nicepay.set('instmntType', '')
Nicepay.set('instmntMon', self.invoice_det.instmnt_mon) Nicepay.set('instmntMon', '')
Nicepay.set('instmntType', self.invoice_det.instmnt_type) Nicepay.set('mRefNo', '')
Nicepay.set('mRefNo', self.invoice_det.m_ref_no) # result dari nicepay
Nicepay.set('payValidDt', self.invoice_det.pay_valid_dt) # Nicepay.set('tXid', '')
Nicepay.set('payValidTm', self.invoice_det.pay_valid_tm) # Nicepay.set('transDt', '')
Nicepay.set('tXid', self.invoice_det.tx_id) # Nicepay.set('transTm', '')
Nicepay.set('transDt', self.invoice_det.trans_dt)
Nicepay.set('transTm', self.invoice_det.trans_tm) Nicepay.set('payValidDt', '')
Nicepay.set('payValidTm', '')
Nicepay.set('recurrOpt', '')
def register(self): def register(self):
Nicepay.requestData = {} Nicepay.requestData = {}
...@@ -174,15 +186,23 @@ class Vendor(VendorClass): #VendorClass ...@@ -174,15 +186,23 @@ class Vendor(VendorClass): #VendorClass
# Nicepay.set('merchantToken', 'a20e500ecd7eb786fcda1761765ca59f344a25716ff0b576f3b42ff4ac9f7224') # Nicepay.set('merchantToken', 'a20e500ecd7eb786fcda1761765ca59f344a25716ff0b576f3b42ff4ac9f7224')
data = str(json.dumps(self.invoice_det.cart)) data = str(json.dumps(self.invoice_det.cart))
# Nicepay.set('cartData', self.invoice_det.cart) # Nicepay.set('cartData', self.invoice_det.cart)
Nicepay.set('cartData', '{}'.format(data)) cart_data = data and '{}'.format(data) or '{}'
Nicepay.set('cartData', cart_data)
self.set_optional_param() self.set_optional_param()
# For Credit Card (Don't forgot change payMethod to '01') # For Credit Card (Don't forgot change payMethod to '01')
if self.pay_method == '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: # if self.reccuring:
# # For Credit Card Reccuring Only # # For Credit Card Reccuring Only
Nicepay.set('recurrOpt', '2') # 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') # For Virtual Account (Don't forgot change payMethod to '02')
elif self.pay_method == '02': elif self.pay_method == '02':
...@@ -194,30 +214,36 @@ class Vendor(VendorClass): #VendorClass ...@@ -194,30 +214,36 @@ class Vendor(VendorClass): #VendorClass
if self.invoice_det.inv_cust_va: if self.invoice_det.inv_cust_va:
self.va_typ = 'fixed' self.va_typ = 'fixed'
Nicepay.set('merFixAcctId', self.invoice_det.inv_cust_va) Nicepay.set('merFixAcctId', self.invoice_det.inv_cust_va)
Nicepay.set('vacctValidDt', '')
Nicepay.set('vacctValidTm', '')
# 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: else:
self.va_typ = 'float' self.va_typ = 'float'
Nicepay.set('merFixAcctId', '') Nicepay.set('merFixAcctId', '')
elif self.pay_method in ['03', '04', '05']: elif self.pay_method in ['03', '05']:
# For CVS,ClickPay or E-Wallet # For CVS,ClickPay or E-Wallet
# (Don't forgot change payMethod to '03'/'04'/'05') # (Don't forgot change payMethod to '03'/'04'/'05')
Nicepay.set('mitraCd', self.bank_cd) Nicepay.set('mitraCd', self.bank_cd)
if self.pay_method == '03':
# For CVS Only # For CVS Only
Nicepay.set('payValidDt', self.invoice_det.inv_valid_date) # Format (YYYYMMDD) Nicepay.set('payValidDt', self.invoice_det.inv_valid_date) # Format (YYYYMMDD)
Nicepay.set('payValidTm', self.invoice_det.inv_valid_time) # Format (HHiiss) Nicepay.set('payValidTm', self.invoice_det.inv_valid_time) # Format (HHiiss)
elif self.pay_method == '04': elif self.pay_method == '04':
# For ClickPay Only
Nicepay.set('mRefNo', self.cust_inv_no) 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)
self.set_optional_param()
self.request = Nicepay.requestData self.request = Nicepay.requestData
log.info("REQUEST: {}".format(json.dumps(self.request))) log.info("REQUEST: {}".format(json.dumps(self.request)))
self.save_log('inquiry') self.save_log('inquiry')
...@@ -239,18 +265,58 @@ class Vendor(VendorClass): #VendorClass ...@@ -239,18 +265,58 @@ class Vendor(VendorClass): #VendorClass
result_code = int(response['resultCd']) result_code = int(response['resultCd'])
result["code"] = result_code result["code"] = result_code
result["message"] = response['resultMsg'] result["message"] = response['resultMsg']
if result_code == 0: if result_code == 0 or self.pay_method == '01':
result["currency"] = response['currency']
result["tx_id"] = response['tXid'] result["tx_id"] = response['tXid']
result['trans_dt'] = response['transDt'] result['trans_dt'] = response['transDt']
result['trans_tm'] = response['transTm'] result['trans_tm'] = response['transTm']
result["amount"] = response['amt']
result["invoice_no"] = response['referenceNo']
result["description"] = response['description']
# Jika kartu kredit # Jika kartu kredit
# if self.pay_method == '01': # if self.pay_method == '01':
# # C-Card # # C-Card
# # payment = self.request_payment(response) # # payment = self.request_payment(response)
# elif response['payMethod'] == "02": # elif response['payMethod'] == "02":
if response['payMethod'] == "02": result['pay_method'] = self.pay_method
if result['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=result['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 # VA
result["vacct_no"]=response['vacctNo'] result["vacct_no"]=response['vacctNo']
result["bank_cd"]=response['bankCd']
# result["vacct_valid_dt"]=response['vacctValidDt'] # result["vacct_valid_dt"]=response['vacctValidDt']
# result["vacct_valid_tm"]=response['vacctValidTm'] # result["vacct_valid_tm"]=response['vacctValidTm']
# result["mer_fix_acct_id"]=response['merFixAcctId'] # result["mer_fix_acct_id"]=response['merFixAcctId']
...@@ -259,13 +325,13 @@ class Vendor(VendorClass): #VendorClass ...@@ -259,13 +325,13 @@ class Vendor(VendorClass): #VendorClass
result["pay_no"]=response['payNo'] result["pay_no"]=response['payNo']
# result["pay_valid_dt"]=response['payValidDt'] # result["pay_valid_dt"]=response['payValidDt']
# result["pay_valid_tm"]=response['payValidTm'] # result["pay_valid_tm"]=response['payValidTm']
elif result['payMethod'] == "04": elif response['payMethod'] == "04":
# clickpay # clickpay
result["receipt_code"]=response['receiptCode'] result["receipt_code"]=response['receiptCode']
elif result['payMethod'] == "05": elif response['payMethod'] == "05":
# e-wallet # e-wallet
result["receipt_code"]='receiptCode' in response and response['receiptCode'] or '' result["receipt_code"]='receiptCode' in response and response['receiptCode'] or ''
elif result['payMethod'] == "06": elif response['payMethod'] == "06":
# akulaku # akulaku
pass pass
......
from _sha256 import sha256
import logging
from agratek.api.merchant.views.notify_vendor import callback_merchant, update_harga
from opensipkd.base import get_settings
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import H2hArInvoiceDet
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()
status = str(data["status"])
if status == "BROADCAST_NEW_PRICE":
signature = sha256("{mid}{key}{status}".format(
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")
new_price = data["new_prices"]
for k in new_price:
v = new_price[k]
update_harga(partner, k, v)
return dict(success=True)
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()
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
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
...@@ -13,6 +13,7 @@ import logging ...@@ -13,6 +13,7 @@ import logging
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
import urllib3 import urllib3
from . import notify
urllib3.disable_warnings() urllib3.disable_warnings()
......
from _sha256 import sha256
import logging
from agratek.api.merchant.views.notify_vendor import callback_merchant, update_harga
from opensipkd.base import get_settings
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import H2hArInvoiceDet
log = logging.getLogger(__name__)
def proses(data):
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()
status = str(data["status"])
if status == "BROADCAST_NEW_PRICE":
signature = sha256("{mid}{key}{status}".format(
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")
new_price = data["new_prices"]
for k in new_price:
v = new_price[k]
update_harga(partner, k, v)
return dict(success=True)
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()
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
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
<html metal:use-macro="load: ../base.pt">
<div metal:fill-slot="content">
<style>
button {
margin:0px 3px;
}
#main{min-height: 1px;
padding-bottom: 1px;}
</style>
</div>
<div metal:fill-slot="scripts">
<div class="panel-body col-md-12">
<div class="col-md-6 col-md-offset-3 col-xs-12 well">
<!-- Proses Template Form -->
<form method="post" accept-charset="utf-8" id="deform" class="form-horizontal"
enctype="multipart/form-data" tal:define="field form"
style="background-color:white;"
autocomplete="off">
<input type="hidden" name="_charset_">
<input type="hidden" value="deform" name="__formid__">
<!-- Tampilan untuk general error -->
<div class="alert alert-danger" tal:condition="field.error">
<div class="errorMsgLbl" i18n:translate="">
Terdapat kesalahan pengisian
</div>
<p class="errorMsg">${field.errormsg}</p>
</div>
<!-- END Tampilan untuk general error -->
<div class="col-md-12">
<!-- Looping Semua Field-->
<div tal:repeat="f form">
<div tal:condition="f.widget.hidden">
<!-- Proses Saat Field hidden-->
${structure:f.serialize()}
</div>
<div tal:condition="not f.widget.hidden and not f.children"
class="form-group f-${f.name}" >
<!-- Proses Saat Field Normal dan bukan Children-->
<!-- Field Reqired menggunakan class required -->
<label for="${f.oid}"
class="control-label col-md-4 ${f.required and 'required' or ''}"
id="req-${f.oid}">
${f.title}</label>
<div class="col-md-8">
${structure:f.serialize()}
<p tal:condition="f.error" id="error-${f.oid}" class="help-block"
tal:repeat="error f.error.messages()">
${error}</p>
</div>
</div>
<div tal:condition="f.children and f.name=='upload_files'">
<!-- Proses saat Form Adalah File Upload-->
${f.start_sequence()}
${structure:f.serialize()}
${f.end_sequence()}
</div>
<div tal:condition="f.children and f.name!='upload_files'">
<!-- Proses saat Form Adalah Children -->
${f.start_mapping()}
<div tal:repeat="g f.children" class="form-group" >
<label for="${g.oid}"
class="control-label col-md-4 ${g.required and 'required' or ''}"
id="req-${g.oid}">
${g.title}</label>
<div class="col-md-8">
${structure:g.serialize()}
<p tal:condition="g.error" id="error-${g.oid}" class="help-block"
tal:repeat="error g.error.messages()">
${error}</p>
</div>
</div>
${f.end_mapping()}
</div>
</div>
<div class="input-group-btn">
<button tal:repeat="fb form.buttons" type="${fb.type}"
class="btn ${fb.css_class} pull-right"
name="${fb.name}">${fb.title}</button>
</div>
</div>
</form>
<!-- End Template Form -->
<!-- </div> -->
</div>
</div>
</div>
</html>
<html metal:use-macro="load: ../base.pt">
<div metal:fill-slot="content">
<style>
button {
margin:0px 3px;
}
#main{min-height: 1px;
padding-bottom: 1px;}
</style>
</div>
<div metal:fill-slot="scripts">
<div class="panel-body col-md-12">
<div class="col-md-6 col-md-offset-3 col-xs-12 well">
<!-- Proses Template Form -->
<form method="post" accept-charset="utf-8" id="deform" class="form-horizontal"
enctype="multipart/form-data" tal:define="field form"
style="background-color:white;"
autocomplete="off">
<input type="hidden" name="_charset_">
<input type="hidden" value="deform" name="__formid__">
<!-- Tampilan untuk general error -->
<div class="alert alert-danger" tal:condition="field.error">
<div class="errorMsgLbl" i18n:translate="">
Terdapat kesalahan pengisian
</div>
<p class="errorMsg">${field.errormsg}</p>
</div>
<!-- END Tampilan untuk general error -->
<div class="col-md-12">
<!-- Looping Semua Field-->
<div tal:repeat="f form">
<div tal:condition="f.widget.hidden">
<!-- Proses Saat Field hidden-->
${structure:f.serialize()}
</div>
<div tal:condition="not f.widget.hidden and not f.children"
class="form-group f-${f.name}" >
<!-- Proses Saat Field Normal dan bukan Children-->
<!-- Field Reqired menggunakan class required -->
<label for="${f.oid}"
class="control-label col-md-4 ${f.required and 'required' or ''}"
id="req-${f.oid}">
${f.title}</label>
<div class="col-md-8">
${structure:f.serialize()}
<p tal:condition="f.error" id="error-${f.oid}" class="help-block"
tal:repeat="error f.error.messages()">
${error}</p>
</div>
</div>
<div tal:condition="f.children and f.name=='upload_files'">
<!-- Proses saat Form Adalah File Upload-->
${f.start_sequence()}
${structure:f.serialize()}
${f.end_sequence()}
</div>
<div tal:condition="f.children and f.name!='upload_files'">
<!-- Proses saat Form Adalah Children -->
${f.start_mapping()}
<div tal:repeat="g f.children" class="form-group" >
<label for="${g.oid}"
class="control-label col-md-4 ${g.required and 'required' or ''}"
id="req-${g.oid}">
${g.title}</label>
<div class="col-md-8">
${structure:g.serialize()}
<p tal:condition="g.error" id="error-${g.oid}" class="help-block"
tal:repeat="error g.error.messages()">
${error}</p>
</div>
</div>
${f.end_mapping()}
</div>
</div>
<div class="input-group-btn">
<button tal:repeat="fb form.buttons" type="${fb.type}"
class="btn ${fb.css_class} pull-right"
name="${fb.name}">${fb.title}</button>
</div>
</div>
</form>
<!-- End Template Form -->
<!-- </div> -->
</div>
</div>
<script>
${params.scripts}
</script>
</div>
</html>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!