RailsApps / rails-stripe-membership-saas

An example Rails 4.2 app with Stripe and the Payola gem for a membership or subscription site.

Home Page:http://railsapps.github.io/rails-stripe-membership-saas

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Stripe logs show requests but no new subscriptions for example.com users

daluzluiz opened this issue · comments

I have a question and I don't if this is right. When I can register an user successfully but stripe does not seem to record their info or register the sale as it should when a user signs up.

I can see from the logs on stripe that i gets some of the info from the app, but I don't see anything on my dashboard or customer. On my app, the credit card info is not there as well.

I'm wondering if this is how its suppose to be in the test environment or there's something wrong with my app.

Thanks

In test mode, Stripe should show you a new customer and new subscription. So something is wrong. Try the newest version of the app from the repo as it recent additions that are not in the generated version. There are Cucumber tests you can run to see if your Stripe connection is configured correctly.

I've cloned the app from the repo, it should be the latest right? From the logs on stripe I can see that it somehow communicates with stripe. But now sure why is not creating the user and subscription.

Response body

card:
    country: "US"
    fingerprint: "2a9fgHKyg6mHCfVJ"
    address_line2: null
    address_line1: null
    address_zip: null
    last4: "5100"
    exp_month: 1
    type: "MasterCard"
    object: "card"
    exp_year: 2014
    address_state: null
    address_city: null
    name: "juliana"
    address_country: null
used: false
object: "token"
livemode: false
id: "tok_0rsCo7xzPp0Pau"
created: 1354814951

what results do you get when you run rake spec?

this is what i get:

/Users/luizdaluz/.rvm/rubies/ruby-1.9.3-p327/bin/ruby -S rspec ./spec/controllers/content_controller_spec.rb ./spec/controllers/home_controller_spec.rb ./spec/controllers/users_controller_spec.rb ./spec/mailers/user_mailer_spec.rb ./spec/models/user_spec.rb ./spec/stripe/stripe_config_spec.rb
.........................FF

Failures:

  1. Config Variables STRIPE_API_KEY should not be nil
    Failure/Error: Stripe.api_key.should_not be_nil,
    Your STRIPE_API_KEY is not set, Please refer to the 'Configure the Stripe Initializer' section of the README

    ./spec/stripe/stripe_config_spec.rb:8:in `block (3 levels) in <top (required)>'

  2. Config Variables STRIPE_PUBLIC_KEY should not be nil
    Failure/Error: STRIPE_PUBLIC_KEY.should_not be_nil,
    Your STRIPE_PUBLIC_KEY is not set, Please refer to the 'Configure the Stripe Initializer' section of the README

    ./spec/stripe/stripe_config_spec.rb:17:in `block (3 levels) in <top (required)>'

Finished in 0.79702 seconds
27 examples, 2 failures

Failed examples:

rspec ./spec/stripe/stripe_config_spec.rb:7 # Config Variables STRIPE_API_KEY should not be nil
rspec ./spec/stripe/stripe_config_spec.rb:16 # Config Variables STRIPE_PUBLIC_KEY should not be nil

Randomized with seed 52989

