source: main/waeup.fceokene/trunk/src/waeup/fceokene/interswitch/browser.py @ 9434

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

Log payment category.

Adjust to previous revisions.

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