source: main/waeup.kwarapoly/trunk/src/waeup/kwarapoly/interswitch/browser.py @ 9432

Last change on this file since 9432 was 9408, checked in by Henrik Bettermann, 12 years ago

The payment_categories vocab does no longer exist. We have a dict in KofaUtils? instead.

  • Property svn:keywords set to Id
File size: 15.1 KB
RevLine 
[7894]1## $Id: browser.py 9408 2012-10-24 21:59:34Z henrik $
2##
3## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18from datetime import datetime
[7898]19import httplib
20import urllib
[9392]21import hashlib
[7898]22from xml.dom.minidom import parseString
[7894]23import grok
[8281]24from zope.component import getUtility
[7894]25from waeup.kofa.browser.layout import KofaPage, UtilityView
26from waeup.kofa.accesscodes import create_accesscode
[8281]27from waeup.kofa.interfaces import RETURNING, IKofaUtils
28from waeup.kofa.utils.helpers import to_timezone
[8421]29from waeup.kofa.students.viewlets import ApprovePaymentActionButton as APABStudent
30from waeup.kofa.applicants.viewlets import ApprovePaymentActionButton as APABApplicant
[9347]31from waeup.kwarapoly.students.interfaces import ICustomStudentOnlinePayment
32from waeup.kwarapoly.applicants.interfaces import ICustomApplicantOnlinePayment
33from waeup.kwarapoly.interfaces import MessageFactory as _
[7894]34
[9387]35PRODUCT_ID = '3986'
[9347]36SITE_NAME = 'kwarapoly-kofa.waeup.org'
[9387]37PROVIDER_ACCT = '1010764827'
38PROVIDER_BANK_ID = '117'
[8263]39PROVIDER_ITEM_NAME = 'BT Education'
[9347]40INSTITUTION_NAME = 'KwaraPoly'
[7894]41CURRENCY = '566'
[8401]42#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
[8293]43#QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
[9392]44
[9387]45#POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
46POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
[7894]47
[9387]48#HOST = 'webpay.interswitchng.com'
49HOST = 'testwebpay.interswitchng.com'
[9392]50
[9387]51#URL = '/paydirect/services/TransactionQueryWs.asmx'
52URL = '/test_paydirect/services/TransactionQueryWs.asmx'
[7898]53httplib.HTTPConnection.debuglevel = 0
54
[8256]55
[7898]56def SOAP_post(soap_action,xml):
57    """Handles making the SOAP request.
58
59    Further reading:
60    http://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryWs.asmx?op=getTransactionData
61    """
62    h = httplib.HTTPConnection(HOST)
63    headers={
64        'Host':HOST,
65        'Content-Type':'text/xml; charset=utf-8',
66        'Content-Length':len(xml),
67        'SOAPAction':'"%s"' % soap_action,
68    }
69    h.request('POST', URL, body=xml,headers=headers)
70    r = h.getresponse()
71    d = r.read()
72    if r.status!=200:
73        raise ValueError('Error connecting: %s, %s' % (r.status, r.reason))
74    return d
75
76def get_SOAP_response(product_id, transref):
77    xml="""\
78<?xml version="1.0" encoding="utf-8"?>
79<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
80  <soap:Body>
81    <getTransactionData xmlns="http://tempuri.org/">
82      <product_id>%s</product_id>
83      <trans_ref>%s</trans_ref>
84    </getTransactionData>
85  </soap:Body>
86</soap:Envelope>""" % (product_id, transref)
87    result_xml=SOAP_post("http://tempuri.org/getTransactionData",xml)
88    doc=parseString(result_xml)
89    response=doc.getElementsByTagName('getTransactionDataResult')[0].firstChild.data
90    return response
91
[8430]92def query_interswitch(payment):
[8256]93    sr = get_SOAP_response(PRODUCT_ID, payment.p_id)
94    wlist = sr.split(':')
95    if len(wlist) != 7:
[8430]96        msg = _('Invalid callback: ${a}', mapping = {'a': sr})
97        log = 'invalid callback for payment %s: %s' % (payment.p_id, sr)
98        return False, msg, log
[8256]99    payment.r_code = wlist[0]
100    payment.r_desc = wlist[1]
101    payment.r_amount_approved = float(wlist[2]) / 100
102    payment.r_card_num = wlist[3]
103    payment.r_pay_reference = wlist[5]
104    if payment.r_code != '00':
[8430]105        msg = _('Unsuccessful callback: ${a}', mapping = {'a': sr})
[8639]106        log = 'unsuccessful callback for payment %s: %s' % (payment.p_id, sr)
[8256]107        payment.p_state = 'failed'
[8430]108        return False, msg, log
[8263]109    if payment.r_amount_approved != payment.amount_auth:
[8430]110        msg = _('Callback amount does not match.')
111        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
[8256]112        payment.p_state = 'failed'
[8430]113        return False, msg, log
[8256]114    if wlist[4] != payment.p_id:
[8430]115        msg = _('Callback transaction id does not match.')
116        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
[8256]117        payment.p_state = 'failed'
[8430]118        return False, msg, log
[8256]119    payment.p_state = 'paid'
[8433]120    payment.payment_date = datetime.utcnow()
[8430]121    msg = _('Successful callback received')
122    log = 'valid callback for payment %s: %s' % (payment.p_id, sr)
123    return True, msg, log
[8256]124
[8421]125class InterswitchActionButtonStudent(APABStudent):
[8259]126    grok.order(1)
[8255]127    grok.context(ICustomStudentOnlinePayment)
[8430]128    grok.require('waeup.payStudent')
[7894]129    icon = 'actionicon_pay.png'
130    text = _('CollegePAY')
131    target = 'goto_interswitch'
132
133    @property
134    def target_url(self):
135        if self.context.p_state != 'unpaid':
136            return ''
137        return self.view.url(self.view.context, self.target)
138
[8421]139class InterswitchActionButtonApplicant(APABApplicant):
[8259]140    grok.order(1)
[8256]141    grok.context(ICustomApplicantOnlinePayment)
[8430]142    grok.require('waeup.payApplicant')
[8256]143    icon = 'actionicon_pay.png'
144    text = _('CollegePAY')
145    target = 'goto_interswitch'
146
147    @property
148    def target_url(self):
149        if self.context.p_state != 'unpaid':
150            return ''
151        return self.view.url(self.view.context, self.target)
152
[8421]153class InterswitchRequestWebserviceActionButtonStudent(APABStudent):
[8259]154    grok.order(2)
[8255]155    grok.context(ICustomStudentOnlinePayment)
[8430]156    grok.require('waeup.payStudent')
[7919]157    icon = 'actionicon_call.png'
[8421]158    text = _('Requery CollegePAY')
[7919]159    target = 'request_webservice'
160
[8421]161class InterswitchRequestWebserviceActionButtonApplicant(APABApplicant):
[8259]162    grok.order(2)
[8256]163    grok.context(ICustomApplicantOnlinePayment)
[8430]164    grok.require('waeup.payApplicant')
[8256]165    icon = 'actionicon_call.png'
[8421]166    text = _('Requery CollegePAY')
[8256]167    target = 'request_webservice'
[7919]168
[8256]169class InterswitchPageStudent(KofaPage):
[7894]170    """ View which sends a POST request to the Interswitch
171    CollegePAY payment gateway.
172    """
[8255]173    grok.context(ICustomStudentOnlinePayment)
[7894]174    grok.name('goto_interswitch')
[8256]175    grok.template('student_goto_interswitch')
[7894]176    grok.require('waeup.payStudent')
177    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
178    submit_button = _('Submit')
179    action = POST_ACTION
180    site_name = SITE_NAME
181    currency = CURRENCY
[9387]182    pay_item_id = '101'
[7894]183    product_id = PRODUCT_ID
[9392]184    mac = '737396C271FB8E2BA1A612A942267553E16373658A5F83D90DAFFBB806C16E9E6284006C06CEFFB55768004179D7BC01CD237CCE6314B938A5A5D9F49369DE5A'
[7894]185
186    def update(self):
[8256]187        #if self.context.p_state != 'unpaid':
188        if self.context.p_state == 'paid':
[7894]189            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
190            self.redirect(self.url(self.context, '@@index'))
191            return
[8256]192
[8745]193        student = self.student = self.context.student
194        certificate = getattr(student['studycourse'],'certificate',None)
[8276]195        self.amount_auth = 100 * self.context.amount_auth
[7894]196        xmldict = {}
197        if certificate is not None:
198            xmldict['department'] = certificate.__parent__.__parent__.code
199            xmldict['faculty'] = certificate.__parent__.__parent__.__parent__.code
200        else:
201            xmldict['department'] = None
202            xmldict['faculty'] = None
[9408]203        self.category = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
[8281]204        tz = getUtility(IKofaUtils).tzinfo
205        self.local_date_time = to_timezone(
206            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
[8256]207        self.site_redirect_url = self.url(self.context, 'request_webservice')
[8263]208        # Provider data
209        xmldict['detail_ref'] = self.context.p_id
210        xmldict['provider_acct'] = PROVIDER_ACCT
211        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
212        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
[9387]213        xmldict['provider_amt'] = 100 * 1200
214        # Dalash data
215        xmldict['dalash_amt'] = 100 * 1800
[8263]216        # Institution data
[9387]217        if xmldict['faculty'] in ('CPGS',):
218            xmldict['institution_acct'] = "1771180233"
219            xmldict['institution_bank_id'] = '120'
220        elif xmldict['faculty'] in ('IBAS',):
221            xmldict['institution_acct'] = "0006772436"
222            xmldict['institution_bank_id'] = '121'
223        elif xmldict['faculty'] in ('IETS',):
224            xmldict['institution_acct'] = "0106259811"
225            xmldict['institution_bank_id'] = '10'
226        elif xmldict['faculty'] in ('IFMS',):
227            xmldict['institution_acct'] = "2013910271"
228            xmldict['institution_bank_id'] = '8'
229        elif xmldict['faculty'] in ('ITCH',):
230            xmldict['institution_acct'] = "1010445144"
[9129]231            xmldict['institution_bank_id'] = '117'
232        else:
[9387]233            xmldict['institution_acct'] = "0000000000000"
[9129]234            xmldict['institution_bank_id'] = '0'
235        xmldict['institution_amt'] = 100 * (
[9387]236            self.context.amount_auth - 1200 - 300 - 1800)
[8263]237        xmldict['institution_item_name'] = self.context.p_category
238        xmldict['institution_name'] = INSTITUTION_NAME
[9392]239
240        hashargs = (
241            self.context.p_id +
242            PRODUCT_ID +
243            self.pay_item_id +
244            str(int(self.amount_auth)) +
245            self.site_redirect_url +
246            self.mac)
247        self.hashvalue = hashlib.sha512(hashargs).hexdigest()
248
[8263]249        # Interswitch amount is not part of the xml data
250        xmltext = """<payment_item_detail>
251<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s" department="%(department)s" faculty="%(faculty)s">
252<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
[9387]253<item_detail item_id="2" item_name="Dalash" item_amt="%(dalash_amt)s" bank_id="117" acct_num="1013196791" />
[9129]254<item_detail item_id="3" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
[8263]255</item_details>
256</payment_item_detail>""" % xmldict
257        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
[7894]258        return
259
[8263]260class InterswitchPageApplicant(KofaPage):
[8256]261    """ View which sends a POST request to the Interswitch
262    CollegePAY payment gateway.
263    """
264    grok.context(ICustomApplicantOnlinePayment)
265    grok.require('waeup.payApplicant')
266    grok.template('applicant_goto_interswitch')
[8263]267    grok.name('goto_interswitch')
268    label = _('Submit data to CollegePAY (Interswitch Payment Gateway)')
269    submit_button = _('Submit')
270    action = POST_ACTION
271    site_name = SITE_NAME
272    currency = CURRENCY
[9392]273    pay_item_id = ''
[8263]274    product_id = PRODUCT_ID
[8256]275
276    def update(self):
[8263]277        if self.context.p_state != 'unpaid':
278            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
279            self.redirect(self.url(self.context, '@@index'))
280            return
[8831]281        if self.context.__parent__.__parent__.expired \
282            and self.context.__parent__.__parent__.strict_deadline:
[8706]283            self.flash(_("Payment ticket can't be send to CollegePAY. "
284                         "Application period has expired."))
285            self.redirect(self.url(self.context, '@@index'))
286            return
[8256]287        self.applicant = self.context.__parent__
[8276]288        self.amount_auth = 100 * self.context.amount_auth
[8256]289        xmldict = {}
[9408]290        self.category = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
[8281]291        tz = getUtility(IKofaUtils).tzinfo
292        self.local_date_time = to_timezone(
293            self.context.creation_date, tz).strftime("%Y-%m-%d %H:%M:%S %Z")
[8256]294        self.site_redirect_url = self.url(self.context, 'request_webservice')
[8641]295        xmldict['detail_ref'] = self.context.p_id
[8263]296        # Provider data
[8644]297        xmldict['provider_amt'] = 100 * 500
[8263]298        xmldict['provider_acct'] = PROVIDER_ACCT
299        xmldict['provider_bank_id'] = PROVIDER_BANK_ID
300        xmldict['provider_item_name'] = PROVIDER_ITEM_NAME
301        # Institution data
[8644]302        xmldict['institution_amt'] = 100 * (self.context.amount_auth - 500 - 150)
[9387]303        xmldict['institution_acct'] = '0'
304        xmldict['institution_bank_id'] = '0'
[8263]305        xmldict['institution_item_name'] = self.context.p_category
306        xmldict['institution_name'] = INSTITUTION_NAME
307        # Interswitch amount is not part of the xml data
308        xmltext = """<payment_item_detail>
309<item_details detail_ref="%(detail_ref)s" college="%(institution_name)s">
310<item_detail item_id="1" item_name="%(institution_item_name)s" item_amt="%(institution_amt)d" bank_id="%(institution_bank_id)s" acct_num="%(institution_acct)s" />
311<item_detail item_id="2" item_name="%(provider_item_name)s" item_amt="%(provider_amt)d" bank_id="%(provider_bank_id)s" acct_num="%(provider_acct)s" />
312</item_details>
313</payment_item_detail>""" % xmldict
314        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
[8256]315        return
316
[7894]317
[8256]318class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
[7919]319    """ Request webservice view for the CollegePAY gateway
320    """
[8255]321    grok.context(ICustomStudentOnlinePayment)
[7919]322    grok.name('request_webservice')
323    grok.require('waeup.payStudent')
324
325    def update(self):
[8430]326        ob_class = self.__implemented__.__name__
[7919]327        if self.context.p_state == 'paid':
328            self.flash(_('This ticket has already been paid.'))
329            return
[8745]330        student = self.context.student
[8430]331        success, msg, log = query_interswitch(self.context)
[8745]332        student.writeLogMessage(self, log)
[8430]333        if not success:
334            self.flash(msg)
335            return
336        success, msg, log = self.context.doAfterStudentPayment()
337        if log is not None:
[8745]338            student.writeLogMessage(self, log)
[8430]339        self.flash(msg)
[8256]340        return
[7919]341
[8256]342    def render(self):
343        self.redirect(self.url(self.context, '@@index'))
344        return
[7926]345
[8256]346class InterswitchPaymentRequestWebservicePageApplicant(UtilityView, grok.View):
347    """ Request webservice view for the CollegePAY gateway
348    """
349    grok.context(ICustomApplicantOnlinePayment)
350    grok.name('request_webservice')
351    grok.require('waeup.payApplicant')
[7919]352
[8256]353    def update(self):
354        if self.context.p_state == 'paid':
355            self.flash(_('This ticket has already been paid.'))
[7919]356            return
[8256]357        applicant = self.context.__parent__
[8430]358        success, msg, log = query_interswitch(self.context)
[8745]359        applicant.writeLogMessage(self, log)
[8430]360        if not success:
361            self.flash(msg)
362            return
363        success, msg, log = self.context.doAfterApplicantPayment()
364        if log is not None:
[8745]365            applicant.writeLogMessage(self, log)
[8430]366        self.flash(msg)
[7919]367        return
368
369    def render(self):
370        self.redirect(self.url(self.context, '@@index'))
[9108]371        return
Note: See TracBrowser for help on using the repository browser.