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

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

Configure live payment and remove ICT split amount data again.

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