Question

I am building a Django application that uses Stripe to let users make payments to each other. Sellers need to connect their accounts to Stripe so I can save their access and refresh tokens into the database. Buyers are also able to make donations to the service during the payment.

If I try to charge the seller, I get an error I don't really understand:

"Invalid token id: tok_355k8o2rGvbwWLbLbNKPAcOk. The publishable key used to create this token is from a different account.

There is something wrong with the access token of the seller but I can't figure out what it is. I've double checked my secret and publishable keys and they are OK.

Here is the piece of code I use during payments.

Connecting sellers with Stripe:

def callback(request):
  code = request.GET.get('code')
  profile = UserProfile.objects.get(user=request.user)

  r = requests.post('https://connect.stripe.com/oauth/token', params={
    'client_secret': settings.STRIPE_SECRET_KEY,
    'code': code,
    'grant_type': 'authorization_code'
  }).json()

  try:
    profile.access_token = r['access_token']
    profile.refresh_token = r['refresh_token']
    profile.save()

    messages.success(request, "Your account was successfully connected to Stripe.")
  except KeyError:
    messages.error(request, "Unable to connect your account to Stripe.")

  return redirect('home')

Making charges:

def charge(request, item_id):
  stripe.api_key = settings.STRIPE_SECRET_KEY

  try:
    item = Item.objects.get(pk=item_id)
    profile = UserProfile.objects.get(user=item.owner)
    access_token = profile.access_token
  except Item.DoesNotExist:
    raise Http404

  if request.method == 'POST':
    form = PaymentForm(request.POST)
    if form.is_valid():
      try:
        charge = stripe.Charge.create(
          # Multiply by 100 to get value in cents
          amount=form.cleaned_data['amount'] * 100,
          application_fee=form.cleaned_data['donation'] * 100,

          currency='gbp',
          card=form.cleaned_data['stripeToken'],
          description="{} by {}".format(item.title, item.author),
          api_key=access_token, # <-- This is the line where the error occurs
        )

        messages.success(request, "The payment was successful.")
      except stripe.CardError, e:
        messages.error(request, "The payment could not be completed.")

Do you have an idea how to correct this? Many thanks.

Was it helpful?

Solution

The access token comes with its own publishable key, which you'll need to use on your form when creating card tokens for that user. You'll need to store that publishable key:

profile.access_token = r['access_token']
profile.refresh_token = r['refresh_token']
profile.publishable_key = r['stripe_publishable_key']
profile.save()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top