Rails - 如何通过API向SendGrid营销广告系列添加联系人

时间:2015-12-29 15:14:30

标签: ruby-on-rails ruby rest sendgrid rest-client

我需要使用SendGrid发送HTTP get和post请求以向我们的帐户添加联系人,但是它们似乎并不是他们的电子邮件营销功能的宝石。

归结为提出一些要求,但我无法通过身份验证步骤。

They say to do this

curl -X "GET" "https://api.sendgrid.com/v3/templates" -H "Authorization: Bearer Your.API.Key-HERE" -H "Content-Type: application/json"

使用Rest-Client gem我试图像这样提出身份验证请求......

username = 'username'
api_key = 'SG.MY_API_KEY'
key = Base64.encode64(username + ":" + api_key)
headers = {"Authorization" => "Bearer #{key}", "Content-Type" => "application/json"}
response = RestClient.get 'https://api.sendgrid.com/v3/templates', headers

返回......

RestClient::Unauthorized: 401 Unauthorized: {"errors":[{"field":null,"message":"authorization required"}]}

using their API is to add contacts的最终目标。

我如何错误地提出此请求?

2 个答案:

答案 0 :(得分:4)

我最终搞清楚了。为了将来的参考,这里是有效的代码......

require 'rest_client'
api_key = 'YOUR_API_KEY'
headers = {'Authorization' => "Bearer #{api_key}"}
data = {:email => 'email@website.com'}
response = RestClient.post 'https://api.sendgrid.com/v3/contactdb/recipients', [data].to_json, headers

答案 1 :(得分:1)

要通过API向您的SendGrid帐户添加营销联系人, 请参阅https://sendgrid.api-docs.io/v3.0/contacts-api-recipients/add-recipients

上的文档

您可以在页面的“代码生成”部分看到示例代码。

require 'uri'
require 'net/http'

url = URI("https://api.sendgrid.com/v3/contactdb/recipients")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request["authorization"] = 'Bearer <<YOUR_API_KEY>>'
request["content-type"] = 'application/json'
request.body = "[{\"email\":\"example@example.com\",\"first_name\":\"\",\"last_name\":\"User\",\"age\":25},{\"email\":\"example2@example.com\",\"first_name\":\"Example\",\"last_name\":\"User\",\"age\":25}]"

response = http.request(request)
puts response.read_body