'No such token' error 400 payment request to Stripe

The site API STRIPE tells me there is an error in LOGS: For what exact reason do I get a 400 error when entering the test card numbers and clicking the "Confirm" button? This message contains all the details of my error. I have attached the code in which the payment is made. Processing tokens, etc.

POST /v1/charges
Status
400 ERR
ID
req_GKbBUprcIuSQ0X
Time
5/25/24, 1:09:58 PM
IP address
151.249.163.206
API version
2024-04-10
Source
Stripe/v1 PythonBindings/2.37.2
Idempotency
Key — badc22f3-4989-46e8-aec6-35347aa48d10

resource_missing - source
No such token: 'tok_1PKHY1IRI3YGNQKDocTdMkPu'

Was this useful?

Yes

No
{
  "source": "tok_1PKHY1IRI3YGNQKDocTdMkPu",
  "amount": "4400",
  "currency": "usd"
}
Response body
{
  "error": {
    "code": "resource_missing",
    "doc_url": "https://stripe.com/docs/error-codes/resource-missing",
    "message": "No such token: 'tok_1PKHY1IRI3YGNQKDocTdMkPu'",
    "param": "source",
    "request_log_url": "https://dashboard.stripe.com/test/logs/req_GKbBUprcIuSQ0X?t=1716631798",
    "type": "invalid_request_error"
  }
}
Request POST body
{
  "source": "tok_1PKHY1IRI3YGNQKDocTdMkPu",
  "amount": "4400",
  "currency": "usd"
}

My API tokens

STRIPE_SECRET_KEY=sk_test_51PKFiB03rDhpU9syC7RuPemfhPC6Z5IZvxaKWRR5MajKEE3tvE58VrbZjxp3y56VoGrC2QLkARr95QVuDpmmu8uv00TP46EZQM STRIPE_PUBLISHABLE_KEY=pk_test_51PKFiB03rDhpU9syvWsl9Mvlt0XLdWaDI9a8fdolFlN9SXcUSxPhd9rtolZSUKIbBikfuWoeYZkPrdxFvf1T3Pmw00DGaQtOPA

VIEWS.PY

class PaymentView(LoginRequiredMixin, View):
    def get(self, *args, **kwargs):
        order = Order.objects.filter(user=self.request.user, ordered=False).first()
        return render(self.request, 'checkout/payment.html', {'order': order})

    def post(self, *args, **kwargs):
        order = Order.objects.filter(user=self.request.user, ordered=False).first()
        token = self.request.POST.get('stripeToken')
        try:
            charge = stripe.Charge.create(
              amount=round(float(order.get_total_amount() * 100)),
              currency="usd",
              source=token
            )
        except stripe.error.CardError:
            messages.error(self.request, 'Payment could not be made')
            return redirect('products:home-page')
        except Exception:
            messages.error(self.request, 'Internal server error')
            return redirect('products:home-page')

        payment = Payment(
            user=self.request.user,
            stripe_id=charge.id,
            amount=order.get_total_amount()
        )
        payment.save()
        order.order_id = get_random_string(length=20)
        order.payment = payment
        order.ordered = True
        order.save()

        messages.info(self.request, 'Payment was successfully issued')
        return redirect('checkout:checkout-success')

JS-file

const stripe = Stripe('pk_test_51PKFiB03rDhpU9syvWsl9Mvlt0XLdWaDI9a8fdolFlN9SXcUSxPhd9rtolZSUKIbBikfuWoeYZkPrdxFvf1T3Pmw00DGaQtOPA');
const elements = stripe.elements();

// Custom styling can be passed to options when creating an Element.
const style = {
  base: {
    // Add your base input styles here. For example:
    fontSize: '16px',
    color: "#32325d",
  },
};

// Create an instance of the card Element.
const card = elements.create('card', {style});

// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');

card.addEventListener('change', ({error}) => {
  const displayError = document.getElementById('card-errors');
  if (error) {
    displayError.textContent = error.message;
  } else {
    displayError.textContent = '';
  }
});

// Create a token or display an error when the form is submitted.
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
  event.preventDefault();

  const {token, error} = await stripe.createToken(card);

  if (error) {
    // Inform the customer that there was an error.
    const errorElement = document.getElementById('card-errors');
    errorElement.textContent = error.message;
  } else {
    // Send the token to your server.
    stripeTokenHandler(token);
  }
});

const stripeTokenHandler = (token) => {
  // Insert the token ID into the form so it gets submitted to the server
  const form = document.getElementById('payment-form');
  const hiddenInput = document.createElement('input');
  hiddenInput.setAttribute('type', 'hidden');
  hiddenInput.setAttribute('name', 'stripeToken');
  hiddenInput.setAttribute('value', token.id);
  form.appendChild(hiddenInput);

  // Submit the form
  form.submit();
}

This message contains all the details of my error. I have attached the code in which the payment is made. Processing tokens, etc. help

As the error message mentions, it can't find tok_1PKHY1IRI3YGNQKDocTdMkPu on your Stripe account. Are you sure this Token was created with the same publishable key that you used in your JS file? I recommend that you check / log the publishable keys being used to create the token, and the token id.

Like the comment mentions, you should never share your secret API keys regardless of whether it's a test or live mode key. You should roll your test mode key immediately : https://stripe.com/docs/keys#rolling-keys

Also, Tokens and Charges are legacy APIs, you should be using PaymentMethods and PaymentIntents instead. See https://docs.stripe.com/payments/payment-intents/migration/charges for the differences between Charges and PaymentIntents.

You can also refer to https://docs.stripe.com/payments/quickstart for ready to use samples.

Back to Top