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
Line 
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
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.viewlets import ApprovePaymentActionButton as APABStudent
29from waeup.kofa.applicants.viewlets import ApprovePaymentActionButton as APABApplicant
30from waeup.fceokene.students.interfaces import ICustomStudentOnlinePayment
31from waeup.fceokene.applicants.interfaces import ICustomApplicantOnlinePayment
32from waeup.fceokene.interfaces import MessageFactory as _
33
34PRODUCT_ID = '83'
35SITE_NAME = 'fceokene-kofa.waeup.org'
36PROVIDER_ACCT = '0026781725'
37PROVIDER_BANK_ID = '31'
38PROVIDER_ITEM_NAME = 'BT Education'
39INSTITUTION_NAME = 'FCEOkene'
40CURRENCY = '566'
41#QUERY_URL = 'https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx'
42#QUERY_URL = 'https://testwebpay.interswitchng.com/test_paydirect/services/TransactionQueryURL.aspx'
43POST_ACTION = 'https://webpay.interswitchng.com/paydirect/webpay/pay.aspx'
44#POST_ACTION = 'https://testwebpay.interswitchng.com/test_paydirect/webpay/pay.aspx'
45
46HOST = 'webpay.interswitchng.com'
47#HOST = 'testwebpay.interswitchng.com'
48URL = '/paydirect/services/TransactionQueryWs.asmx'
49#URL = '/test_paydirect/services/TransactionQueryWs.asmx'
50httplib.HTTPConnection.debuglevel = 0
51
52
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
89def query_interswitch(payment):
90    sr = get_SOAP_response(PRODUCT_ID, payment.p_id)
91    wlist = sr.split(':')
92    if len(wlist) != 7:
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
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':
102        msg = _('Unsuccessful callback: ${a}', mapping = {'a': sr})
103        log = 'unsuccessful callback for payment %s: %s' % (payment.p_id, sr)
104        payment.p_state = 'failed'
105        return False, msg, log
106    if payment.r_amount_approved != payment.amount_auth:
107        msg = _('Callback amount does not match.')
108        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
109        payment.p_state = 'failed'
110        return False, msg, log
111    if wlist[4] != payment.p_id:
112        msg = _('Callback transaction id does not match.')
113        log = 'wrong callback for payment %s: %s' % (payment.p_id, sr)
114        payment.p_state = 'failed'
115        return False, msg, log
116    payment.p_state = 'paid'
117    payment.payment_date = datetime.utcnow()
118    msg = _('Successful callback received')
119    log = 'valid callback for %s payment %s: %s' % (
120        payment.p_category, payment.p_id, sr)
121    return True, msg, log
122
123class InterswitchActionButtonStudent(APABStudent):
124    grok.order(1)
125    grok.context(ICustomStudentOnlinePayment)
126    grok.require('waeup.payStudent')
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
137class InterswitchActionButtonApplicant(APABApplicant):
138    grok.order(1)
139    grok.context(ICustomApplicantOnlinePayment)
140    grok.require('waeup.payApplicant')
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
151class InterswitchRequestWebserviceActionButtonStudent(APABStudent):
152    grok.order(2)
153    grok.context(ICustomStudentOnlinePayment)
154    grok.require('waeup.payStudent')
155    icon = 'actionicon_call.png'
156    text = _('Requery CollegePAY')
157    target = 'request_webservice'
158
159class InterswitchRequestWebserviceActionButtonApplicant(APABApplicant):
160    grok.order(2)
161    grok.context(ICustomApplicantOnlinePayment)
162    grok.require('waeup.payApplicant')
163    icon = 'actionicon_call.png'
164    text = _('Requery CollegePAY')
165    target = 'request_webservice'
166
167class InterswitchPageStudent(KofaPage):
168    """ View which sends a POST request to the Interswitch
169    CollegePAY payment gateway.
170    """
171    grok.context(ICustomStudentOnlinePayment)
172    grok.name('goto_interswitch')
173    grok.template('student_goto_interswitch')
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
180    pay_item_id = '8302'
181    product_id = PRODUCT_ID
182
183    def update(self):
184        #if self.context.p_state != 'unpaid':
185        if self.context.p_state == 'paid':
186            self.flash(_("Payment ticket can't be re-send to CollegePAY."))
187            self.redirect(self.url(self.context, '@@index'))
188            return
189
190        student = self.student = self.context.student
191        certificate = getattr(student['studycourse'],'certificate',None)
192        self.amount_auth = 100 * self.context.amount_auth
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
200        self.category = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
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")
204        self.site_redirect_url = self.url(self.context, 'request_webservice')
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
210        xmldict['provider_amt'] = 100 * 500
211        # Institution data
212        studycourse = student['studycourse']
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)
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" />
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" />
240</item_details>
241</payment_item_detail>""" % xmldict
242        self.xml_data = """<input type="hidden" name="xml_data" value='%s'  />""" % xmltext
243        return
244
245class InterswitchPageApplicant(KofaPage):
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')
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
258    pay_item_id = '8303'
259    product_id = PRODUCT_ID
260
261    def update(self):
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
266        if self.context.__parent__.__parent__.expired \
267            and self.context.__parent__.__parent__.strict_deadline:
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
272        self.applicant = self.context.__parent__
273        self.amount_auth = 100 * self.context.amount_auth
274        xmldict = {}
275        self.category = getUtility(IKofaUtils).PAYMENT_CATEGORIES[self.context.p_category]
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")
279        self.site_redirect_url = self.url(self.context, 'request_webservice')
280        xmldict['detail_ref'] = self.context.p_id
281        # Provider data
282        xmldict['provider_amt'] = 100 * 500
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
287        xmldict['institution_amt'] = 100 * (self.context.amount_auth - 500 - 150)
288        xmldict['institution_acct'] = '1012445289'
289        xmldict['institution_bank_id'] = '117'
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
300        return
301
302
303class InterswitchPaymentRequestWebservicePageStudent(UtilityView, grok.View):
304    """ Request webservice view for the CollegePAY gateway
305    """
306    grok.context(ICustomStudentOnlinePayment)
307    grok.name('request_webservice')
308    grok.require('waeup.payStudent')
309
310    def update(self):
311        ob_class = self.__implemented__.__name__
312        if self.context.p_state == 'paid':
313            self.flash(_('This ticket has already been paid.'))
314            return
315        student = self.context.student
316        success, msg, log = query_interswitch(self.context)
317        student.writeLogMessage(self, log)
318        if not success:
319            self.flash(msg)
320            return
321        success, msg, log = self.context.doAfterStudentPayment()
322        if log is not None:
323            student.writeLogMessage(self, log)
324        self.flash(msg)
325        return
326
327    def render(self):
328        self.redirect(self.url(self.context, '@@index'))
329        return
330
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')
337
338    def update(self):
339        if self.context.p_state == 'paid':
340            self.flash(_('This ticket has already been paid.'))
341            return
342        applicant = self.context.__parent__
343        success, msg, log = query_interswitch(self.context)
344        applicant.writeLogMessage(self, log)
345        if not success:
346            self.flash(msg)
347            return
348        success, msg, log = self.context.doAfterApplicantPayment()
349        if log is not None:
350            applicant.writeLogMessage(self, log)
351        self.flash(msg)
352        return
353
354    def render(self):
355        self.redirect(self.url(self.context, '@@index'))
356        return
Note: See TracBrowser for help on using the repository browser.