source: OpenRLabs-Git/deploy/rlabs-docker/web2py-rlabs/gluon/contrib/stripe.py

main
Last change on this file was 42bd667, checked in by David Fuertes <dfuertes@…>, 4 years ago

Historial Limpio

  • Property mode set to 100755
File size: 9.3 KB
Line 
1from __future__ import print_function
2import urllib
3import json
4from hashlib import sha1
5
6class Stripe:
7    """
8    Use in WEB2PY (guaranteed PCI compliant)
9
10def pay():
11    from gluon.contrib.stripe import StripeForm
12    form = StripeForm(
13        pk=STRIPE_PUBLISHABLE_KEY,
14        sk=STRIPE_SECRET_KEY,
15        amount=150, # $1.5 (amount is in cents)
16        description="Nothing").process()
17    if form.accepted:
18        payment_id = form.response['id']
19        redirect(URL('thank_you'))
20    elif form.errors:
21        redirect(URL('pay_error'))
22    return dict(form=form)
23
24Low level API:
25
26    key='<api key>'
27    d = Stripe(key).charge(
28               amount=100, # 1 dollar!!!!
29               currency='usd',
30               card_number='4242424242424242',
31               card_exp_month='5',
32               card_exp_year='2012',
33               card_cvc_check='123',
34               description='test charge')
35    print d
36    print Stripe(key).check(d['id'])
37    print Stripe(key).refund(d['id'])
38
39    Sample output (python dict):
40    {u'fee': 0, u'description': u'test charge', u'created': 1321242072, u'refunded': False, u'livemode': False, u'object': u'charge', u'currency': u'usd', u'amount': 100, u'paid': True, u'id': u'ch_sdjasgfga83asf', u'card': {u'exp_month': 5, u'country': u'US', u'object': u'card', u'last4': u'4242', u'exp_year': 2012, u'type': u'Visa'}}
41    if paid is True than transaction was processed
42
43    """
44
45    URL_CHARGE = 'https://%s:@api.stripe.com/v1/charges'
46    URL_CHECK = 'https://%s:@api.stripe.com/v1/charges/%s'
47    URL_REFUND = 'https://%s:@api.stripe.com/v1/charges/%s/refund'
48
49    def __init__(self, key):
50        self.key = key
51
52    def charge(self,
53               amount, # in cents
54               currency='usd',
55               card_number='4242424242424242',
56               card_exp_month='5',
57               card_exp_year='2012',
58               card_cvc_check='123',
59               token=None,
60               description='test charge',
61               more=None):
62        if token:
63            d = {'amount': amount,
64                 'currency': currency,
65                 'card': token,
66                 'description': description}
67        else:
68            d = {'amount': amount,
69                 'currency': currency,
70                 'card[number]': card_number,
71                 'card[exp_month]': card_exp_month,
72                 'card[exp_year]': card_exp_year,
73                 'card[cvc_check]': card_cvc_check,
74                 'description': description}
75        if more:
76            d.update(mode)
77        params = urllib.urlencode(d)
78        u = urllib.urlopen(self.URL_CHARGE % self.key, params)
79        return json.loads(u.read())
80
81    def check(self, charge_id):
82        u = urllib.urlopen(self.URL_CHECK % (self.key, charge_id))
83        return json.loads(u.read())
84
85    def refund(self, charge_id):
86        params = urllib.urlencode({})
87        u = urllib.urlopen(self.URL_REFUND % (self.key, charge_id),
88                           params)
89        return json.loads(u.read())
90
91class StripeForm(object):
92    def __init__(self,
93                 pk, sk,
94                 amount, # in cents
95                 description,
96                 currency = 'usd',
97                 currency_symbol = '$',
98                 security_notice = True,
99                 disclosure_notice = True,
100                 template = None):
101        from gluon import current, redirect, URL
102        if not (current.request.is_local or current.request.is_https):
103            redirect(URL(args=current.request.args,scheme='https'))
104        self.pk = pk
105        self.sk = sk
106        self.amount = amount
107        self.description = description
108        self.currency = currency
109        self.currency_symbol = currency_symbol
110        self.security_notice = security_notice
111        self.disclosure_notice = disclosure_notice
112        self.template = template or TEMPLATE
113        self.accepted = None
114        self.errors = None
115        self.signature = sha1(repr((self.amount,self.description))).hexdigest()
116
117    def process(self):
118        from gluon import current
119        request = current.request
120        if request.post_vars:
121            if self.signature == request.post_vars.signature:
122                self.response = Stripe(self.sk).charge(
123                    token=request.post_vars.stripeToken,
124                    amount=self.amount,
125                    description=self.description,
126                    currency=self.currency)
127                if self.response.get('paid',False):
128                    self.accepted = True
129                    return self
130            self.errors = True
131        return self
132
133    def xml(self):
134        from gluon.template import render
135        if self.accepted:
136            return "Your payment was processed successfully"
137        elif self.errors:
138            return "There was an processing error"
139        else:
140            context = dict(amount=self.amount,
141                           signature=self.signature, pk=self.pk,
142                           currency_symbol=self.currency_symbol,
143                           security_notice=self.security_notice,
144                           disclosure_notice=self.disclosure_notice)
145            return render(content=self.template, context=context)
146
147
148TEMPLATE = """
149<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
150<script>
151jQuery(function(){
152    // This identifies your website in the createToken call below
153    Stripe.setPublishableKey('{{=pk}}');
154
155    var stripeResponseHandler = function(status, response) {
156      var jQueryform = jQuery('#payment-form');
157
158      if (response.error) {
159        // Show the errors on the form
160        jQuery('.payment-errors').text(response.error.message).show();
161        jQueryform.find('button').prop('disabled', false);
162      } else {
163        // token contains id, last4, and card type
164        var token = response.id;
165        // Insert the token into the form so it gets submitted to the server
166        var tokenInput = jQuery('<input type="hidden" name="stripeToken" />');
167        jQueryform.append(tokenInput.val(token));
168        // and re-submit
169        jQueryform.get(0).submit();
170      }
171    };
172
173    jQuery(function(jQuery) {
174      jQuery('#payment-form').submit(function(e) {
175
176        var jQueryform = jQuery(this);
177
178        // Disable the submit button to prevent repeated clicks
179        jQueryform.find('button').prop('disabled', true);
180
181        Stripe.createToken(jQueryform, stripeResponseHandler);
182
183        // Prevent the form from submitting with the default action
184        return false;
185      });
186    });
187});
188</script>
189
190<h3>Payment Amount: {{=currency_symbol}} {{="%.2f" % (0.01*amount)}}</h3>
191<form action="" method="POST" id="payment-form" class="form-horizontal">
192
193  <div class="form-row form-group">
194    <label class="col-sm-2 control-label">Card Number</label>
195    <div class="controls col-sm-10">
196      <input type="text" size="20" data-stripe="number"
197             placeholder="4242424242424242" class="form-control"/>
198    </div>
199  </div>
200
201  <div class="form-row form-group">
202    <label class="col-sm-2 control-label">CVC</label>
203    <div class="controls col-sm-10">
204      <input type="text" size="4" style="width:80px" data-stripe="cvc"
205             placeholder="XXX" class="form-control"/>
206      <a href="http://en.wikipedia.org/wiki/Card_Verification_Code" target="_blank">What is this?</a>
207    </div>
208  </div>
209
210  <div class="form-row form-group">
211    <label class="col-sm-2 control-label">Expiration</label>
212    <div class="controls col-sm-10">
213      <input type="text" size="2" style="width:40px; display:inline-block"
214             data-stripe="exp-month" placeholder="MM" class="form-control"/>
215      /
216      <input type="text" size="4" style="width:80px; display:inline-block"
217             data-stripe="exp-year" placeholder="YYYY" class="form-control"/>
218    </div>
219  </div>
220
221  <div class="form-row form-group">
222    <div class="controls col-sm-offset-2 col-sm-10">
223      <button type="submit" class="btn btn-primary">Submit Payment</button>
224      <div class="payment-errors error hidden"></div>
225    </div>
226  </div>
227  <input type="hidden" name="signature" value="{{=signature}}" />
228</form>
229
230{{if security_notice or disclosure_notice:}}
231<div class="well">
232  {{if security_notice:}}
233  <h3>Security Notice</h3>
234  <p>For your security we process all payments using a service called <a href="http://stripe.com">Stripe</a>. Thanks to <a href="http://stripe.com">Stripe</a> your credit card information is communicated directly between your Web Browser and the payment processor, <a href="http://stripe.com">Stripe</a>, without going through our server. Since we never see your card information nobody can steal it through us. Stripe is <a href="https://stripe.com/us/help/faq#security-and-pci">PCI compliant</a> and so are we.</p>
235  {{pass}}
236  {{if disclosure_notice:}}
237  <h3>Disclosure Notice</h3>
238
239  <p>We do store other information about your purchase including your name, a description of the purchase, the time when it was processed, and the amount paid. This information is necessary to provide our services and for accounting purposes. We do not disclose this information to third parties unless required to operate our services or accounting purposes.</p>
240  {{pass}}
241</div>
242{{pass}}
243"""
244
245if __name__ == '__main__':
246    key = raw_input('user>')
247    d = Stripe(key).charge(100)
248    print('charged', d['paid'])
249    s = Stripe(key).check(d[u'id'])
250    print('paid', s['paid'], s['amount'], s['currency'])
251    s = Stripe(key).refund(d[u'id'])
252    print('refunded', s['refunded'])
Note: See TracBrowser for help on using the repository browser.