It is not possible to process a payment for a customer who does not have a valid

Currently, I am in the process of replacing Stripe Checkout with Stripe.js. Although everything seems to be functioning well when entering card details, I encounter an issue where the transaction never goes through. Upon clicking submit, I receive an error message stating:

Cannot charge a customer that has no active card 

I have attempted using both a test card and a genuine credit card number, yet both are resulting in the same error. Below is my stripe.rb file:

class ChargesController < ApplicationController
    before_action :authenticate_user!
    def new
    end

    def create
      # Amount in cents
      @amount = 500

      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )

      Stripe.api_key = 'sk_test_string'

charge = Stripe::Charge.create(
:amount => 1000,
:customer => customer.id,
:currency => "usd",
:card => params[:stripeToken] # replace full card details with the string token from our params
)

    rescue Stripe::CardError => e
      flash[:error] = e.message
      redirect_to new_charge_path
    end
end

Here is my HAML code including embedded JavaScript:

.well{:style => "margin-left: 0px; position: relative; min-width: 650px; min-height: 180px; max-height: 180px"}
    = form_tag charges_path :id => 'payment-form' do
      .row
      .row
        %div
          %label.control-label{:for => "number"} Card Number
          %input#number{"data-stripe" => "number", :pattern => "[\\d ]*", :placeholder => "**** **** **** ****", :size => "20", :style => "width: 18em", :type => "text", :maxlength => "16"}/
      .row
        %div
          %label.control-label{:for => "cvc"} CVC
          %input#cvc{"data-stripe" => "cvc", :pattern => "\\d*", :placeholder => "***", :size => "3", :style => "width: 3em", :type => "text"}/
          = image_tag "credit.png"
        %div
          %label.control-label Exp (MM/YYYY)
          %input#exp-month{"data-stripe" => "exp-month", :pattern => "\\d*", :placeholder => "MM", :size => "2", :type => "text"}/
          %span /
          %input#exp-year{"data-stripe" => "exp-year", :pattern => "\\d*", :placeholder => "YYYY", :size => "4", :type => "text"}/
      .row
        .price
          5.00
        %div
          %button.btn.btn-primary.btn-large{:type => "submit"} Buy Now
