简体   繁体   English

更改/更新条带订阅的问题(django)

[英]Issues with changin/updating stripe subscription (django)

Currently have this code for one of the subscriptions that I have available on my site.目前,此代码适用于我在我的网站上提供的订阅之一。 The code checks to see if the user has a plan already, if they don't, the else statement is run (works fine) and if they do, the code for updating their current subscription is replaced with the new subscription.(not working)代码检查用户是否已经有计划,如果没有,则运行 else 语句(工作正常),如果有,更新其当前订阅的代码将替换为新订阅。(不工作)

@login_required
def charge(request):

    user_info = request.user.profile
    email = user_info.inbox


    if request.method == 'POST':
        #returns card token in terminal
        print('Data:', request.POST)

        user_plan = request.user.profile.current_plan

        if user_plan != 'None':
            '''if they have a plan already, override that plan
            with this new plan this is using an already created
            user'''

            #this throws an error right now
            new_plan = stripe.Subscription.modify(
                #the current plan(wanting to change)
                user_info.subscription_id,
                cancel_at_period_end=True,
                proration_behavior='create_prorations',
                #the new subscription
                items=[{'plan':'price_HHU1Y81pU1wrNp',}]
                )

            user_info.subscription_id = new_plan.id

        #if they don't have a subscription already
        else:
            amount = 10

            customer = stripe.Customer.create(
                email=email,
                source=request.POST['stripeToken'],
                description=user_info.genre_one,
                )

            charge = stripe.Subscription.create(
                customer=customer.id,#email of logged in person
                items = [{"plan": "price_HHU1Y81pU1wrNp"}],#change plan id depending on plan chosen
                )

            #updates users current plan with its id and other info 
            user_info.subscription_id = charge.id
            user_info.customer_id = customer.id
        user_info.current_plan = 'B'
        user_info.save()

        return redirect(reverse('success', args=[amount]))

When I try and update the users subscription to the new one I get this runtime error:当我尝试将用户订阅更新为新订阅时,我收到此运行时错误:

Request req_kK2v51jnhuuKsW: Cannot add multiple subscription items with the same plan: price_HHU1Y81pU1wrNp

The Account that I am testing with has a plan that is different than the one that im trying to update to.我正在测试的帐户的计划与我尝试更新的计划不同。 (this code is for basic plan, the account has the standard plan enabled). (此代码用于基本计划,帐户已启用标准计划)。

All help is greatly appreciated!非常感谢所有帮助!

Edit: This is the model data, I tried changing all the 'None' values to something else to see if it would change the error but it didn't.编辑:这是 model 数据,我尝试将所有“无”值更改为其他值,看看它是否会改变错误,但它没有。

SUB_PLANS = [
('None','None'),
('B','Basic Plan'),
('S', 'Standard Plan'),
('P', 'Premium Plan'),
]


GENRE_CHOICES = [
('1','None'),
('2','Adventure'),
('3','Action'),
('4','Puzzle'),
('5','Story Based'),

]

# Create your models here.
class Profile(models.Model):
    User = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    username = models.CharField(max_length=30)
    #where games are sent
    inbox = models.EmailField(max_length = 50)
    current_plan = models.CharField(max_length = 4, choices = SUB_PLANS, default='None')
    #genres they like
    genre_one = models.CharField(max_length = 20, choices = GENRE_CHOICES, default = 'None')
    genre_two = models.CharField(max_length = 20, choices = GENRE_CHOICES, default = 'None')
    genre_three = models.CharField(max_length = 20, choices = GENRE_CHOICES, default = 'None')

    subscription_id = models.CharField(max_length = 40, default="None")
    customer_id = models.CharField(max_length = 40, default = "None")

    '''on account creation plan == null, then once they buy one,
    plan is added as a dropdown that they can edit easy'''
    def __str__(self):
        return self.username

The trick here is that if you're updating an existing Subscription that already has a single item, then you'll need to pass the ID for that SubscriptionItem when updating so that the API knows you're not attempting to add a second SubscriptionItem with the same plan.这里的技巧是,如果您要更新已经有一个项目的现有 Subscription,那么您需要在更新时传递该 SubscriptionItem 的 ID,以便 API 知道您没有尝试添加第二个 SubscriptionItem相同的计划。

Based on that error message, it seems the Plan was already updated on that Subscription, but likely not in the way you're expecting.根据该错误消息,该计划似乎已针对该订阅进行了更新,但可能与您期望的方式不同。 If the Subscription started out on the "standard" plan, then your code above was executed, it likely added the "basic" plan in addition to the existing standard.如果订阅以“标准”计划开始,那么上面的代码已被执行,它可能会在现有标准之外添加“基本”计划。 I bet they are subscribed to both basic and standard now.我敢打赌,他们现在订阅了basicstandard版。 In order to update as you expect, you'll want to delete the standard SubscriptionItem and add the basic SubscriptionItem which I'll show code for below.为了按照您的预期进行更新,您需要删除标准的 SubscriptionItem 并添加基本的 SubscriptionItem,我将在下面显示代码。 Alternatively, you can update the SubscriptionItem directly to swap the plan.或者,您可以直接更新 SubscriptionItem以交换计划。

Note that if you have multiple plans per Subscription, this example will need to be modified to find the correct SubscriptionItem ID.请注意,如果每个订阅有多个计划,则需要修改此示例以找到正确的 SubscriptionItem ID。 Here's one way to do this:这是执行此操作的一种方法:

current_subscription = stripe.Subscription.retrieve(user_info.subscription_id)

new_plan = stripe.Subscription.modify(
    user_info.subscription_id,
    cancel_at_period_end=True,
    proration_behavior='create_prorations',
    #the new subscription
    items=[{
        'id': current_subscription['items'].data[0].id, # note if you have more than one Plan per Subscription, you'll need to improve this. This assumes one plan per sub.
        'deleted': True,
    }, {
        'plan': 'price_HHU1Y81pU1wrNp'
    }]
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM