简体   繁体   中英

Add a single contact via sendgrid api in Ruby on Rails

I have a Rails 5 app and have a form where I want the user to enter their email address and be added as a contact. THIS QUESTION go me pretty close. The response error I am getting is: {"errors":[{"field":null,"message":"access forbidden"}]} which looks like an authentication issue. Here is my code...

def email_signup
    email_address = params[:email_address]

    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 <<my_api_key>>'
    request["content-type"] = 'application/json'
    request.body = "[{\"email\" : email_address}]"

    response = http.request(request)

    redirect_to jobs_url, notice: response.read_body
  end

What am I missing?

OK...I had two issues that needed to be addressed. First, I had the << in the string portion of my API key, the other was that the request body wasn't formatted quite right. Here is what worked for me:

  def email_signup
    email_address = params[:email_address]

    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 SG.Q9sdfsd9s098sdf89sf809sdf809sd'
    request["content-type"] = 'application/json'
    request.body = [{"email": email_address}].to_json

    response = http.request(request)

    redirect_to jobs_url, notice: response.read_body
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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