Send bulk Email with mailchimp - ruby-on-rails

I need to send promotional email and fetch there corresponding stats.Currently i am using Gibbon Gem but not able to create campaign through .Is there any way to create campaign and add bulk email in receiver
through Gibbon Gem or there is any other Gem to work for same.I need all stat of a campaign like sent ,bounced, effective email.Which version Of Gibbon Gem should i use to create campaign and contact list through Api

Gibbon does allow you to create and trigger campaigns through the Mailchimp API v3. You have to use Gibbon version >= 2.1.3 to send campaigns, because there was a bug in the earlier versions.
Gibbon's readme file was recently updated with examples.
To create a campaign:
recipients = {
list_id: list_id,
segment_opts: {
saved_segment_id: segment_id
}
}
settings = {
subject_line: "Subject Line",
title: "Name of Campaign",
from_name: "From Name",
reply_to: "my#email.com"
}
body = {
type: "regular",
recipients: recipients,
settings: settings
}
begin
gibbon.campaigns.create(body: body)
rescue Gibbon::MailChimpError => e
puts "Houston, we have a problem: #{e.message} - #{e.raw_body}"
end
To send a campaign:
gibbon.campaigns(campaign_id).actions.send.create
To get stats:
email_stats = gibbon.reports(campaign_id).retrieve["opens"]

Related

how to send email to user after purchase on STRIPE with ruby ​on rails

I would like to know how to send an email to the user after successful checkout
My Webhook controller:
class WebhooksController < ApplicationController
skip_before_action :verify_authenticity_token
def create
payload = request.body.read
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
event = nil
begin
event = Stripe::Webhook.construct_event(
payload, sig_header, Rails.application.credentials[:stripe][:webhook]
)
rescue JSON::ParserError => e
status 400
return
rescue Stripe::SignatureVerificationError => e
# Invalid signature
puts "Signature error"
return
end
# Handle the event
case event.type
when 'checkout.session.completed'
session = event.data.object
session_with_expand = Stripe::Checkout::Session.retrieve({id: session.id, expand: ["line_items"] })
session_with_expand.line_items.data.each do |line_item|
product = Product.find_by(stripe_product_id: line_item.price.product)
product.increment!(:sales_count)
end
end
render json: { message: 'success' }
end
end
If you are creating the payment intent with the Ruby SDK you can add the receipt_email field to add a customers email.(see ther Stripe PaymentIntent docs)
Stripe.api_key = 'API_KEY'
intent = Stripe::PaymentIntent.create({
amount: 1099,
currency: 'cad',
payment_method_types: ['card'],
receipt_email: 'jenny.rosen#example.com',
})
If you are creating the checkout session server side you can preconfigure the properties/settings like for the checkout page per the Stripe Checkout Docs
require 'stripe'
Stripe.api_key ='API_KEY'
Stripe::Checkout::Session.create({
success_url: 'https://example.com/success',
cancel_url: 'https://example.com/cancel',
customer_email:'email',
line_items: [
{price: 'price_H5ggYwtDq4fbrJ', quantity: 2},
],
mode: 'payment',
})
This is the note on the customer email field per Stripe docs :
If provided, this value will be used when the Customer object is
created. If not provided, customers will be asked to enter their email
address. Use this parameter to prefill customer data if you already
have an email on file. To access information about the customer once a
session is complete, use the customer field.

adding tag on mailchimp via api replies success but no tags are added

Here's my method to add tags to an existing Mailchimp subscriber:
def self.add_tag_on_mailchimp(email,tag)
begin
mailchimp = MailchimpMarketing::Client.new
mailchimp.set_config({
:api_key => Rails.configuration.mailchimp_api_key,
:server => "us2"
})
lower_case_md5_hashed_email_address = Digest::MD5.hexdigest(email.downcase)
response = mailchimp.lists.update_list_member_tags(
'6181dc4fdc', lower_case_md5_hashed_email_address,{
body: {
tags: [
{
name: tag,
status: "active"
}
]
}
})
p "reply from mailchimp: #{response}"
p "added #{tag} tag"
rescue MailchimpMarketing::ApiError => e
puts "Error: #{e}. trying to create"
end
end
The call returns "success" if the email exists, but the tags aren't added at all. I tried sending tags that existed or not on Mailchimp, and I always get success, but there are no tags on Mailchimp.
What am I missing?
Thanks
the mailchimp-marketing gem is buggy. I switched to the gibbons gem and it's all good.

STRIPE : This customer has no attached payment source or default payment method. RUBY ON RAILS

I've got some issues, i'm trying to implement subscription with stripe > it works when there is for exemple 3 items in my order > it create a subscription for the 3 items.
The problem is that if the customer wants to stop sub only for ONE element, i dont know how to handle this ...
So i was wondering to create a subscription for each element, this is my code
customer = Stripe::Customer.create
#order.line_items.each do |line_item|
product = Stripe::Product.create(
{
name: line_item.product.name,
metadata: {
product_id: line_item.product.id,
line_item_id: line_item.id
}
}
)
price = Stripe::Price.create(
{
product: product.id,
unit_amount: line_item.product.price_cents,
currency: 'eur',
recurring: {
interval: 'month'
}
}
)
Stripe::Subscription.create({
customer: customer.id,
items: [
{price: price.id, quantity: line_item.quantity}
]
})
but i got this error This customer has no attached payment source or default payment method.
and i dont know how to attach it, even with documentation..
any help please ? thank you
As said in comments; To fix the error in the title:
You need to first have the "payment method", if you haven't already, create one:
Maybe using Stripe.js and it's elements API.
Which nowadays has "payment" element, allowing users to choose their payment-method.
And supports Setup-Intent's "client_secret" (beside Payment-Intent's), submittable using confirmSetup(...) method.
Then (using Stripe API):
Attach said "payment method" to the Customer:
(Optionally) set it as their default for invoices (with invoice_settings.default_payment_method).
And, while creating the subscription, pass the customer (that which you atteched said "payment method" to).

