繁体   English   中英

Rails-如何通过API将联系人添加到SendGrid营销活动中

[英]Rails - How to add contacts to SendGrid marketing campaigns via API

我需要使用SendGrid进行HTTP获取和发布请求,以将联系人添加到我们的帐户中,但是,他们的电子邮件营销功能似乎并没有什么特色。

归结为提出了一些请求,但是我无法通过他们的身份验证步骤。

他们说要这样做

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"}]}

使用他们的API的最终目的是添加联系人

我如何错误地发出此获取请求?

我最终弄清楚了。 供以后参考,下面是起作用的代码...

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

要通过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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM