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

Last change on this file since 8642 was 8641, checked in by Henrik Bettermann, 13 years ago

Customize amounts and bank data. pay_item_id and product_id still missing.

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