Mailchimp does not forget about unsubscribed users

I'm having a problem when it comes to unsubrscibe email from my mailchimp list.
Basically I have a user with an email. When the user subscribe to my service I automatically insert his email into my mailchimp list through the gem gibbon (the server is Ruby on Rails v2.2.3)
##gibbon = Gibbon::Request.new(api_key: ENV['MAILCHIMP_API_KEY'])
##list = 'list_id'
...
##gibbon.lists(##list).members.create(body: {email_address: email, status: "subscribed", merge_fields: {FNAME: first_name, LNAME: full_name}})
After creating the account the user can obviously change his email address. If he does so, I add the new email to the mailchimp list and I delete the old one:
begin
##gibbon.lists(##list).members.create(body: {email_address: email, status: "subscribed", merge_fields: {FNAME: first_name, LNAME: full_name}})
rescue => e
render :json => {
:error => true,
:message => "Email already present",
:user => u,
:personal_link => u.current_link
}
return
end
member = ##mailchimp.lists(##list).members(u.email)
member.update status: "unsubscribed"
This works fine in most cases.
The problem comes when I try to change my email with my old one:
0) Subscribe to the website with the email "test#gmail.com"
Works fine.
1) From my account I change my email from "test#gmail.com" to "test1#gmail.com"
Works fine, I don't see anymore my old email in the mailchimp list and I see the new one.
2) Change back my email from "test1#gmail.com" to "test#gmail.com"
Mailchimp throws this error:
#<Gibbon::MailChimpError: the server responded with status 400 #title="Member Exists", #detail="test#gmail.com is already a list member.
The problem is that I don't have any user with this email in the database and I don' have any user with that email in my mailchimp list.
It' like mailchimp does not forget about unsubribed user and prevents me to add the same user twice in a list, even if it has been cancelled before.
How can I solve the problem?
I solved the problem. Basically for mailchimp a "unsubscribed" user is not a deleted user, so you can subscribe two users with the same email even if their state is different.
Instead of changing their status to "unsubscribed" I deleted them:
email_hash = Digest::MD5.hexdigest(u.email).downcase
##gibbon.lists(##list).members(email_hash).delete

Actionmailer - Sparkpost template and multilanguage

It's my first time setting up mails in a rails project.
I was told to use SparkPost and to create templates for different languages for several actions.
For simplicity lets say a user_signed_up(user) mail.
Currently I have this setup working:
Gem installed: 'sparkpost'
mail.rb
ActionMailer::Base.smtp_settings = {
address: "smtp.sparkpostmail.com",
port: 587,
enable_starttls_auto: true,
user_name: "SMTP_Injection",
password: SPARKPOST_API_KEY,
domain: 'foo-bar.com'
}
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.default charset: "utf-8"
application_mailer.rb
require 'sparkpost'
class ApplicationMailer < ActionMailer::Base
default from: "Seal Notification <noreply#foobar.com>"
layout 'mailer'
end
signup_mailer.rb
class SignupMailer < ApplicationMailer
def user_signed_up(user)
receiver = user.email
sender = 'myself#test.com'
title = 'Thanks for registering'
body = 'This is a test body'
sparky = SparkPost::Client.new(SPARKPOST_API_KEY)
sparky.transmission.send_message(receiver,sender,title,body)
end
end
And I can successfully send emails.
Although, this is definitely not scaleable due to multi language and body not style-able.
Now I need to setup templates to allow non-technical people to adjust email templates.
But here is where I am stuck and an answer to following questions would help me tremendously:
1) How can I send specific email templates?
2) How do I pass variables to these templates?
3) How do I handle multiple language support?
Thank you.
Here's an intro article on creating templates in SparkPost.
Here's one on previewing your templates and sending test messages - including how variables work (aka 'substitution data').
Long form Ruby-centric answers follow:
A couple of observations on your code first: It looks like you are both configuring SMTP globally but using the REST API in your signup mailer. I'd recommend the REST API over SMTP since it has the templating and other rich capabilities you require.
1) You can manage email templates either the SparkPost UI here or directly by API call as documented here. The template syntax is documented here.
Once you have a created and published a template, you can send using the SparkPost client like this (assuming your template ID is 'your-template-en'):
require 'sparkpost'
host = 'https://api.sparkpost.com'
SparkPost::Request.request("#{host}/api/v1/transmissions", API_KEY, {
recipients: [
{ address: { email: 'recipient#example.com' } }
],
content: {
template_id: 'your-template-en'
}
})
2) SparkPost supports message-level and recipient-level 'substitution_data' which are JSON-formatted variables for use in your templates. Here's a sample transmission request:
SparkPost::Request.request("#{host}/api/v1/transmissions", API_KEY, {
recipients: [
{
address: { email: 'recipient#example.com' },
substitution_data: {
first_name: 'Recip',
favorites: {
color: 'Orange',
ice_cream: 'Vanilla'
}
}
}
],
content: {
template_id: 'your-template-en'
},
substitution_data: {
title: 'Daily News'
}
})
You now use substitution data in your templates. For example:
<h1>{{title}}</h1>
<p>Hi {{first_name or 'there'}}</p>
<p>This {{favorites.color}} bulletin is all about {{favorites.ice_cream}} ice cream</p>
Note: recipient substitution data takes precedence over message-level fields.
3) For the multi-lingual use case, you might consider creating a template per language as many of our other customers do.
Incidentally, this looks like several questions - should we consider splitting them up?

Resources