我正在尝试在Django中为订户创建一种方法,将订户的默认付款方式更改为与他们归档的现有卡。当我尝试访问Stripe卡时,收到错误消息“没有客户,收件人或帐户ID的用户无法检索卡。请使用customer.sources.retrieve('card_id'),receiver.cards.retrieve('card_id') ,或account.external_accounts.retrieve('card_id')代替。”尽管提供了客户。
我试图从视图中删除其他逻辑。我不知道从这里去哪里。
@login_required
# @is_subscriber
def update_payment(request):
title = 'Update Payment Methods'
description = title
key = settings.STRIPE_PUBLISHABLE_KEY
user_membership = UserMembership.objects.get(user=request.user)
current_payment_methods = stripe.PaymentMethod.list(customer=user_membership.stripe_customer_id,
type='card')
customer = stripe.Customer.retrieve(user_membership.stripe_customer_id)
if request.method == 'POST':
if request.POST.get('source_obj'):
logger.info('User is attempting to delete a paid payment method')
card_id = request.POST.get('source_obj')
if len(current_payment_methods) > 1:
stripe.Customer.delete_source(
user_membership.stripe_customer_id, card_id
)
message = 'This payment method has been removed from your account.'
messages.info(request, message=message)
logger.info('User has deleted a payment method')
elif len(current_payment_methods) <= 1:
message = 'You must have at least one payment method associated with your account.'
messages.error(request, message=message)
logger.info('User failed to delete only payment method.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
if request.POST.get('new_prim'):
logger.info('User is changing their default payment method.')
card_id = request.POST.get('new_prim')
print(card_id)
card = stripe.Card.retrieve(id=card_id, customer=user_membership.stripe_customer_id)
stripe.Customer.modify(user_membership.stripe_customer_id,
default_source=card)
message = 'You have changed your primary payment method.'
messages.success(request, message=message)
else:
logger.info('Customer is adding a payment method.')
stripe.Customer.create_source(
user_membership.stripe_customer_id,
source=request.POST.get('stripeToken')
)
message = 'You have added this payment method to your account.'
messages.success(request, message=message)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
return render(request, 'memberships/update_payment.html',
{'title': title, 'description': description, 'key': key,
'current_payment_methods': current_payment_methods,
'customer': customer})
返回此错误,而不是成功的响应。
“没有客户,接收者或帐户ID的卡无法检索。请使用customer.sources.retrieve('card_id'),receiver.cards.retrieve('card_id')或account.external_accounts.retrieve(' card_id')代替。”
答案 0 :(得分:0)
解决方案是通过客户对象检索卡。
customer = stripe.Customer.retrieve(user_membership.stripe_customer_id)
card = customer.sources.retrieve(card_id)
stripe.Customer.modify(user_membership.stripe_customer_id,
default_source=card)
答案 1 :(得分:0)
如果该卡已经与客户关联,则只需一个API请求即可完成此操作:
customer = stripe.Customer.modify('cus_123',default_source='card_123')
检索卡时,您也可以在一个API请求中执行此操作,而不必先检索客户:
card = stripe.Customer.retrieve_source('cus_123', 'card_123')