Ruby on Rails - Submitting Email Form Newsletter to Mailchimp

646 views Asked by At

I am trying to submit an email that goes into my Mailchimp List that I have created. The thing is that when I click subscribe in my production environment, I get a 200 OK message in my console:

[ee0cda43-9651-4c7e-9499-ac499094d8b6] Started POST "/subscribe" for 127.0.0.1 at 2017-08-26 02:52:00 -0700
[ee0cda43-9651-4c7e-9499-ac499094d8b6] Processing by SubscriptionsController#subscribe as JSON
[ee0cda43-9651-4c7e-9499-ac499094d8b6]   Parameters: {"email"=>"[email protected]"}
[ee0cda43-9651-4c7e-9499-ac499094d8b6] Completed 200 OK in 2ms (Views: 0.4ms)

But when I check in my list, the e-mail does not appear in my contact list.

By the way, I am using Ruby 2.3.1, Rails 5.1.2 and Figaro 1.1.1 for ENV

This is how I have it in my home.html.erb:

<div class="subscribe">
    <div class="row">
      <div class="col-lg-12">
        <h4>Sign up for our Newsletter</h4>
        <div class="row small-uncollapse large-collapse">
          <div class="col-lg-11">
            <input id="email" placeholder="Your Email" type="text">/</input>
          </div>
          <div class="col-lg-1">
            <button class=".btn-primary" id="subscribe">Subscribe</button>
          </div>
        </div>
      </div>
    </div>
  </div>

routes.rb:

get 'subscriptions/subscribe'
post :subscribe, controller: :subscriptions, action: :subscribe

Using Gibbon for API connection with Mailchimp:

Gibbon::Request.api_key = ENV["MAILCHIMP_API_KEY"]
Gibbon::Request.timeout = 15
Gibbon::Request.open_timeout = 15
Gibbon::Request.symbolize_keys = true
Gibbon::Request.debug = false
puts "MailChimp API key: #{Gibbon::Request.api_key}" # temporary

And JS script with AJAX integrated into application.js:

$(document).ready(function () {
    $('#subscribe').click(function () {
        var email = $('#email').val();
        $.ajax({
            url: '/subscribe',
            type: 'post',
            dataType: 'json',
            data: {email: email}
        })
        .done(function (data) {
            $('.subscribe').html('<strong>' + data.message + '</strong>');
        });

    });
});

Am I missing something? Would appreciate any suggestion.

----UPDATE----

Subscription Controller:

class SubscriptionsController < ApplicationController
  def subscribe
    email = params[:email]
    gb = Gibbon::Request.new
    gb.lists.subscribe({:id => ENV["MAILCHIMP_LIST_ID"],
                        :email => {email: email}, :double_optin => false})
    render json: {message: "You are signed (#{email}) and good to go! Check your e-mail. Thank You!"}
  end
end

----UPDATE 2----

class SubscriptionsController < ApplicationController
  def subscribe
    email_address = params[:email_address]
    gb = Gibbon::Request.new
    gb.lists(ENV["MAILCHIMP_LIST_ID"]).members.create(body: {email_address: "email", status: "subscribed"})
    render json: {message: "You are signed (#{email_address}) and good to go! Check your e-mail. Thank You!"}
  end
end

Updated data in application.js:

data: {email_address: email}

Error Log:

[a6e21ee4-b955-4453-a1e0-56ff8035faee] Started POST "/subscribe" for 127.0.0.1 at 2017-08-27 04:25:33 -0700
[a6e21ee4-b955-4453-a1e0-56ff8035faee] Processing by SubscriptionsController#subscribe as JSON
[a6e21ee4-b955-4453-a1e0-56ff8035faee]   Parameters: {"email"=>"[email protected]"}
[a6e21ee4-b955-4453-a1e0-56ff8035faee] Completed 500 Internal Server Error in 956ms
[a6e21ee4-b955-4453-a1e0-56ff8035faee]   
[a6e21ee4-b955-4453-a1e0-56ff8035faee] Gibbon::MailChimpError (the server responded with status 400 @title="Invalid Resource", @detail="Please provide a valid email address.", @body={:type=>"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/", :title=>"Invalid Resource", :status=>400, :detail=>"Please provide a valid email address.", :instance=>""}, @raw_body="{\"type\":\"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/\",\"title\":\"Invalid Resource\",\"status\":400,\"detail\":\"Please provide a valid email address.\",\"instance\":\"\"}", @status_code=400):
[a6e21ee4-b955-4453-a1e0-56ff8035faee]   
[a6e21ee4-b955-4453-a1e0-56ff8035faee] app/controllers/subscriptions_controller.rb:8:in `subscribe'
1

There are 1 answers

0
maxshelley On BEST ANSWER

Based on your updates, I think you're close, but I think:

body: {email_address: "email", status: "subscribed"}

should be:

body: {email_address: email_address, status: "subscribed"}

For some context, I grabbed some code where we use Gibbon's upsert method:

    Gibbon::Request.lists(@subscriber.mailing_list_info.list_id)
    .members(Digest::MD5.hexdigest(@subscriber.email))
    .upsert(
      body: {
        status_if_new: 'subscribed',
        email_address: @subscriber.email,
        merge_fields: @subscriber.mailing_list_info.merge_vars })

From what I remember, this will either update the member if they exist, or add them if they don't.

@subscriber and @subscriber.mailing_list_info are objects we used to wrap our User and add relevant Mailchimp information.