:javascript
 Stripe.setPublishableKey('pk_test_string');
 $('#payment-form').submit(function(event) {
   var form = $(this);
   form.find('button').prop('disabled', true);
   Stripe.createToken(form, stripeResponseHandler);
   return false;
 });
 function stripeResponseHandler(status, response) {
   var form = $('#payment-form');
   if (response.error) {
     form.find('.payment-errors').text(response.error.message);
     form.find('button').prop('disabled', false);
   } else {
     var token = response.id;
     form.append($('<input type="hidden" name="stripeToken">').val(token));
     form.get(0).submit();
   }

Upon reviewing the error logs on Stripe, it provides the following information:

error:
    message: "Cannot charge a customer that has no active card"
    type: "card_error"
    param: "card"
    code: "missing"

Although I have inputted the card details correctly, the system still encounters this error. Notably, I am utilizing test keys for this setup.

An additional insight into what was sent to Stripe:

id: cus_7gzOPGpAB2DMYY
object: "customer"
account_balance: 0
created: 1452402410
currency: null
default_source: null
delinquent: false
description: "Thank you"
discount: null
email: null
livemode: false
metadata:
shipping: null
sources:
    object: "list"
    data:
    has_more: false
    total_count: 0
    url: "/v1/customers/cus_7gzOPGpAB2DMYY/sources"
subscriptions:
    object: "list"
    data:
    has_more: false
    total_count: 0
    url: "/v1/customers/cus_7gzOPGpAB2DMYY/subscriptions"

Answer №1

In my opinion, it would be more efficient to place :card => params[:stripeToken] within the Stripe::Customer.create method rather than using Stripe::Charge.create

Answer №2

I got in touch with stripe and they were able to solve the issue. It turns out that haml interprets this code differently. Instead of using:

= form_tag charges_path :id => 'payment-form' do

You should use:

= form_tag charges_path do
   #payment-form

By making this adjustment, everything functions properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating DOM elements at specific intervals using Jquery

I am looking to dynamically create 1 div container every x seconds, and repeat this process n times. To achieve this, I have started with the following code: $(document).ready(function() { for (var i = 0; i < 5; i++) { createEle(i); } }); f ...

Discovering values within an array of objects through the use of JavaScript

Consider the following: let myArray = [ { id: "3283267", innerArray: ["434","6565","343","3665"] }, { id: "9747439", innerArray: ["3434","38493","4308403840","34343"] }, { id: "0849374", innerArray: ["343434","57575","38 ...

Adding a div after a specific child in a bootstrap grid

I've been searching tirelessly, but I just can't seem to crack this puzzle... In my Bootstrap grid, I'm faced with the challenge of injecting a div upon click after the row where the clicked div is located. For instance, I have a series of 5 ...

JavaScript shortening a string while joining it

I'm facing a challenge with string truncation in my laravel and JS(jquery) app. Initially, I suspected it was an issue with the backend (as indicated in my question here: Laravel Truncating Strings). However, after thorough debugging, I discovered tha ...

The flat function for JavaScript Arrays is not defined in React Native

I am currently developing an application using react-native and it's common knowledge that we can utilize JavaScript code in this particular project as well as any other react projects. However, whenever I attempt to use the following code snippet, t ...

Difficulties encountered when trying to load a URL or API that contains an array in javascript/p5js

I've run into a coding issue that I'm trying to troubleshoot in p5js. My goal is to retrieve data from a URL/API. The line `kursMin[1]...` gives the correct stock value, but the line `kursMin[i]` returns `[object Object]2021-03-124. close` Bo ...

Interested in learning how to redirect to a different page using vanilla JavaScript after submitting an HTML form with a Django backend?

Recently delving into Django, I encountered a challenge of linking a js file to my HTML form page and saving the form data before moving on to the next screen. My aim was to incorporate a feature where users can click a picture and POST it along with their ...

Fade in and out of div elements upon clicking on an # anchor

I have been attempting to create a function where different divs fade in and out when clicking on an image with an <a href>. Unfortunately, I have not been successful in getting it to work despite several attempts. Here is the code that I am using: ...

Regular Expressions in JavaScript can be used to search for patterns of text, such as finding a word containing

I need to validate user input. Users are allowed to use all characters, digits, "_" and "-". Currently, I am using the following code snippet to validate: myString.search(/\W/) != -1 It successfully validates everything I need except for the hyphen ...

Tips for declaring the project npm registry within the package.json configuration file

Currently, I am juggling multiple projects simultaneously and facing the issue of each project having a different node module registry. For instance, project A sources its modules from http://registroy.foo.com, while project B pulls modules from http://re ...

The completion action is never carried out

I am currently facing an issue with one of my JavaScript functions. I have several $.ajax calls throughout my webpage followed by .done(), and they all seem to be functioning properly, except for one. Can anyone identify what could be causing the error? m ...

Is there a way to modify the dimensions of this container? (CSS)

After performing a search and clicking on a result, a white bubble pops up on the map. I am looking to use CSS to make this bubble smaller as it is currently too large. Can anyone provide guidance on how to achieve this? ...

Make sure to close any existing Featherlight windows before trying to open another one

I'm setting up multiple featherlight instances when the page loads jQuery('.feedback').featherlight(jQuery( "#feedback-box" ), { closeIcon: 'close'}); jQuery('#imprint').featherlight(jQuery( "#imprint-box" ), { closeIcon ...

ES6 destructuring in a loop

I attempted to extract the father's name from an array of objects and populate a new array with these names. Here is an example: var people = [ { name: "Mike Smith", family: { father: "Harry Smith", } }, { name: "Tom Jones ...

An error occurred in the defer callback: The specified template "wiki" does not exist

I recently developed a Meteor package called Wiki. Within the package, I included a wiki.html file that contains: <template name="wiki"> FULL WIKI UI CODE HERE </template> Next, I created a wiki.js file where I defined my collections and eve ...

Enhance your webpage with our jQuery plugin that allows you to easily make Ajax

I am currently working on developing a custom jquery plugin. One of the functions within this plugin requires an ajax-call to be made. However, I want to ensure that the function remains chainable, meaning that the ajax-call should only happen after a re ...

Generate fresh JavaScript objects with customized properties

My goal is to use Javascript and JQuery to automatically create a new object with properties provided by the user when they fill out an HTML form. I have a constructor named "object" for this purpose. function object (prop1, prop2, prop3) { this.p ...

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

Unable to retrieve ajax responseText within a jquery function

Seeking assistance with a form designed for user registration. Utilizing jQuery and AJAX to validate email address availability upon blur event. Employing e.preventDefault(); in JQuery code to prevent form submission in case of errors. However, encounterin ...

render :json => 'expected output containing desired string'

Despite my repeated attempts, I still find myself struggling with the way render :json handles strings. Let's delve into Rails 3 to discuss how to set a scope. Currently, the behavior is as follows: ... render :json => 'This is the string&a ...