如何在订阅时创建stripe_id?

时间:2017-01-29 23:14:01

标签: python django stripe-payments

我在我的网站上使用带有django-allauth的API条带,我想为刚订阅的新用户创建一个stripe_id,不久前我的代码正在运行,今天我收到了一个新错误我从未遇到过:

  

stripe.error.AuthenticationError:未提供API密钥。 (提示:使用“stripe.api_key =”设置API密钥)。您可以从Stripe Web界面生成API密钥。

当用户第一次订阅或登录时,我会在其中创建一个新的stripe_id回调,然后调用回调,但在创建Customer时出错。请参阅 models.py

class Profile(models.Model):
    stripe_id = models.CharField(max_length=200, null=True, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ...

def stripeCallback(sender, request, user, **kwargs):
    user_stripe_account, created = Profile.objects.get_or_create(user=user)
    if user_stripe_account.stripe_id is None or user_stripe_account.stripe_id == '':
        new_stripe_id = stripe.Customer.create(email=user.email) #error occurs here
        user_stripe_account.stripe_id = new_stripe_id['id']
        user_stripe_account.save()

user_logged_in.connect(stripeCallback)
user_signed_up.connect(stripeCallback)

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

您正在类Profile中定义stripe_id,但这应该在它之外分配。 尝试设置

 stripe.api_key = settings.STRIPE_SECRET_KEY 

首先是代码的其余部分。

在YouTube视频中也完美地解释了这一点: https://www.youtube.com/watch?v=9Wbfk16jEOk&t=79s

例如,这是我为类似项目创建的models.py:

from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from allauth.account.signals import user_logged_in, user_signed_up
import stripe
# Create your views here.

stripe.api_key = settings.STRIPE_SECRET_KEY 

# Create your models here.

class profile(models.Model):
    name = models.CharField(max_length=120)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True,
     blank=True)
    description = models.TextField(default='description default text')

    def __unicode__(self):
        return self.name

class userStripe(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    stripe_id = models.CharField(max_length=200, null=True, blank=True)

    def __unicode__(self):
        if self.stripe_id:
            return str(self.stripe_id)
        else:
            return self.user.username 

    def stripeCallback(sender, request, user, **kwargs):
        user_stripe_account, created = 
              userStripe.objects.get_or_create(user=user)
        if created:
            print 'created for %s'%(user.username)
        if user_stripe_account.stripe_id is None or
            user_stripe_account.stripe_id == '':
            new_stripe_id = stripe.Customer.create(email=user.email)
            user_stripe_account.stripe_id = new_stripe_id['id']
            user_stripe_account.save()

def profileCallback(sender, request, user, **kwargs):
    userProfile, is_created = profile.objects.get_or_create(user=user)
    if is_created:
        userProfile.name = user.username
        userProfile.save()
相关问题