-
-
Notifications
You must be signed in to change notification settings - Fork 199
Replace Mailchimp with a Flodesk integration #2162
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
gnclmorais
merged 1 commit into
codebar:master
from
gnclmorais:me-from-mailchimp-to-flowdesk
Feb 26, 2025
+371
−141
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,31 @@ | ||
- content_for :head do | ||
:javascript | ||
(function(w, d, t, h, s, n) { | ||
w.FlodeskObject = n; | ||
var fn = function() { | ||
(w[n].q = w[n].q || []).push(arguments); | ||
}; | ||
w[n] = w[n] || fn; | ||
var f = d.getElementsByTagName(t)[0]; | ||
var v = '?v=' + Math.floor(new Date().getTime() / (120 * 1000)) * 60; | ||
var sm = d.createElement(t); | ||
sm.async = true; | ||
sm.type = 'module'; | ||
sm.src = h + s + '.mjs' + v; | ||
f.parentNode.insertBefore(sm, f); | ||
var sn = d.createElement(t); | ||
sn.async = true; | ||
sn.noModule = true; | ||
sn.src = h + s + '.js' + v; | ||
f.parentNode.insertBefore(sn, f); | ||
})(window, document, 'script', 'https://assets.flodesk.com', '/universal', 'fd'); | ||
|
||
.row.justify-content-md-center | ||
.col-md-8 | ||
%h2= t('homepage.newsletter.title') | ||
%p= t('homepage.newsletter.description') | ||
|
||
-# Mailchimp Signup Form | ||
#mc_embed_signup | ||
%form.validate#mc-embedded-subscribe-form{ action: "https://codebar.us8.list-manage.com/subscribe/post?u=b4652d85b385945c79f2ffa2e&id=3798974cb3", | ||
method: "post", | ||
name: "mc-embedded-subscribe-form", | ||
target: "_blank", | ||
novalidate: true } | ||
#mc_embed_signup_scroll | ||
#indicates-required | ||
.mc-field-group.mb-3 | ||
.d-flex.justify-content-between | ||
%label.form-label{ for: "mce-EMAIL" } | ||
Email Address | ||
%span.asterisk * | ||
%small | ||
%span.asterisk * indicates required | ||
%input.required.email.form-control#mce-EMAIL{ type: 'email', value: '', name: 'EMAIL' } | ||
.clear#mce-responses | ||
.response#mce-error-response{ style: 'display:none' } | ||
.response#mce-success-response{ style: 'display:none' } | ||
-# real people should not fill this in and expect good things - do not remove this or risk form bot signups | ||
%div{ style: 'position: absolute; left: -5000px;', 'aria-hidden': 'true' } | ||
%input{ type: 'text', name: 'b_b4652d85b385945c79f2ffa2e_3798974cb3', tabindex: '-1', value: '' } | ||
.d-flex.justify-content-between.align-items-center | ||
%input.btn.btn-primary#mc-embedded-subscribe{ type: 'submit', value: 'Subscribe', name: 'subscribe' } | ||
-# Flodesk signup form | ||
#fd-form-67b7415796213859df0a8a86 | ||
:javascript | ||
if (window.fd) window.fd('form', { | ||
formId: '67b7415796213859df0a8a86', | ||
containerEl: '#fd-form-67b7415796213859df0a8a86' | ||
}); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
require 'services/flodesk' | ||
|
||
key = Rails.env.test? ? 'test' : ENV['FLODESK_KEY'] | ||
Rails.logger.warn 'Missing FLODESK_KEY environment variable' unless key | ||
|
||
# We use Flodesk for newsletter sending, so we need both values | ||
Rails.logger.warn 'Missing NEWSLETTER_ID environment variable' unless ENV['NEWSLETTER_ID'] | ||
|
||
Flodesk::Client.api_key = key | ||
Flodesk::Client.complete_timeout = 15 | ||
Flodesk::Client.open_timeout = 15 |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
require 'faraday' | ||
|
||
module Flodesk | ||
# Subscriber status | ||
ACTIVE = 'active'.freeze | ||
|
||
class Client | ||
API_ENDPOINT = 'https://api.flodesk.com/v1/'.freeze | ||
DEFAULT_TIMEOUT = 60 | ||
|
||
class_attribute :api_key | ||
class_attribute :complete_timeout | ||
class_attribute :open_timeout | ||
|
||
# Allows for setting these values in `config/initializers/flodesk.rb` | ||
class << self | ||
def api_key | ||
@@api_key | ||
end | ||
|
||
def complete_timeout | ||
@@complete_timeout | ||
end | ||
|
||
def open_timeout | ||
@@open_timeout | ||
end | ||
end | ||
|
||
attr_accessor :api_endpoint, :debug, :logger | ||
|
||
# We need 3 actions: | ||
# | ||
# 1. subscribe --> params(list_id, email, first_name, last_name) | ||
# Documentation: https://developers.flodesk.com/#tag/subscriber/operation/createOrUpdateSubscriber | ||
# Endpoint: https://api.flodesk.com/v1/subscribers | ||
# | ||
# 2. unsubscribe --> params(list_id, email) | ||
# Documentation: https://developers.flodesk.com/#tag/subscriber/operation/removeSubscriberFromSegments | ||
# Endpoint: https://api.flodesk.com/v1/subscribers/{id_or_email}/segments | ||
# | ||
# 3. subscribed? --> params(list_id, email) | ||
# Documentation: https://developers.flodesk.com/#tag/subscriber/operation/retrieveSubscriber | ||
# Endpoint: https://api.flodesk.com/v1/subscribers/{id_or_email} | ||
|
||
def initialize(api_key: nil, complete_timeout: nil, open_timeout: nil) | ||
@api_key = api_key || self.class.api_key || ENV['FLODESK_KEY'] | ||
@api_key = @api_key.strip if @api_key | ||
|
||
@complete_timeout = complete_timeout || self.class.complete_timeout || DEFAULT_TIMEOUT | ||
@open_timeout = open_timeout || self.class.open_timeout || DEFAULT_TIMEOUT | ||
end | ||
|
||
def disabled? | ||
!@api_key | ||
end | ||
|
||
def subscribe(email:, first_name:, last_name:, segment_ids:, double_optin: true) | ||
body = { email:, first_name:, last_name:, segment_ids:, double_optin: } | ||
|
||
request(:post, 'subscribers', body) | ||
end | ||
|
||
def unsubscribe(email:, segment_ids:) | ||
body = { segment_ids: } | ||
|
||
request(:delete, "subscribers/#{email}/segments", body) | ||
end | ||
|
||
def subscribed?(email:, segment_ids:) | ||
response = request(:get, "subscribers/#{email}") | ||
response => { status:, body: } | ||
|
||
return false if response.is_a?(FlodeskError) && status == 404 | ||
|
||
body.symbolize_keys => { status:, segments: } | ||
|
||
# If not subscribed, stop here | ||
is_active = status.to_s.eql?(ACTIVE) | ||
return false unless is_active | ||
|
||
segment_ids.all? do |segment_id| | ||
segments.any? { |segment| segment_id.to_s.eql?(segment.symbolize_keys[:id]) } | ||
end | ||
end | ||
|
||
private | ||
|
||
def connection | ||
options = { | ||
headers: { | ||
user_agent: 'codebar (codebar.io)' | ||
}, | ||
request: { | ||
timeout: @complete_timeout, | ||
open_timeout: @open_timeout | ||
} | ||
} | ||
|
||
# https://lostisland.github.io/faraday/#/customization/request-options | ||
@connection ||= Faraday.new(url: API_ENDPOINT, **options) do |config| | ||
config.request :json | ||
|
||
# Beware: the order of these lines matter. Examples: | ||
# - https://mattbrictson.com/blog/advanced-http-techniques-in-ruby#pitfall-raise_error-and-logger-in-the-wrong-order | ||
# - https://stackoverflow.com/a/67182791/590525 | ||
config.response :raise_error | ||
config.response :logger, Rails.logger, headers: true, bodies: true, log_level: :debug | ||
config.response :json | ||
|
||
# https://developers.flodesk.com/#section/Authentication/api_key | ||
config.request :authorization, 'Basic', -> { @api_key } | ||
end | ||
end | ||
|
||
def request(http_method, endpoint, body = {}) | ||
# Faraday's `delete` does not accept body at the time of writing | ||
response = if http_method == :delete | ||
connection.run_request(http_method, endpoint, body, nil) | ||
else | ||
connection.public_send(http_method, endpoint, body) | ||
end | ||
|
||
{ | ||
status: response.status, | ||
body: response.body | ||
} | ||
rescue Faraday::Error => e | ||
FlodeskError.new(e.response_body['message'], { | ||
raw_body: e.response_body, | ||
status_code: e.response_status | ||
}) | ||
end | ||
end | ||
|
||
# Inspired by https://github.com/amro/gibbon/blob/master/lib/gibbon/mailchimp_error.rb | ||
class FlodeskError < StandardError | ||
attr_reader :status_code, :raw_body | ||
|
||
def initialize(message = '', params = {}) | ||
@status_code = params[:status_code] | ||
@raw_body = params[:raw_body] | ||
|
||
super(message) | ||
end | ||
|
||
def to_s | ||
"#{super} #{instance_variables_to_s}" | ||
end | ||
|
||
private | ||
|
||
def instance_variables_to_s | ||
%i[status_code raw_body].map do |attr| | ||
attr_value = send(attr) | ||
|
||
"@#{attr}=#{attr_value.inspect}" | ||
end.join(', ') | ||
end | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,67 +1,39 @@ | ||
class MailingList | ||
SUBSCRIBED = 'subscribed'.freeze | ||
MEMBER_EXISTS = 'Member Exists'.freeze | ||
|
||
attr_reader :list_id | ||
|
||
def initialize(list_id) | ||
@list_id = list_id | ||
end | ||
|
||
def subscribe(email, first_name, last_name) | ||
return if disabled? | ||
return if client.disabled? | ||
|
||
begin | ||
client.lists(list_id).members | ||
.create(body: { email_address: email, | ||
status: 'subscribed', | ||
merge_fields: { FNAME: first_name, LNAME: last_name } }) | ||
rescue Gibbon::MailChimpError => e | ||
reactivate_subscription(email, first_name, last_name) if e.title.eql?(MEMBER_EXISTS) | ||
end | ||
client.subscribe(email:, first_name:, last_name:, segment_ids: [@list_id]) | ||
rescue Flodesk::FlodeskError | ||
false | ||
end | ||
handle_asynchronously :subscribe | ||
|
||
def unsubscribe(email) | ||
return if disabled? | ||
return if client.disabled? | ||
|
||
client.lists(list_id).members(md5_hashed_email_address(email)) | ||
.update(body: { status: 'unsubscribed' }) | ||
rescue Gibbon::MailChimpError | ||
client.unsubscribe(email:, segment_ids: [@list_id]) | ||
rescue Flodesk::FlodeskError | ||
false | ||
end | ||
handle_asynchronously :unsubscribe | ||
|
||
def reactivate_subscription(email, first_name, last_name) | ||
return if disabled? | ||
|
||
client.lists(list_id).members(md5_hashed_email_address(email)) | ||
.upsert(body: { email_address: email, | ||
status: 'subscribed', | ||
merge_fields: { FNAME: first_name, LNAME: last_name } }) | ||
end | ||
|
||
def subscribed?(email) | ||
return if disabled? | ||
return if client.disabled? | ||
|
||
info = client.lists(list_id).members(md5_hashed_email_address(email)).retrieve | ||
info.body[:status].eql?(SUBSCRIBED) | ||
rescue Gibbon::MailChimpError | ||
client.subscribed?(email:, segment_ids: [@list_id]) | ||
rescue Flodesk::FlodeskError | ||
false | ||
end | ||
|
||
private | ||
|
||
def client | ||
@client ||= Gibbon::Request.new | ||
end | ||
|
||
def md5_hashed_email_address(email) | ||
require 'digest' | ||
Digest::MD5.hexdigest(email.downcase) | ||
end | ||
|
||
def disabled? | ||
!ENV['MAILCHIMP_KEY'] | ||
@client ||= Flodesk::Client.new | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
require 'spec_helper' | ||
require 'json' | ||
require 'services/flodesk' | ||
|
||
RSpec.describe Flodesk do | ||
let(:stub) { Faraday::Adapter::Test::Stubs.new } | ||
let(:conn) { Faraday.new { |b| b.adapter(:test, stub) } } | ||
let(:client) { Flodesk::Client.new } | ||
|
||
before do | ||
allow(ENV).to receive(:[]).and_call_original | ||
allow(ENV).to receive(:[]).with('FLODESK_KEY').and_return('test') | ||
allow(Rails).to receive(:env).and_return('production'.inquiry) | ||
|
||
allow(client).to receive(:connection).and_return(conn) | ||
|
||
stub.strict_mode = true | ||
end | ||
|
||
context '#subscribe' do | ||
it 'adds a user to segments' do | ||
payload = { | ||
email: :email, | ||
first_name: :first_name, | ||
last_name: :last_name, | ||
segment_ids: [:segment_id], | ||
double_optin: true, | ||
} | ||
|
||
check = ->(request_body) { request_body == payload } | ||
stub.post('/subscribers', check) { [200, {}, '{}'] } | ||
|
||
client.subscribe(**payload) | ||
|
||
stub.verify_stubbed_calls | ||
end | ||
end | ||
|
||
context '#unsubscribe' do | ||
it 'removes a user from segments' do | ||
payload = { | ||
email: :email, | ||
segment_ids: [:segment_id], | ||
} | ||
|
||
check = ->(request_body) do | ||
request_body == payload.slice(:segment_ids) | ||
end | ||
|
||
# Faraday's `stub.delete` does not accept body at the time of writing | ||
stub.send(:new_stub, :delete, "/subscribers/#{payload[:email]}/segments", {}, check) { [200, {}, '{}'] } | ||
|
||
client.unsubscribe(**payload) | ||
|
||
stub.verify_stubbed_calls | ||
end | ||
end | ||
|
||
context '#subscribed?' do | ||
it 'confirms that a user is active and subscribed to a segment' do | ||
payload = { | ||
email: :email, | ||
segment_ids: ["segment_id"], | ||
} | ||
|
||
stub.get("/subscribers/#{payload[:email]}") { [200, {}, { | ||
"id": "123456789", | ||
"status": "active", | ||
"email": "email", | ||
"segments": [ | ||
{ | ||
"id": "segment_id", | ||
"name": "codebar" | ||
} | ||
] | ||
}] } | ||
|
||
expect(client.subscribed?(**payload)).to be true | ||
|
||
stub.verify_stubbed_calls | ||
end | ||
|
||
it 'confirms that a user is active but not subscribed to a segment' do | ||
payload = { | ||
email: :email, | ||
segment_ids: ["segment_id"], | ||
} | ||
|
||
stub.get("/subscribers/#{payload[:email]}") { [200, {}, { | ||
"id": "123456789", | ||
"status": "active", | ||
"email": "email", | ||
"segments": [ | ||
{ | ||
"id": "some_other_segment_id", | ||
"name": "not codebar" | ||
} | ||
] | ||
}] } | ||
|
||
expect(client.subscribed?(**payload)).to be false | ||
|
||
stub.verify_stubbed_calls | ||
end | ||
|
||
it 'confirms that a user is not active' do | ||
payload = { | ||
email: :email, | ||
segment_ids: ["segment_id"], | ||
} | ||
|
||
stub.get("/subscribers/#{payload[:email]}") { [200, {}, { | ||
"id": "123456789", | ||
"status": "unsubscribed", | ||
"email": "email", | ||
"segments": [ | ||
{ | ||
"id": "segment_id", | ||
"name": "codebar" | ||
} | ||
] | ||
}] } | ||
|
||
expect(client.subscribed?(**payload)).to be false | ||
|
||
stub.verify_stubbed_calls | ||
end | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,82 +1,49 @@ | ||
require 'spec_helper' | ||
require 'json' | ||
require 'services/mailing_list' | ||
|
||
RSpec.describe MailingList do | ||
let(:client) { double(:gibbon, lists: lists) } | ||
let(:mailing_list) { MailingList.new(:list_id) } | ||
let(:lists) { double(:lists, members: members) } | ||
let(:members) { double(:members) } | ||
let(:client) { double(:flodesk) } | ||
|
||
before do | ||
allow(client).to receive(:disabled?).and_return(false) | ||
|
||
allow(ENV).to receive(:[]).and_call_original | ||
allow(ENV).to receive(:[]).with('MAILCHIMP_KEY').and_return('test') | ||
allow(ENV).to receive(:[]).with('FLODESK_KEY').and_return('test') | ||
allow(mailing_list).to receive(:client).and_return(client) | ||
allow(Rails).to receive(:env).and_return("production".inquiry) | ||
end | ||
|
||
context '#subscribe' do | ||
it 'adds a user to the mailing list' do | ||
expect(members).to receive(:create) | ||
.with(body: { email_address: :email, | ||
status: "subscribed", | ||
merge_fields: { FNAME: :first_name, LNAME: :last_name } }) | ||
expect(client).to receive(:subscribe) | ||
.with({ | ||
email: :email, | ||
first_name: :first_name, | ||
last_name: :last_name, | ||
segment_ids: [:list_id] | ||
}) | ||
|
||
mailing_list.subscribe(:email, :first_name, :last_name) | ||
end | ||
|
||
it 'updates the subscription of existing mailing list contacts' do | ||
email = 'test@email.com' | ||
|
||
allow(members).to receive(:create) | ||
.and_raise(Gibbon::MailChimpError.new('Error', | ||
{ status_code: 400, | ||
title: MailingList::MEMBER_EXISTS })) | ||
|
||
expect(Digest::MD5).to receive(:hexdigest).with(email) | ||
expect(members).to receive(:upsert) | ||
.with(body: { email_address: email, | ||
status: "subscribed", | ||
merge_fields: { FNAME: :first_name, LNAME: :last_name } }) | ||
|
||
mailing_list.subscribe(email, :first_name, :last_name) | ||
end | ||
end | ||
|
||
context '#reactivate_subscription' do | ||
it 'updates an existing inactive subscription' do | ||
email = 'test@email.com' | ||
|
||
expect(Digest::MD5).to receive(:hexdigest).with(email) | ||
expect(members).to receive(:upsert) | ||
.with(body: { email_address: email, | ||
status: "subscribed", | ||
merge_fields: { FNAME: :first_name, LNAME: :last_name } }) | ||
|
||
mailing_list.reactivate_subscription(email, :first_name, :last_name) | ||
end | ||
end | ||
|
||
context '#unsubscribe' do | ||
it 'removes a user from the mailing list' do | ||
email = 'test@email.com' | ||
expect(client).to receive(:unsubscribe) | ||
.with({ email: :email, segment_ids: [:list_id] }) | ||
|
||
expect(Digest::MD5).to receive(:hexdigest).with(email) | ||
expect(members).to receive(:update) | ||
.with(body: { status: "unsubscribed" }) | ||
|
||
mailing_list.unsubscribe(email) | ||
mailing_list.unsubscribe(:email) | ||
end | ||
end | ||
|
||
context '#subscribed?' do | ||
it 'checks if a user is already subscribed to the mailing list' do | ||
email = 'test@email.com' | ||
info = double(:info, body: { status: MailingList::SUBSCRIBED }) | ||
|
||
expect(Digest::MD5).to receive(:hexdigest).with(email) | ||
expect(members).to receive(:retrieve).and_return(info) | ||
|
||
expect(mailing_list.subscribed?(email)).to be true | ||
expect(client).to receive(:subscribed?) | ||
.with({ email: :email, segment_ids: [:list_id] }) | ||
.and_return(true) | ||
expect(mailing_list.subscribed?(:email)).to be true | ||
end | ||
end | ||
end |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.