2017-03-09 70 views
0

我設置了一個簡單的條帶付款以供玩耍,並且我可以成功爲一張卡充電,但是當它失敗時,我得到一個AttributeError且'CardError'對象沒有屬性'消息'而不是HTML頁面上的錯誤消息。嘗試從失敗的條紋費用中獲取錯誤

在我的模型中,我得到了一個條帶電荷,並返回一個元組,其中包含充電成功和充電或錯誤消息的詳細信息。

#models.py中

class Sale(models.Model): 
def __init__(self, *args, **kwargs): 
    super(Sale, self).__init__(*args, **kwargs) 

    import stripe 
    stripe.api_key = settings.STRIPE_SECRET_KEY 
    self.stripe = stripe 

customer = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) 
charge_id = models.CharField(max_length=32) 



def charge(self, price_in_cents, number, exp_month, exp_year, cvc, address_zip): 

    if self.charge_id: 
     return False, Exception(message='This charge has already been issued.') 

    try: 
     response = self.stripe.Charge.create(
      amount = price_in_cents, 
      currency = 'usd', 
      card = { 
       'number': number, 
       'exp_month': exp_month, 
       'exp_year': exp_year, 
       'cvc': cvc, 
       'address_zip': address_zip, 
      }, 
      description = 'Thank you for signing up for our program.') 
     self.charge_id = response.id 
     self.customer = request.user 

    except self.stripe.error.CardError as ce: 
     return False, ce 
    except Exception as e: 
     return False, e 

    return True, response 

我的形式設置了現場,並得到從模型上的電荷。

#forms.py

class SalePaymentForm(forms.Form): 
    number = CreditCardField(required=True, label="Card Number") 
    expiration = CCExpField(required=True, label="Expiration") 
    cvc = forms.IntegerField(required=True, label="CCV Number", max_value=9999, widget=forms.TextInput(attrs={'size': '4'})) 
    address_zip = forms.IntegerField(required=True, label='Address Zip Code', max_value=99999, widget=forms.TextInput(attrs={'size': '5'})) 

def clean(self): 
    cleaned = super(SalePaymentForm, self).clean() 

    if not self.errors: 
     number = self.cleaned_data['number'] 
     exp_month = self.cleaned_data['expiration'].month 
     exp_year = self.cleaned_data['expiration'].year 
     cvc = self.cleaned_data['cvc'] 
     address_zip = self.cleaned_data['address_zip'] 

     sale = Sale() 

     success, instance = sale.charge(2500, number, exp_month, exp_year, cvc, address_zip) 

     if not success: 
      raise forms.ValidationError('Error: %s' % (instance.messages)) 
     else: 
      instance.save() 
      # Send Email 
      pass 

    return cleaned 

我的觀點只是顯示的形式,要麼去一個成功頁面重新加載或形式。

#的views.py

def charge(request): 
if request.method == "POST": 
    form = SalePaymentForm(request.POST) 

    if form.is_valid(): # charges the card 
     return HttpResponse('Success!') 
else: 
    form = SalePaymentForm() 

return render(request, 'sales.html', {'form': form}) 

這裏是sales.html

#sales.html HTML模板

<html> 
 
<head> 
 
    <title>Stripe Example</title> 
 
</head> 
 
<body> 
 
    
 
<div class="wrapper"> 
 
    
 
    {% for key, value in form.errors.items %} 
 
     <p>{{ value }}</p> 
 
    {% endfor %} 
 
    
 
    <form action="" method="post">{% csrf_token %} 
 
    
 
    {% for field in form %} 
 
     <div class="field-wrapper"> 
 
    
 
     <div class="field-label"> 
 
      {{ field.label_tag }}: 
 
     </div> 
 
    
 
     <div class="field-field"> 
 
      {{ field }} 
 
      {{ field.errors }} 
 
     </div> 
 
    
 
     </div> 
 
    {% endfor %} 
 
    
 
    <br> 
 
    <input type="submit" value="Charge Me!" /> 
 
    </form> 
 
    
 
</div> 
 
    
 
</body> 
 
</html>

感謝您的幫助。

回答

1

正在拋出的異常沒有messages屬性。 messages屬性僅適用於Django的ValidationError s類型異常及其子類。爲了處理條紋的錯誤,請參見下面的例子:

try: 
    # Use Stripe's library to make requests... 
    pass 
except stripe.error.CardError as e: 
    # Since it's a decline, stripe.error.CardError will be caught 
    body = e.json_body 
    err = body['error'] 

https://stripe.com/docs/api/python#errors

+0

我仍然得到同樣的錯誤。我猜這個問題似乎來自這個行 raise forms.ValidationError('Error:%s'%(instance.messages)) – Xixecal

+0

只需更改 raise forms.ValidationError('Error:%s' %(instance.messages)) to raise forms.ValidationError('Error:%s'%(instance。['message']))謝謝! – Xixecal

+0

如果它對你有幫助,請接受答案 –

相關問題