/**
  * Turns a ClientException into a CtctException - like magic.
  * @param ClientException $exception - Guzzle ClientException
  * @return CtctException
  */
 protected function convertException($exception)
 {
     $ctctException = new CtctException($exception->getResponse()->getReasonPhrase(), $exception->getCode());
     $ctctException->setUrl($exception->getResponse()->getEffectiveUrl());
     $ctctException->setErrors(json_decode($exception->getResponse()->getBody()->getContents()));
     return $ctctException;
 }
Beispiel #2
0
 /**
  * Make an HTTP request
  * @param $url - request url
  * @param $method - HTTP method to use for the request
  * @param array $headers - any http headers that should be included with the request
  * @param string|null $data - payload to send with the request, if any
  * @return CurlResponse
  * @throws CTCTException
  */
 private static function httpRequest($url, $method, array $headers = array(), $data = null)
 {
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_URL, $url);
     curl_setopt($curl, CURLOPT_HEADER, 0);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($curl, CURLOPT_USERAGENT, "ConstantContact AppConnect PHP Library v1.1");
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
     curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
     // add data to send with request if present
     if ($data) {
         curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
     }
     $response = CurlResponse::create(curl_exec($curl), curl_getinfo($curl), curl_error($curl));
     curl_close($curl);
     // check if any errors were returned
     $body = json_decode($response->body, true);
     if (isset($body[0]) && array_key_exists('error_key', $body[0])) {
         $ex = new CtctException($response->body);
         $ex->setCurlInfo($response->info);
         $ex->setErrors($body);
         throw $ex;
     }
     return $response;
 }
            $action = "Updating Contact";
            $contact = $response->results[0];
            if ($contact instanceof Contact) {
                $contact->addList($_POST['list']);
                $contact->first_name = $_POST['first_name'];
                $contact->last_name = $_POST['last_name'];
                /*
                 * The third parameter of updateContact defaults to false, but if this were set to true it would tell
                 * Constant Contact that this action is being performed by the contact themselves, and gives the ability to
                 * opt contacts back in and trigger Welcome/Change-of-interest emails.
                 *
                 * See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
                 */
                $returnContact = $cc->contactService->updateContact(ACCESS_TOKEN, $contact);
            } else {
                $e = new CtctException();
                $e->setErrors(array("type", "Contact type not returned"));
                throw $e;
            }
        }
        // catch any exceptions thrown during the process and print the errors to screen
    } catch (CtctException $ex) {
        echo '<span class="label label-important">Error ' . $action . '</span>';
        echo '<div class="container alert-error"><pre class="failure-pre">';
        print_r($ex->getErrors());
        echo '</pre></div>';
        die;
    }
}
?>
function wpcc_add_contact()
{
    $cc = new ConstantContact(WPCC_APIKEY);
    try {
        $lists = $cc->listService->getLists(WPCC_ACCESS_TOKEN);
    } catch (CtctException $ex) {
        foreach ($ex->getErrors() as $error) {
            print_r($error);
        }
        if (!isset($lists)) {
            $lists = null;
        }
    }
    // check if the form was submitted
    if (isset($_POST['email']) && strlen($_POST['email']) > 1) {
        $action = "Getting Contact By Email Address";
        try {
            // check to see if a contact with the email address already exists in the account
            $response = $cc->contactService->getContacts(WPCC_ACCESS_TOKEN, array("email" => $_POST['email']));
            // create a new contact if one does not exist
            if (empty($response->results)) {
                $action = "Creating Contact";
                $contact = new Contact();
                $contact->addEmail($_POST['email']);
                $contact->addList('1818691277');
                $contact->first_name = $_POST['first_name'];
                $contact->last_name = $_POST['last_name'];
                $address = new Address();
                $address->address_type = "BUSINESS";
                // PERSONAL, BUSINESS, UNKNOWN
                $address->line1 = $_POST['address_line_1'];
                $address->line2 = $_POST['address_line_2'];
                $address->city = $_POST['city'];
                $address->state_code = $_POST['state_code'];
                $address->postal_code = $_POST['postal_code'];
                $address->country_code = "US";
                $contact->addAddress($address);
                $returnContact = $cc->contactService->addContact(WPCC_ACCESS_TOKEN, $contact);
            } else {
                $action = "Updating Contact";
                $contact = $response->results[0];
                if ($contact instanceof Contact) {
                    $contact->addList('1818691277');
                    $contact->first_name = $_POST['first_name'];
                    $contact->last_name = $_POST['last_name'];
                    //If address exists, update that address. Else, create a new address object.
                    if (count($contact->addresses) > 0) {
                        $address = $contact->addresses[0];
                    } else {
                        $address = new Address();
                    }
                    $address->address_type = "BUSINESS";
                    // PERSONAL, BUSINESS, UNKNOWN
                    $address->line1 = $_POST['address_line_1'];
                    $address->line2 = $_POST['address_line_2'];
                    $address->city = $_POST['city'];
                    $address->state = '';
                    $address->state_code = $_POST['state_code'];
                    $address->postal_code = $_POST['postal_code'];
                    $address->country_code = $_POST['country_code'];
                    $contact->addAddress($address);
                    $customField_1 = new CustomField();
                    $customField_1->name = "CustomField1";
                    $customField_1->value = date('m/d/y', strtotime($_POST['dob']));
                    $contact->addCustomField($customField_1);
                    /*
                     * The third parameter of updateContact defaults to false, but if this were set to true it would tell
                     * Constant Contact that this action is being performed by the contact themselves, and gives the ability to
                     * opt contacts back in and trigger Welcome/Change-of-interest emails.
                     *
                     * See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
                     */
                    $returnContact = $cc->contactService->updateContact(WPCC_ACCESS_TOKEN, $contact);
                } else {
                    $e = new CtctException();
                    $e->setErrors(array("type", "Contact type not returned"));
                    throw $e;
                }
            }
            // catch any exceptions thrown during the process and print the errors to screen
        } catch (CtctException $ex) {
            echo '<span class="label label-important">Error ' . $action . '</span>';
            echo '<div class="container alert-error"><pre class="failure-pre">';
            print_r($ex->getErrors());
            echo '</pre></div>';
            die;
        }
    }
}
 /**
  * Make an Http request
  * @param $url - request url
  * @param array $headers - array of all http headers to send
  * @param $data - data to send with the request
  * @throws CtctException - if any errors are contained in the returned payload
  * @return CurlResponse
  */
 private static function httpRequest($url, $method, array $headers = array(), $data = null)
 {
     self::$debug = current_user_can('manage_options') && (isset($_GET['debug']) && $_GET['debug'] === 'requests');
     // Make it WP format.
     $headers[] = sprintf("User-Agent: Constant Contact WordPress Plugin v%s", WP_CTCT::version);
     $headers = implode("\n", $headers);
     $args = array('headers' => $headers, 'method' => $method, 'body' => $data, 'timeout' => 50, 'redirection' => strtoupper($method) === 'POST' ? 0 : 10, 'httpversion' => '1.1', 'ssl_verify' => 0, 'cache' => self::getCache($url, $data, $method), 'cache_key' => apply_filters('ctct_cachekey', self::$cachekey), 'flush_key' => apply_filters('ctct_flushkey', self::$flushkey));
     $response = wp_remote_request($url, $args);
     /**
      * Since 3.1.5
      */
     if (is_wp_error($response)) {
         $response->add_data('url', $url);
         $response->add_data('args', $args);
         do_action('constant_contact_add_notice', $response);
         return false;
     }
     // check if any errors were returned
     $body = json_decode($response['body'], true);
     // There was an error
     if (isset($body[0]) && !empty($body[0]['error_key'])) {
         try {
             // Throw a new CTCT exception
             $ex = new CtctException($response['body']);
             $ex->setCurlInfo($response['response']);
             $ex->setErrors($body);
             do_action('ctct_log', 'httpRequest Error', $ex);
             do_action('ctct_debug', 'httpRequest Error', $ex);
             throw $ex;
         } catch (Exception $e) {
             $errors = $ex->getErrors();
             preg_match('/^#\\/(.*?):(.+)$/ism', $errors[0]['error_message'], $matches);
             if (!empty($matches)) {
                 $error_field = trim(rtrim($matches[1]));
                 $error_message = trim(rtrim($matches[2]));
             } else {
                 $error_field = NULL;
                 $error_message = $errors[0]['error_message'];
             }
             $WP_Error = new WP_Error($errors[0]['error_key'], $error_message, array('field' => $error_field, 'response' => $response, 'request' => $args, 'request_url' => $url));
             do_action('constant_contact_add_notice', $WP_Error);
             return false;
         }
     }
     $responseClass = new stdClass();
     $responseClass->body = $response['body'];
     return $responseClass;
 }