stripe: Use context managers for error handling in cgi
authorClinton Ebadi <clinton@unknownlamer.org>
Thu, 27 Mar 2014 23:21:14 +0000 (19:21 -0400)
committerClinton Ebadi <clinton@unknownlamer.org>
Thu, 27 Mar 2014 23:21:14 +0000 (19:21 -0400)
stripe/stripe-payment.cgi

index 130bac2..ebb39c9 100755 (executable)
@@ -6,6 +6,7 @@ sys.path.insert(0, '/afs/hcoop.net/user/h/hc/hcoop/portal3/stripe/stripe-pkg/lib
 
 import stripe, cgi, psycopg2, cgitb, datetime, smtplib
 from email.mime.text import MIMEText
+from contextlib import contextmanager
 
 cgitb.enable()
 
@@ -34,6 +35,37 @@ def stripe_key ():
     keyfile.close ()
     return keystring
 
+
+@contextmanager
+def stripe_error_handling ():
+    try:
+        yield
+    except stripe.error.CardError, e: # The card has been declined
+        print 'Status: 200 OK'
+        print
+        print '<html>'
+        print '<head><title>Transaction Failed</title></head>'
+        print '<body>'
+        print '<h1>Failed</h1><p>Reason: '
+        print e.json_body['error']['message']
+        print '</p>'
+        print '</body>'
+        print '</html>'
+        raise
+
+@contextmanager
+def stripe_refund_on_error (charge):
+    try:
+        yield
+    except:
+        print 'Status: 200 OK'
+        print 'Content-Type: text/html'
+        print ''
+        print '<h1>Something went wrong after accepting payment!</h1>'
+        charge.refund ()
+        print '<p>The charge should be refunded. Please contact payment@hcoop.net if it was not!</p>'
+        raise
+
 # Set your secret key: remember to change this to your live secret key in production 
 # See your keys here https://manage.stripe.com/account
 
@@ -50,44 +82,22 @@ amount = request_params.getvalue('stripeDues')
 
 # Create the charge on Stripe's servers - this will charge the user's card 
 
-try: 
+with stripe_error_handling ():
     charge = stripe.Charge.create( amount=amount,
                                    currency="usd", 
                                    card=token, 
                                    description='Payment for member {0}'.format (member_name)) 
-except stripe.error.CardError, e: # The card has been declined 
-    print 'Status: 200 OK'
-    print
-    print '<html>'
-    print '<head><title>Transaction Failed</title></head>'
-    print '<body>'
-    print '<h1>Failed</h1><p>Reason: '
-    print e.json_body['error']['message']
-    print '</p>'
-    print '</body>'
-    print '</html>'
-else:
-    try:
-        balance = stripe.BalanceTransaction.retrieve (charge.balance_transaction);
-        conn = psycopg2.connect ('dbname=hcoop_portal3test user=hcoop host=postgres port=5433')
-        cur = conn.cursor ()
-        cur.execute ('insert into stripe_payment (charge_id, card_name, webuser_id, paid_on, gross, fee) values (%s, %s, %s, %s, %s, %s)',
-                     (charge.id, charge.card.name, webuser_id, datetime.date.today (), charge.amount, balance.fee))
-    except:
-        print 'Status: 200 OK'
-        print 'Content-Type: text/html'
-        print ''
-        print '<h1>Something went wrong after accepting payment!</h1>'
-        charge.refund ()
-        conn.rollback ()
-        print '<p>The charge should be refunded. Please contact payment@hcoop.net if it was not!</p>'
-        raise
-    else:
-        conn.commit ()
-        cur.close ()
-        conn.close ()
-        notify_payment (charge, member_name)
-        print 'Status: 303 See Other'
-        print 'Location: /portal/portal?cmd=stripeSuccess'
-        print ''
-        print '<a href="/portal/portal?cmd=stripeSuccess">Go back to the portal</a>'
+
+with stripe_refund_on_error (charge):
+    with psycopg2.connect ('dbname=hcoop_portal3test user=hcoop host=postgres port=5433') as conn:
+        with conn.cursor () as cur:
+            balance = stripe.BalanceTransaction.retrieve (charge.balance_transaction);
+            cur.execute ('insert into stripe_payment (charge_id, card_name, webuser_id, paid_on, gross, fee) values (%s, %s, %s, %s, %s, %s)',
+                         (charge.id, charge.card.name, webuser_id, datetime.date.today (), charge.amount, balance.fee))
+
+notify_payment (charge, member_name)
+print 'Status: 303 See Other'
+print 'Location: /portal/portal?cmd=stripeSuccess'
+print ''
+print '<a href="/portal/portal?cmd=stripeSuccess">Go back to the portal</a>'
+