Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ConstantContact{
- private $api_key;
- private $token;
- private $is_valid = false;
- private $url = 'https://api.constantcontact.com/v2/';
- # constructor simply sets some internal vars
- function __construct($api_key, $token){
- if(!is_string($api_key) || empty($api_key)) return;
- $this->api_key = $api_key;
- if(!is_string($token) || empty($token)) return;
- $this->token = $token;
- $this->is_valid = true;
- }
- # returns available contact lists
- function get_lists(){
- if(!$this->is_valid) return false;
- $url = $this->url.'lists/?api_key='.$this->api_key;
- $ctx = stream_context_create($this->get_auth_context());
- $result = json_decode(file_get_contents($url,0,$ctx));
- if(false===$result) return false;
- return (array)$result;
- }
- # adds a contact to specified list.
- # extra data is appended with array_merge_recursive()
- function add_contact($email, $list_id, $extra_data=array()){
- # standard input validation
- if(!is_email($email)) return false;
- if(!is_numeric($list_id) ) return false;
- if(!is_array($extra_data)) $extra_data = array();
- # prepare the data
- $d = array_merge_recursive($extra_data, array(
- 'lists'=>array(array('id'=>"".$list_id)),
- 'email_addresses'=>array( array(
- 'email_address'=>$email,
- 'opt_in_source'=>'ACTION_BY_OWNER',
- 'confirm_status'=>'NO_CONFIRMATION_REQUIRED'
- ))
- ));
- # create the context
- $url = $this->url."contacts?api_key=".$this->api_key;
- $ctx = array_merge_recursive($this->get_auth_context(),array(
- 'http'=>array(
- 'content'=>''.json_encode($d)
- )
- ));
- $ctx['http']['method']="POST";
- $ctx['http']['header'].="\r\n".implode("\r\n", array(
- "Content-type: application/json",
- "Action-By: ACTION_BY_OWNER"
- ));
- $ctx = stream_context_create($ctx);
- return file_get_contents($url,0,$ctx);
- }
- # returns authentication context template for file_get_contents
- private function get_auth_context(){
- return array('http'=>array(
- 'method'=>'GET','header'=>implode("\r\n",array(
- "Authorization: Bearer ".$this->token,
- "X-Originating-Ip: ".$_SERVER['REMOTE_ADDR']
- ))
- ));
- }
- }
- $coco = new ConstantContact("api_key", "token");
- echo var_dump($coco->add_contact('test_'.time().'@test.ca',1));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement