## $Id: helpers.py 17754 2024-05-09 08:28:08Z henrik $ ## ## Copyright (C) 2017 Uli Fouquet & Henrik Bettermann ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## """General helper functions for the etranzact module in custom packages. """ import grok import re from datetime import datetime from ssl import SSLError from datetime import datetime from urllib import urlencode from urllib2 import urlopen from urlparse import parse_qs import httplib import hashlib import json from zope.event import notify from waeup.kofa.payments.interfaces import IPayer from waeup.kofa.utils.helpers import extract_formvars from kofacustom.nigeria.interfaces import MessageFactory as _ ERROR_PART1 = ( 'PayeeName=N/A~' + 'Faculty=N/A~' + 'Department=N/A~' + 'Level=N/A~' + 'ProgrammeType=N/A~' + 'StudyType=N/A~' + 'Session=N/A~' + 'PayeeID=N/A~' + 'Amount=N/A~' + 'FeeStatus=') ERROR_PART2 = ( '~Semester=N/A~' + 'PaymentType=N/A~' + 'MatricNumber=N/A~' + 'Email=N/A~' + 'PhoneNumber=N/A') def write_payments_log(id, payment): payment.logger.info( '%s,%s,%s,%s,%s,%s,%s,%s,,,' % ( id, payment.p_id, payment.p_category, payment.amount_auth, payment.r_code, payment.provider_amt, payment.gateway_amt, payment.thirdparty_amt)) def query_history(host, terminal_id, transaction_id, https): headers={"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} url = "/webconnect/v3/query.jsp" if https: h = httplib.HTTPSConnection(host) else: h = httplib.HTTPConnection(host) args = {'TERMINAL_ID': terminal_id, 'TRANSACTION_ID': transaction_id, } #args['RESPONSE_URL'] = responseurl h.request('POST', url, urlencode(args), headers) response = h.getresponse() if response.status!=200: return 'Connection error (%s, %s)' % (response.status, response.reason), None raw = response.read() return raw, extract_formvars(raw) # A sample caller response sent to the RESPONSE_URL # http://salsa:8080/app/applicants/cbt2015/449072/p5679522929425/receive_etranzact? # AMOUNT=3333.0& # DESCRIPTION=& # CHECKSUM=8aab3904652f8ba69ebed42d3bae80a2& # EMAIL=aa%40aa.de& # SUCCESS=C& # MESSAGE=Cancel& # LOGO_URL=https%3A%2F%2Fiuokada.waeup.org%2Fstatic_custom%2Fiou_logo.png& # RESPONSE_URL=http%3A%2F%2Fsalsa%3A8080%2Fapp%2Fapplicants%2Fcbt2015%2F449072%2Fp5679522929425%2Freceive_etranzact& # CURRENCY_CODE=NGN& # TERMINAL_ID=0000000001& # TRANSACTION_ID=p5679522929425& # MERCHANT_CODE=0339990001& # RESPONSE_CODE=C& # FINAL_CHECKSUM=E524590DBFAB719EEE428C778FFF1650& # STATUS_REASON=Cancel& # TRANS_NUM=01ESA20190913062149AHGUHQ& # CARD_NO=null& # CARD_TYPE=null # A sample query response # # #
# # A sample query response sent to the RESPONSE_URL after the browser has # automatically executed the Javascript above (we don't use this response) # http://salsa:8080/app/applicants/cbt2015/449072/p5686487280654/receive_etranzact? # LOGO_URL=https%3A%2F%2Fiuokada.waeup.org%2Fstatic_custom%2Fiou_logo.png& # RESPONSE_URL=http%3A%2F%2Fsalsa%3A8080%2Fapp%2Fapplicants%2Fcbt2015%2F449072%2Fp5686487280654%2Freceive_etranzact& # CURRENCY_CODE=NGN& # TERMINAL_ID=0000000001& # TRANSACTION_ID=p5686487280654& # AMOUNT=3333.0& # DESCRIPTION=& # CHECKSUM=3886118fcd91a376cc95c48c94dc499a& # MERCHANT_CODE=0339990001& # EMAIL=aa%40aa.de& # SUCCESS=0& # FINAL_CHECKSUM=EE105B703F84B1D67D0A4234622C03E8& # STATUS_REASON=Approved& # TRANS_NUM=01ESA20190916164636L2UTU7& # CARD_NO=506066XXXXXXXXX6666& # CARD_TYPE=Verve def process_response(payment, form, view, verify): if not form or not form.get('SUCCESS', None): msg = _('No (valid) response from Etranzact.') log = 'invalid response for payment %s' % payment.p_id payment.p_state = 'failed' notify(grok.ObjectModifiedEvent(payment)) return False, msg, log success = form.get('SUCCESS', None) # Compute final checksum transaction_id = payment.p_id amount = "%.1f" % payment.amount_auth responseurl = view.url(payment, 'receive_etranzact') hashargs = success + amount + view.terminal_id + transaction_id \ + responseurl + view.secret_key final_checksum = hashlib.md5(hashargs).hexdigest().upper() if form.get('FINAL_CHECKSUM', None) != final_checksum: msg = _('Wrong checksum.') log = 'wrong checksum for %s payment %s: %s' % ( payment.p_category, payment.p_id, str(form)) payment.p_state = 'failed' notify(grok.ObjectModifiedEvent(payment)) return False, msg, log payment.r_code = form.get('SUCCESS', None) payment.r_desc = form.get('STATUS_REASON', None) # MESSAGE also available payment.r_amount_approved = float(form.get('AMOUNT', None)) payment.r_pay_reference = form.get('TRANS_NUM', None) payment.r_card_num = "%s %s" % (form.get('CARD_TYPE', None), form.get('CARD_NO', None)) if payment.r_code != '0': msg = _('Unsuccessful response: ${a}', mapping = {'a': payment.r_desc}) log = 'unsuccessful response for %s payment %s: %s' % ( payment.p_category, payment.p_id, payment.r_desc) payment.p_state = 'failed' notify(grok.ObjectModifiedEvent(payment)) return False, msg, log if round(payment.r_amount_approved/10.0, 0) != round( payment.amount_auth/10.0, 0): msg = _('Response amount does not match.') log = 'wrong response for %s payment %s: %s' % ( payment.p_category, payment.p_id, str(form)) payment.p_state = 'failed' notify(grok.ObjectModifiedEvent(payment)) return False, msg, log transaction_id = form.get('TRANSACTION_ID', None) if transaction_id != payment.p_id: msg = _('Response transaction id does not match.') log = 'wrong response for %s payment %s: %s' % ( payment.p_category, payment.p_id, str(form)) payment.p_state = 'failed' notify(grok.ObjectModifiedEvent(payment)) return False, msg, log payment.p_state = 'paid' if not verify: payment.payment_date = datetime.utcnow() msg = _('Successful response received') log = 'valid response for %s payment %s: %s' % ( payment.p_category, payment.p_id, str(form)) notify(grok.ObjectModifiedEvent(payment)) return True, msg, log # Requerying Etranzact Payoutlet payments # Expected response: # RECEIPT_NO=500191030486&PAYMENT_CODE=500854291572447457669&MERCHANT_CODE=700602WDUB # &TRANS_AMOUNT=200000.0&TRANS_DATE=2019/10/30 # 15:13:47&TRANS_DESCR=Test%20Test%20Test-CLEARANCE%20-001-p5723474039401 # &CUSTOMER_ID=p5723474039401&BANK_CODE=500&BRANCH_CODE=001 # &SERVICE_ID=p5723474039401&CUSTOMER_NAME=Test%20Test%20Test # &CUSTOMER_ADDRESS=ASS-ENG&TELLER_ID=etzbankteller&USERNAME=%20 # &PASSWORD=%20&BANK_NAME=eTranzact%20Intl%20Plc # &BRANCH_NAME=ETRANZACT&CHANNEL_NAME=Bank&PAYMENT_METHOD_NAME=Cash # &PAYMENT_CURRENCY=566&TRANS_TYPE=101&TRANS_FEE=0.0 # &TYPE_NAME=CLEARANCE&LEAD_BANK_CODE=700&LEAD_BANK_NAME=eTranzact%20Intl%20Plc # COL1=2018/2019&COL2=Acceptance # Fee&COL3=ASS&COL4=ENG&COL5=BARTENL&COL6=400&COL7=ug_ft&COL8=N/A&COL9=11/12345 # &COL10=damms005@gmail.com&COL11=None&COL12=&COL13= def query_payoutlet(host, terminal_id, confirmation_number, payment, https): headers={"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} url = "/WebConnectPlus/query.jsp" if https: h = httplib.HTTPSConnection(host) else: h = httplib.HTTPConnection(host) args = {'TERMINAL_ID': terminal_id, 'CONFIRMATION_NO': confirmation_number, } h.request('POST', url, urlencode(args), headers) response = h.getresponse() if response.status!=200: return False, 'Connection error (%s, %s)' % (response.status, response.reason), None raw = response.read() # Remove empty lines raw = raw.replace('\r\n','') success = parse_qs(raw) if not success.get('CUSTOMER_ID'): msg = _('Invalid or unsuccessful callback: ${a}', mapping = {'a': raw}) log = 'invalid callback for payment %s: %s' % (payment.p_id, raw) payment.p_state = 'failed' return False, msg, log # We expect at least two parameters if len(success) < 2: msg = _('Invalid callback: ${a}', mapping = {'a': raw}) log = 'invalid callback for payment %s: %s' % (payment.p_id, raw) payment.p_state = 'failed' return False, msg, log customer_id = success.get('CUSTOMER_ID')[0] if payment.p_id != customer_id: msg = _('Wrong payment id') log = 'wrong callback for payment %s: %s' % (payment.p_id, raw) payment.p_state = 'failed' return False, msg, log payment.r_code = u'ET' payment.r_desc = u'%s' % success.get('TRANS_DESCR')[0] payment.r_amount_approved = float(success.get('TRANS_AMOUNT')[0]) payment.r_card_num = None payment.r_pay_reference = u'%s' % success.get('RECEIPT_NO')[0] if payment.r_amount_approved != payment.amount_auth: msg = _('Wrong amount') log = 'wrong callback for payment %s: %s' % (payment.p_id, raw) payment.p_state = 'failed' return False, msg, log log = 'valid callback for payment %s: %s' % (payment.p_id, raw) msg = _('Successful callback received') payment.p_state = 'paid' payment.payment_date = datetime.utcnow() return True, msg, log # Etranzact Credo payments helper functions def get_JSON_response_initialize(payment, host, callbackUrl, public_api_key): headers={ 'Content-Type':'application/JSON', 'Authorization':public_api_key, } h = httplib.HTTPSConnection(host) firstname = IPayer(payment).display_fullname.split()[0] lastname = IPayer(payment).display_fullname.split()[-1] email = IPayer(payment).email phone = IPayer(payment).phone args = { 'email': email, 'amount': 100 * payment.amount_auth, 'reference': payment.p_id, 'currency': 'NGN', 'callbackUrl': callbackUrl, 'customerFirstName': firstname, 'customerLastName': lastname, 'customerPhoneNumber': phone, 'bearer': '0', } try: h.request('POST', '/transaction/initialize', body=json.dumps(args), headers=headers) except SSLError: return {'error': 'SSL handshake error'} response = h.getresponse() if response.status==400: jsonout = response.read() parsed_json = json.loads(jsonout) errormsg = '' for value in parsed_json['error'].values(): errormsg += "%s. " %(value) return {'error': errormsg} if response.status!=200: return {'error': 'Connection error (%s, %s)' % (response.status, response.reason)} jsonout = response.read() parsed_json = json.loads(jsonout) # A typical JSON result # {u'status': 200, # u'execTime': 5.109764, # u'message': u'Successfully processed', # u'data': # {u'credoReference': u'vsb200B5oM0521Mb00og', # u'reference': u'xyz', # u'authorizationUrl': u'https://pay.credodemo.com/vsb200B5oM0521Mb00og' # }, # u'error': [] # } return parsed_json def initiate_payment(payment, host, callbackUrl, public_api_key): response = get_JSON_response_initialize(payment, host, callbackUrl, public_api_key) if response.get('error', None): return False, response['error'] if response['status'] == 200: return True, response['data']['authorizationUrl'] return False, response['message'] def get_JSON_response_verify(transref, host, secret_api_key): headers={ 'Content-Type':'text/xml; charset=utf-8', 'Authorization':secret_api_key, } h = httplib.HTTPSConnection(host) url = '/transaction/%s/verify' % transref try: h.request("GET", url, headers=headers) except SSLError: return {'error': 'SSL handshake error'} response = h.getresponse() if response.status==404: jsonout = response.read() parsed_json = json.loads(jsonout) return {'error': parsed_json['error']} if response.status!=200: return {'error': 'Connection error (%s, %s)' % (response.status, response.reason)} jsonout = response.read() parsed_json = json.loads(jsonout) return parsed_json def query_credo_payment(payment, host, secret_api_key): jr = get_JSON_response_verify(payment.p_id, host, secret_api_key) error = jr.get('error') if error: msg = log = error return False, msg, log # A typical JSON result #{u'status': 200, # u'execTime': 35.20671, # u'message': u'Pending bank credit notification', # u'data': { # u'status': 12, # u'businessCode': u'700607003930001', # u'channelId': 0, # u'businessRef': u'xyz', # u'businessName': u'Igbinedion University Okada', # u'settlementAmount': 100000.0, # u'currencyCode': u'NGN', # u'transFeeAmount': 1600.0, # u'transRef': u'vsb200B5oM0521Mb00og', # u'transAmount': 100000.0, # u'debitedAmount': 101600.0, # u'customerId': u'aa@aa.ng', # u'statusMessage': u'Pending bank credit notification', # u'metadata': [] # }, # u'error': [] #} payment.r_code = unicode(jr['data']['status']) payment.r_desc = jr['data']['statusMessage'] payment.r_amount_approved = jr['data']['debitedAmount'] payment.r_pay_reference = jr['data'].get('transRef', u'') payment.r_payment_link = u'n/a' payment.r_card_num = u'n/a' if payment.r_code != '0': msg = _('Unsuccessful callback: ${a}', mapping = {'a': payment.r_desc}) log = 'unsuccessful callback for %s payment %s: %s' % ( payment.p_category, payment.p_id, payment.r_desc) payment.p_state = 'failed' notify(grok.ObjectModifiedEvent(payment)) return False, msg, log payment.p_state = 'paid' payment.payment_date = datetime.utcnow() msg = _('Successful callback received') log = 'valid callback for %s payment %s: %s' % ( payment.p_category, payment.p_id, str(jr)) notify(grok.ObjectModifiedEvent(payment)) return True, msg, log