Mailchimp API v3 create list REST Client Ruby - ruby-on-rails

I'm trying to create a Mailchimp list using Mailchimps API (v3) and the REST Client gem. I've got this working correctly for retrieving list names and ids. However, I'm getting a 401 Unauthorized - API Key Missing response for the creation of a list. I think my post request is malformed but I'm having trouble indentifying where I'm going wrong. My code looks like this:
params_hash = {
name: "#{territory}",
contact: {
company: "Company",
address1: "Address",
city: "City",
state: "State",
zip: "0000",
country: "US"
},
permission_reminder: "You are receiving this email because....",
campaign_defaults: {
from_name: "From Name",
from_email: "contact#contact.com",
subject: "Subject",
language: "en"
},
notify_on_subscribe: "contact1#contact.com",
notify_on_unsubscribe: "contact1#contact.com",
email_type_option: true,
apikey: mailchimp_key
}
RestClient.post("#{mailchimp_url}/lists", { params: params_hash }) { |response, request, result, &block|
}

You should not pass your API key in the payload, instead, you should use HTTP Basic Authentication. RestClient does support this, but it's kind of awkward. If you want to use the RestClient shortcuts, you can modify your URL to include the username/password, like this: https://username:api_key#us1.api.mailchimp.com -- username doesn't matter to MailChimp, but it's required for Basic Auth, so you can pass anything.
Alternately, you can use RestClient's Request class directly, making your request something like this instead:
RestClient::Request.execute(method: :post, url: "#{mailchimp_url}/lists", payload: params_hash, user: 'anything', password: mailchimp_key)
But, honestly? RestClient is not great. I prefer HTTParty, which allows you to create very lightweight wrappers with lots of defaults set for you, OR use it like RestClient, but with a more friendly API:
HTTParty.post("#{mailchimp_url}/lists", body: params_hash, basic_auth: {username: 'whatever', password: mailchimp_key})

Related

How to send a POST request with after create or update of a user (RAILS)

This is my first time working with Requests and i'm a little confused, any guidance would be greatly appreciated.
Task: after a user is created i would like to send that user's information (name, email, etc) to another site that we are integrating with. The goal is when a user leaves our site and goes to the next site (we're also setting up SSO) they would see the same information.
Here is what I put in the Model:
after_validation :send_new_user_to_hivebrite, on: [ :create, :update ]
def send_new_user_to_hivebrite
payload = {user:{email:Email.find_by(person_id:self.id).address,sub_network_ids:[0],firstname:self.given_name,lastname: self.family_name,is_active:true}}
begin
response = RestClient::Request.execute(
method: :post,
url: 'https://mysite.us.hivebrite.com/api/admin/v1/users',
payload: payload.to_json,
headers: {content_type: :json, accept: :json, Authorization: 'my_token'}
)
self.description = "Response code: #{response.code}"
rescue RestClient::ExceptionWithResponse => e
self.description = "It didn't work"
end
end
I tried doing the same thing but with a GET request (without the payload) and stored the response in self.description and it worked. so the authorization works and the url works. which means something is wrong with my payload right? am i formatting it wrong?
this exact format worked in postman:
{
"user":
{
"email": "MoeTest#postman.com",
"sub_network_ids": [ 0 ],
"firstname": "Moe",
"lastname": "Test",
"external_id": "test_person_id",
"sso_identifier": "test_identifier",
"is_active": true,
"headline": "Nothing to fear, POSTMAN is here",
"summary": "This is my test summary, you will only see it if this post request worked!"
}
}
I thought maybe it couldn't find the email because it was not created yet or something, so i tried updating an existing user and it still goes to rescue.
In rails C i did
payload = {user:{email:Email.find_by(person_id:Person.last.id).address,sub_network_ids:[20548],firstname:Person.last.given_name,lastname:Person.last.family_name,is_active:true}}
then i did
irb(main):016:0> payload.to_json
=> "{\"user\":{\"email\":\"temp#temptemp.temp\",\"sub_network_ids\":[20548],\"firstname\":\"temp\",\"lastname\":\"tempsir\",\"is_active\":true}}"
I checked https://jsonlint.com/ to see if that is valid json and it was. sooo what am I doing wrong?

HelpScout Mailbox API 2.0 - How to create an outgoing conversation from a "user" to a "customer"