rake aborted!
/Users/luizdaluz/.rvm/rubies/ruby-1.9.3-p327/bin/ruby -S rspec ./spec/controllers/content_controller_spec.rb ./spec/controllers/home_controller_spec.rb ./spec/controllers/users_controller_spec.rb ./spec/mailers/user_mailer_spec.rb ./spec/models/user_spec.rb ./spec/stripe/stripe_config_spec.rb failed
/Users/luizdaluz/.rvm/gems/ruby-1.9.3-p327@rails-stripe-membership-saas/gems/rspec-core-2.12.0/lib/rspec/core/rake_task.rb:154:in run_task' /Users/luizdaluz/.rvm/gems/ruby-1.9.3-p327@rails-stripe-membership-saas/gems/rspec-core-2.12.0/lib/rspec/core/rake_task.rb:122:inblock (2 levels) in initialize'
/Users/luizdaluz/.rvm/gems/ruby-1.9.3-p327@rails-stripe-membership-saas/gems/rspec-core-2.12.0/lib/rspec/core/rake_task.rb:120:in block in initialize' /Users/luizdaluz/.rvm/gems/ruby-1.9.3-p327@rails-stripe-membership-saas/bin/ruby_noexec_wrapper:14:ineval'
/Users/luizdaluz/.rvm/gems/ruby-1.9.3-p327@rails-stripe-membership-saas/bin/ruby_noexec_wrapper:14:in `

'
Tasks: TOP => spec
(See full trace by running task with --trace)

but the API keys are there. also on the javascript file.

Try hardcoding them instead of using the ENV variables.

how do I do that? Sorry for such a noob question.

In the Stripe initializer file config/initializers/stripe.rb, look for

Stripe.api_key = ENV["STRIPE_API_KEY"]
STRIPE_PUBLIC_KEY = ENV["STRIPE_PUBLIC_KEY"]

and replace ENV["STRIPE_API_KEY"] and ENV["STRIPE_PUBLIC_KEY"] with the keys Stripe gives you.

I have done that from the beginning. That's I mentioned that from the logs on stripe I can that the app and stripe connect somehow. But it does not add the customer or the subscription to stripe. The user is created on the app, but the CC info is not recorded as well.

What do you see in the Stripe logs?

for exemple, If i use a valid card, I get the 200 OK:

POST /v1/tokens 2012/12/07 00:03:54
Summary

Time:
    2012/12/07 00:03:54
Method:
    POST
URL:
    /v1/tokens
Status:
    200
IP address:
    76.166.228.173

Parsed Request Query Parameters

    key: "MY_TEST_KEY"
    card:
        exp_year: "2013"
        cvc: "***"
        exp_month: "6"
        number: "************4242"
        name: "Silver User"

Parsed Request POST Body
No body
Response body

    object: "token"
    id: "tok_0ryZZVoQJL5SQ1"
    created: 1354838634
    livemode: false
    card:
        object: "card"
        country: "US"
        address_line2: null
        address_line1: null
        address_country: null
        type: "Visa"
        fingerprint: "eCOsewGdYPBQGlwC"
        address_city: null
        exp_year: 2013
        address_zip: null
        address_state: null
        last4: "4242"
        exp_month: 6
        name: "Silver User"
    used: false

I see you have key: "MY_TEST_KEY"
that should be something like

pk_OGQRwoebqerboqoirb

You changed it just to get it secret here? Or you really have key: "MY_TEST_KEY"?

No, I just changed it now before posting it in here (not sure if it matters or not). But the log has my real test key.

Ok, just checking. It is a public key so doesn't matter if it is public.

Sorry to butt in, but have you tried running the cucumber tests? they may help give you a few more clues as to whats going on.

Your Stripe log entry looks identical to mine.

@tmock12 has a good point, you should run:

$ cucumber

Have you set up a plan on Stripe named "Silver"?

I did, and this is what I got:

Failing Scenarios:
cucumber features/users/sign_up_with_stripe.feature:11 # Scenario: With valid card data
cucumber features/users/sign_up_with_stripe.feature:56 # Scenario: With declined card

16 scenarios (2 failed, 14 passed)
78 steps (2 failed, 1 skipped, 75 passed)
0m18.400s

Strange. Testy McUserson and Testy McDecline fail but Testy McBadCard and Testy McBadCode succeed.

@tmock12 ain't that odd?

I have all 3 plans set up as mentioned on the tutorial.

Testy McUserson:

Then I should be on the "content silver" page # features/step_definitions/user_steps.rb:156
expected: "/content/silver"
got: "/users" (using ==) (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/user_steps.rb:157:in /^I should be on the "([^"]*)" page$/' features/users/sign_up_with_stripe.feature:22:inThen I should be on the "content silver" page'
And I should see a successful sign up message # features/step_definitions/user_steps.rb:172

and

Testy McDecline:

And I should see "declined" # features/step_definitions/user_steps.rb:152
expected there to be text "declined" in "Rails Stripe Membership Saas Login Sign up Silver Subscription Plan Please review the problems below: × No API key provided. (HINT: set your API key using "Stripe.api_key = ". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.). Name * Email * Password * Password confirmation Credit Card Number Card Security Code (CVV) Card Expiration 1 - January 2 - February 3 - March 4 - April 5 - May 6 - June 7 - July 8 - August 9 - September 10 - October 11 - November 12 - December 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022" (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/user_steps.rb:153:in /^I should see "(.*?)"$/' features/users/sign_up_with_stripe.feature:68:inAnd I should see "declined"'

Testy McDecline is helpful. He shows that Stripe replied "No API key provided." And we saw that the RSpec tests failed with "Config Variables STRIPE_API_KEY should not be nil".

Yet the Stripe logs show that you are getting a token (if I am reading them correctly).

Yes, somehow the app seems to be in communication with stripe, but for some reason stripe is not recording the subscription and the app is not getting the cc info from stripe. Very odd..

@DanielKehoe I think it's because with McUserson and McDecline they actually try and run the cards and the tests are failing at the point of creating the users.

That would be my guess as to why those two tests pass

@daluzluiz I really think your keys aren't being set. did you hardcode in the javascript key?

In the file file app/assets/javascripts/registrations.js.erb add a log statement to handleStripeResponse:

        handleStripeResponse: function(status, response) {
          console.log(JSON.stringify(response))
          if (status === 200) {
            $('#user_stripe_token').val(response.id)
            // $('.card_form')[0].submit()
          } else {
            $('#stripe_error').text(response.error.message).show();
            return $('input[type=submit]').prop('disabled', false);
          }
        }

Then open the JavaScript console and try creating a subscription.

Notice that you have to comment out $('.card_form')[0].submit() (I just updated my suggestion above to include it).

this is how my javascript file looks like:

$('.registrations').ready(function() {
$.externalScript('https://js.stripe.com/v1/').done(function(script, textStatus) {
Stripe.setPublishableKey('pk_test_s78o7XhUivKxSY5hVMXhNHKR');
var subscription = {
setupForm: function() {
return $('.card_form').submit(function() {
$('input[type=submit]').prop('disabled', true);
if ($('#card_number').length) {
subscription.processCard();
return false;
} else {
return true;
}
});
},
processCard: function() {
var card;
card = {
name: $('#user_name').val(),
number: $('#card_number').val(),
cvc: $('#card_code').val(),
expMonth: $('#card_month').val(),
expYear: $('#card_year').val()
};
return Stripe.createToken(card, subscription.handleStripeResponse);
},
handleStripeResponse: function(status, response) {
if (status === 200) {
$('#user_stripe_token').val(response.id)
$('.card_form')[0].submit()
} else {
$('#stripe_error').text(response.error.message).show();
return $('input[type=submit]').prop('disabled', false);
}
}
};
return subscription.setupForm();
});
});

I noticed that I replaced '<%= STRIPE_PUBLIC_KEY %>' with the public key without the '<%= %>. Is that why? If yes, I tried adding them and now I get some other errors.

The <%= %> is just like in a view template. It says "substitute a variable here". So yes,

Stripe.setPublishableKey('pk_test_s78o7XhUivKxSY5hVMXhNHKR');

is okay.

But... you really should leave that as we wrote it and hardcode in the Stripe initializer file config/initializers/stripe.rb. Show me what you have in the file config/initializers/stripe.rb (but obscure the secret Stripe.api_key before posting it here).

if my stripe.rb looks like this:

Stripe.api_key = ENV["sk_test_xxxxxxxxxxxxxxxxxx"]
STRIPE_PUBLIC_KEY = ENV["pk_test_s78o7XhUivKxSY5hVMXhNHKR"]

StripeEvent.setup do
subscribe 'customer.subscription.deleted' do |event|
user = User.find_by_customer_id(event.data.object.customer)
user.expire
end
end

I changed my Stripe initializer file config/initializers/stripe.rb to look like this:

Stripe.api_key = "foobar"
STRIPE_PUBLIC_KEY = ENV["STRIPE_PUBLIC_KEY"]

and ran

$ cucumber

Testy McUserson and Testy McDecline fail but Testy McBadCard and Testy McBadCode succeed. Exactly as @daluzluiz reports.

So my hypothesis is that @daluzluiz has the wrong Stripe.api_key.

Indeed, your keys are wrong. If you look above, I said:

Replace ENV["STRIPE_API_KEY"] and ENV["STRIPE_PUBLIC_KEY"] with the keys Stripe gives you.

You should have:

Stripe.api_key = "sk_test_xxxxxxxxxxxxxxxxxx"
STRIPE_PUBLIC_KEY = "pk_test_s78o7XhUivKxSY5hVMXhNHKR"

That's the correct way to hardcode your Stripe keys. Hardcoding the Stripe keys in the Stripe initializer file will eliminate the possibility that you don't have your Unix ENV variables set correctly. Once you get the app running with hardcoded Stripe keys in the Stripe initializer file, you can look at problems with setting your Unix ENV variables (I can't help you with that).

Thanks, now cucumber passes everything.

But I did that before, although cucumber passes everything, when I try registering a user, stripe does not get his info. When cucumber runs, the user and subscription now show on stripe.

If Cucumber runs, and the user and subscription now show on Stripe, that shows you the application is working.

Try to identify the differences between what you input (and fails) and what Cucumber inputs (and succeeds).

  Scenario: With valid card data
    Given I fill in the following:
      | Name                       | Testy McUserson   |
      | Email                      | testy@testing.com |
      | user_password              | secret_password   |
      | user_password_confirmation | secret_password   |
      | Credit Card Number         | 4242424242424242  |
      | card_code                  | 111               |
    Then I select "5 - May" as the "month"
    And I select "2015" as the "year"
    When I press "Sign up"
    Then I should be on the "content silver" page
    And I should see a successful sign up message

Yes, seems like whenever I use the email @example.com it does not work. Is that why?

It's because of the statement in app/models/user.rb:

return if email.include?('@example.com') and not Rails.env.production?

Here's how it's supposed to work. Keep the "example.com" addresses in your seeds.rb file during local testing. The "return if..." statement allows you to run seeds.rb and add the admin and sample users. Users with an "example.com" domain will not get added to Stripe as subscribers.

When you deploy to Heroku, change the seeds.rb file to include your own email address for admin and remove the sample users. Change the "return if..." statement to this:

return if email.include?('@myemaildomain.com')

which will allow you to run rake db:seed on Heroku to set up your admin account without credit card data. Log in with your admin account and change your password. Everything should work.

@tmock12 the "example.com" admin and sample users in the seeds.rb file are tripping people up. Got any ideas how we can make that easier? Of course I can write better documentation on that topic. But maybe there is a better way to approach it? The idea was to run rake db:seed to set up the admin user.

Got it, I kind understood after this whole thing, but at first when I read it was somewhat unclear to me. I would say same thing with the ENV["STRIPE_PUBLIC_KEY"], it could be just "REPLACE_WITH_STRIPE_PUBLIC_KEY".

Well, thanks anyways. Everything is very helpful and its a great tutorial. I did an amazing job and very fast by answering any issues. :)

@daluzluiz Thank you for your patience and good nature as we diagnosed the problem. You've shown me that I need to improve the tutorial to better explain the use of the "example.com" users as well as providing troubleshooting tips for problems with the Stripe keys. Please note that I've just pushed a new version of the tutorial a few minutes ago so you should work from the new version.

@tmock12 Thanks for stepping in again like a champ with useful suggestions. Your tests make it much easier to troubleshoot!

@daluzluiz for my information, about how long did it take for you to work through the tutorial and set up the application?

Went and watched some TV but I had a feeling thats what was happening. local keys were failing but the javascript stripe stuff was passing.

People seem to have trouble with setting their environment config keys. I have an idea on making that step easier for users Daniel, I'll push them up to a branch this weekend and have you take a look.

I'll also see if I can come up with a solution for the seeds file as well. If you have any thoughts feel free to shoot me an email.

To be honest with you, I read some tutorials for the past month (I'm a designer, trying to code) and on this one I wanted to do something fast. I was going to go through the tutorial because it's much better that way as you know what does what sort of thing, but I was getting some errors setting up the application and decided to clone it and followed every step to make sure I understood everything. I took 20-30min to get it to run.

It's very helpful and detailed, and you can get it fairly quick.

@daluzluiz You are running with the big dogs now :-) This application requires at least "intermediate" Rails, JavaScript, and Unix skills. I'm glad you got this far and we welcome you to the Rails community. I'll urge you to take time to read Michael Hartl's "Rails Tutorial" book before you dive any deeper.

@tmock12 I'll look forward to seeing what you cook up.

Thank you, I did read his tutorial and it's fantastic. I'll now try to implement this app to fit my needs. I'm sure you'll see me around asking some more questions. :)

Thank you very much for your help.