constantcontact / ruby-sdk

Constant Contact Ruby SDK for v2 API
Other
17 stars 47 forks source link

Add an example for creating new contacts #28

Closed garyv closed 8 years ago

garyv commented 10 years ago

Listing existing contacts is okay, but what I need to do is make a form for adding new email subscribers.

I've been trying to extrapolate how to do this based on the documentation and examples, but they don't seem to cover anything like this.

csciuto commented 8 years ago

This is a very old issue, but the example in https://github.com/constantcontact/ruby-sdk/blob/master/examples/contact/myapp.rb does add a contact but isn't easy to follow as it does a lot more than that. I'm not a Ruby expert but this works:

#gem install constantcontact

require 'yaml'
require 'constantcontact'

class ContactExample

  def initialize()
    cnf = YAML::load(File.open('config/config.yml'))
    @cc = ConstantContact::Api.new(cnf['api_key'], cnf['oauth_token'])
  end

  def add_contact( contact_json )
    @cc.add_contact( contact_json )
  end

  def get_lists
    @cc.get_lists()
  end

end

class AddContactTest
    def do()
        contact_example = ContactExample.new    
        contact_list = contact_example.get_lists[0].id
        puts "Add what email address?"
        email_address = gets.chomp
        puts "Adding #{email_address} to Contact List #{contact_list}"

        list_to_add_to = ConstantContact::Components::ContactList.new
        list_to_add_to.id = contact_list

        new_contact = ConstantContact::Components::Contact.new
        new_contact.add_email(ConstantContact::Components::EmailAddress.new(email_address))
        new_contact.add_list(list_to_add_to)
        new_contact.first_name = 'Example'
        new_contact.last_name = 'User'

        #input = "{ 'email_addresses':[{'email_address':'#{email_address}'}], 'lists':[{'id':'#{contact_list}'}], first_name':'Example', 'last_name':'User'}" 
        #puts input
        puts new_contact.to_json

        puts contact_example.add_contact( new_contact ).to_json

    rescue  RestClient::BadRequest => e
        puts "#{e.http_code} - #{e.http_body}"
    end 
end

AddContactTest.new.do