I want to use the Help Scout Mailbox 2.0 API to send renewal invoices to my clients. I'm working with the Ruby help-scout_sdk gem -- but their API is just a Restful JSON thing, Ruby has little to do with it.
It's easy enough to become authenticated and create a conversation:
https://developer.helpscout.com/mailbox-api/endpoints/conversations/create/
# Auth credentials in an Rails' initializer
data = {
subject: 'Time for renewal - Invoice #INV-XXXX - Account Name',
type: 'email',
mailbox_id: HelpScout.default_mailbox,
status: 'active',
customer: { email: 'email#example.com' },
created_by: 1234,
threads: [
{
type: 'customer',
customer: { email: 'email#example.com' },
text: 'A test thread.'
}
]
}
HelpScout::Conversation.create(data)
However, this example code will create a new issue in the mailbox queue FROM the customer. Anyone know how to create a new conversation from a Help Scout "user" (our support email) to be sent TO a customer (our client)?
Basically, what params need to be passed to have the API work like how "New Conversation" (new-ticket) works in their Web UI. Thanks!
Turns out I was using the wrong thread type.
To create a new conversation FROM a "user" addressed TO a "customer" your thread should use the "reply" type.
data = {
subject: 'Time for renewal - Invoice #INV-XXXX - Account Name',
type: 'email',
mailbox_id: HelpScout.default_mailbox,
status: 'active',
customer: { email: 'email#example.com' },
created_by: 1234,
threads: [
{
type: 'reply',
customer: { email: 'email#example.com' },
text: 'A test thread.'
}
]
}
Thanks to Kristi at Help Scout for her super quick answer to my question.

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?

Gem Koala Facebook API get_object request

I'm trying to get user's info via Gem Koala Facebook API with below code
#graph = Koala::Facebook::API.new(auth_hash.credentials.token)
profile = #graph.get_object("me")
user.update(
url: auth_hash.extra.raw_info.id,
email: auth_hash.extra.raw_info.email,
friends: #graph.get_connections("me", "friends"),
birthday: #graph.get_object("me", "birthday")
)
friends: #graph.get_connections("me", "friends") works perfectly fine, I will get a list of friends.
However birthday: #graph.get_object("me", "birthday") will give me type: OAuthException, code: 2500, message: Unknown path components: /birthday [HTTP 400]
Things that returns arrays such as likes, photos works fine.
But strings such as last_name, name, first_name will give me the same error.
What can I do to fix this? Is there something else I can enter instead of just birthday
Although it is not very well documented, I read the code of the gem.
Here it explains how to do what you want.
You can do it like this:
Koala::Facebook::API.new(ACCESS_TOKEN).get_object(:me, { fields: [:birthday]})
This will return the birthday and the id of the user.
birthday is not an endpoint like friends, it´s just a field in the user table. Same for name, first_name and last_name:
/me?fields=name,birthday,first_name,last_name
I have no clue about Ruby and Koala, but i assume you can add the fields parameter as object - this is what it looks like in the docs:
#graph.get_object("me", {}, api_version: "v2.0")
Source: https://github.com/arsduo/koala
I think this should do it!
rest = Koala::Facebook::API.new(access_token)
rest.get_object("me?fields=birthday")

Cannot simulate Rails 4 Griddler gem test posting to email processor (post params issue)

We have Griddler Model tests working fine. e.g. we can instantiate the lib/email_processor.rb and it processes.
We want to create a controller test that does an end to end post to the standard /email_processor.
The problem is the params are not coming through the post. our basic code is:
#postattr= {to: "hello#hello.com", subject: "a subject", attachments: [
ActionDispatch::Http::UploadedFile.new({
filename: 'example_virgin_onetransaction.pdf',
type: 'application/pdf',
tempfile: File.new('testfiles/examplefile.pdf")})
]}
post :create, #postattr
expect(response).to be_success
it works as it posts to the correct route and gets processed except the email.attachments object is nil.
we've tried
#postattr.to_json # gives invalid byte sequence in UTF-8
#postattr.to_s.to_json # works, but no params passed through
uri encoding the json string
nothing seems to get processed correctly. what have we missed?
Your params seems right for using only griddler. But incorrect when you use griddler-postmark. Griddle Postmark adapter accept params like your answer, then griddler-postmark pre-process params for griddler. The right format for passing params for incoming email in rails app is as following with griddler-postmark
attributes = {Subject: "a subject", TextBody: "Hello!",
ToFull: [{Email: 'to_email#email.com', Name: 'to email'}],
FromFull: {Email: "from_email#email.com", Name: "from email"},
Attachments: [{Name: 'filename.pdf',
Content: Base64.encode64(fixture_file.read),
ContentType: 'application/pdf',
ContentLength: fixture_file.size
}]}
post :create, attributes
You may fetch issues with handling incoming email with attachment. Thus I am adding hear an example EmailProcessor class as following
class EmailProcessor
def initialize(email)
#email = email
end
def process
if #email.attachments.present?
attachment = #email.attachments.first
file = File.new(attachment.original_filename, 'wb')
file.write attachment.read
file.flush
attached_document = AttachedDocument.new(paper: file)
attached_document.save!
end
end
end
Wish this will help you :)
Right it seems like the formatting of email params is a not as obvious. to and from addresses are actually lists.
#post_attr = {Subject: "a subject", TextBody: "Hello!",
ToFull: [{Email: 'to_email#email.com', Name: 'to email'}],
FromFull: {Email: "from_email#email.com", Name: "from email"},
Attachments: [{Name: 'filename.pdf',
Content: Base64.encode64(fixture_file.read),
ContentType: 'application/pdf',
ContentLength: fixture_file.size
}]}
hope it helps someone

Resources