Create Google Contact --> Why Only "NAME" not inserted in new contact? - php

Here is what I have made request :-
// create new entry
$doc = new DOMDocument();
$doc->formatOutput = true;
$entry = $doc->createElement('atom:entry');
$entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:atom', 'http://www.w3.org/2005/Atom');
$entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd', 'http://schemas.google.com/g/2005');
$doc->appendChild($entry);
$cat = $doc->createElement('atom:category');
$cat->setAttribute('scheme', 'http://schemas.google.com/g/2005#kind');
$cat->setAttribute('term', 'http://schemas.google.com/contact/2008#contact');
$entry->appendChild($cat);
// add name element
$name = $doc->createElement('gd:name');
$entry->appendChild($name);
$givenName = $doc->createElement('gd:givenName', $_POST['fname']);
$familyName = $doc->createElement('gd:familyName', $_POST['lname']);
$fullName = $doc->createElement('gd:fullName', $_POST['fname'] . $_POST['lname']);
$name->appendChild($givenName);
$name->appendChild($familyName);
$name->appendChild($fullName);
$content = $doc->createElement('atom:content', 'Notes');
$content->setAttribute('type', 'text');
$entry->appendChild($content);
// add email element
$email = $doc->createElement('gd:email');
$entry->appendChild($email);
$email->setAttribute('address', $_POST['email_id']);
$email->setAttribute('displayName', $_POST['fname']);
$email->setAttribute('primary', 'true');
$email->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
// add im element
$im = $doc->createElement('gd:im');
$entry->appendChild($im);
$im->setAttribute('address', $_POST['email_id']);
$im->setAttribute('protocol', 'http://schemas.google.com/g/2005#GOOGLE_TALK');
$im->setAttribute('primary', 'true');
$im->setAttribute('rel', 'http://schemas.google.com/g/2005#home');
// add phone element
$ph = $doc->createElement('gd:phoneNumber', $_POST['phone']);
$entry->appendChild($ph);
$ph->setAttribute('rel', 'http://schemas.google.com/g/2005#home');
//insert Address
$address = $doc->createElement('gd:structuredPostalAddress');
$address->setAttribute('primary', 'true');
$address->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
$entry->appendChild($address);
$postal = $doc->createElement('gd:postcode', $_POST['postal']);
$country = $doc->createElement('gd:country', $_POST['country']);
$fulladd = $doc->createElement('gd:formattedAddress', $_POST['address']);
$address->appendChild($postal);
$address->appendChild($country);
$address->appendChild($fulladd);
return $doc->saveXML();
and my curl POST data code is:-
$url = 'https://www.google.com/m8/feeds/contacts/default/full?oauth_token=' . $accesstoken;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $contact_detail);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$curlheader[0] = "Content-Type: application/atom+xml";
$curlheader[2] = "Content-length:" . strlen($contact_detail);
$curlheader[1] = "Content-Transfer-Encoding: binary";
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);
$xmlresponse = curl_exec($curl);
Here $contact_detail is nothing but the XML generated above.
And it create new contact successfully, but it can't add NAME of the contact.
Please suggest me changes.

Try to set 'GData-Version:3.0' in your Authorized request Headers, or specify the current API version in you request URL (?v=3), this may helps.

Related

Translate array with google translator

I use below PHP code in Laravel to translate one sentence or paragraph from one input field:
$apiKey = env('GOOGLE_TRANSLATOR_API');
$url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . rawurlencode($name) . '&target='.$language;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
return $responseDecoded['data']['translations'][0]['translatedText'];
and it works perfectly fine.
But now I have two input fields (name and description) and I want to translate both of those fields using one API call and show the results individually.
EDIT
I have tried to use array in the API request as below:
$apiKey = env('GOOGLE_TRANSLATOR_API');
$url = env('GOOGLE_TRANSLATOR_LINK') . $apiKey . '&q=' . array('sentence one', 'sentence two) . '&target='.$language;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
return $responseDecoded['data']['translations'][0]['translatedText'];
But I get Array to string conversion error.
1Installing the Basic Client Libraries Client library PHP
composer require google/cloud-translate
and in your code
use Google\Cloud\Translate\V3\TranslationServiceClient;
$translationServiceClient = new TranslationServiceClient();
/** Uncomment and populate these variables in your code */
// $text = 'Hello, world!';
// $textTwo = 'My name is John':
// $targetLanguage = 'fr'; // your lang
// $projectId = '[Google Cloud Project ID]';
$contents = [$text, $textTwo];
$formattedParent = $translationServiceClient->locationName($projectId, 'global');
try {
$response = $translationServiceClient->translateText(
$contents,
$targetLanguage,
$formattedParent
);
// Display the translation for each input text provided
foreach ($response->getTranslations() as $translation) {
printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
}
} finally {
$translationServiceClient->close();
}
View Code in Github

php- curl isn't working

Here is my code, I have two cURL statements in the same program. The first one uses $ch and second uses $ch1. The problem is first one is getting executed and showing the output but second one does nothing.
<?php
include ('DBconnect.php');
if (isset($_POST['submit'])) {
$verified = "1";
$error = array();
if (empty($_POST['name'])) {
$error[] = 'I am sure you have a name!';
}
else {
$name = $_POST['name'];
}
if (empty($_POST['phone'])) {
$error[] = 'Please enter your phone number with country code';
}
else {
$Phone = $_POST['phone'];
}
if (empty($_POST['Password'])) {
$error[] = 'Please choose a password ';
}
else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the phone number is available:
$query_verify_phone = "SELECT * FROM members WHERE Phone ='$Phone'";
$result_verify_phone = mysqli_query($dbc, $query_verify_phone);
if (!$result_verify_phone) { //if the Query Failed ,similar to if($result_verify_phone==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_phone) == 0) { // IF no previous user is using this phone number.
$query_insert_user = "INSERT INTO `members` ( `Name`, `Phone`, `Password`, `Verified`) VALUES ( '$name', '$Phone', '$Password', '$verified')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
$customerToken = "TOKEN HERE";
$clientTransactionId = rand(55555, 77777);
$duration = "180";
$countryCode = "91";
$z2vToken = "TOKEN HERE";
$postData = array(
'customerToken' => $customerToken,
'clientTransactionId' => $clientTransactionId,
'callerid' => $Phone,
'duration' => $duration,
'countryCode' => $countryCode,
'z2vToken' => $z2vToken,
);
// create post body
$post_body = '';
foreach($postData as $key => $value) {
$post_body.= urlencode($key) . '=' . urlencode($value) . '&';
}
$post_body = rtrim($post_body, '&');
// Initialize CURL data to send via POST to the API
// FIRST ONE CURL REQUEST- WORKING
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.zipdial.com/z2v/startTransaction.action");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
// Execute CURL command and return into variable ch
$string = curl_exec($ch);
curl_close($ch);
$json = json_decode($string);
// now the json has been decoded
// echo "Please do a missed call on: ";
// echo "<img src=' ".$json->img."'>";
$pf = 'fl' . uniqid();
$un = uniqid($pf);
$fpl = 'img' . $un . '.png';
file_put_contents($fpl, file_get_contents($json->img));
Everything above goes fine but the second curl request is not working:
// EVERYTHING ABOVE GOES FINE. BELOW IS SECOND REQUEST- NOT WORKING
$url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1";
$post = array(
'apikey' => "MY KEY HERE",
'url' => "http://site.ext/users/$fpl",
'mode' => "document_photo"
);
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
$ocr = curl_exec($ch1);
$jsonocr = json_decode($ocr, true);
$textblock = $jsonocr['text'][0];
echo '<div class="success">Please give a missed call to ' . $textblock['text'] . ' from your registered phone number to activate account. </div>';
curl_close($ch1);
}
else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
}
else { // The phone number is not available.
echo '<div class="errormsgbox" >That phone number has already been registered. </div>';
}
}
else { //If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // End of the main Submit conditional.
?>
I can make request to second curl request manually from my browser and it works but it isn't working here. What's wrong?
I think you get this error when you dump curl_error($ch1) :
Unknown SSL protocol error in connection to api.idolondemand.com
You can add this line when you curl https if you have no sensitive transiting data :
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
Here is the code which works for me :
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_POST, 1);
curl_setopt($ch1, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 1);
$ocr = curl_exec($ch1);
var_dump($ocr);
var_dump(curl_error($ch1));
When I do this, I get :
string(97) "{ "message": "Unknown API key", "detail": { "error": 2002, "key": "MY KEY HERE" } }" string(0) ""
I have set VERIFYPEER to false and VERIFYHOST to 1 and it worked.

How to print MerchandiseReturn label

USPS suggests to send request XML to
secure.shippingapis.com/ShippingAPI.dll?API=MerchandiseReturnV4&XML=
I have tried with the example XML given at
https://www.usps.com/business/web-tools-apis/merchandise-return-service-labels-v10-2a.htm
$url="https://secure.shippingapis.com/ShippingAPI.dll";
$api="API=MerchandiseReturnV4&XML=";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
echo result;
but it is returning nothing.....
If the request is approaching the API then it would return the response which can be the proper expected response or the error code with some error detail.
The problem for not getting the proper response might be of the following here-
Wrong XML passed to the query string
Missed some required fields in the XML
Invalid Web Tools Credentials
In order to know the exact Error Code and Details you need to parse the returned XML from the API Server.
You can get the response stream and read the stream to the Stream Reader
string result = null;
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
However I implemented this in .Net MVC but it might help for a head start to find the exact problem.
I forget to put the answers after solving my problem.
Function for connect to usps :-
public function connectToUSPS($url, $api, $xml) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api . $xml);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$error = curl_error($ch);
if (empty($error)) {
return $result;
} else {
return false;
}
}
Function to generate USPS label :-
function create_UspsLabel($shipId, $userId) {
$row = 'contains user data';
$uspsUserName = 'a valid usps user name';
$uspsPassword = 'a valid usps user password';
$retailerName = 'retailer name';
$retailerAddress ='retailer address';
$permitNumber = 'a valid permit number';
$retailerState = 'retailer state;
$retailerCity = 'retailer city';
$retailerZip = 'retailer zip code';
$PDUPoBox = 'pdu box number';
$PDUCity = 'pdu city name';
$PDUState = 'pdu state name';
$PDUZip = 'pdu zip code';
$PDUZip2 = 'pdu zip code2';
$oid = 'order id';
$packageId = "KR" . str_pad(($oid + 1), 5, "0", STR_PAD_LEFT);
$state = 'state';
$xml = '<EMRSV4.0Request USERID="' . $uspsUserName . '" PASSWORD="' . $uspsPassword . '">
<Option>RIGHTWINDOW</Option>
<CustomerName>' . $row->name.' '.$row->lastName . '</CustomerName>
<CustomerAddress1>' . $row->suit . '</CustomerAddress1>';
$xml.=' <CustomerAddress2>' . $row->address1 . '</CustomerAddress2>
<CustomerCity>' . $row->city . '</CustomerCity>
<CustomerState>' . $state . '</CustomerState>
<CustomerZip5>' . $row->zipcode . '</CustomerZip5>
<CustomerZip4 />
<RetailerName>' . $retailerName . '</RetailerName>
<RetailerAddress>' . $retailerAddress . '</RetailerAddress>
<PermitNumber>' . $permitNumber . '</PermitNumber>
<PermitIssuingPOCity>' . $retailerCity . '</PermitIssuingPOCity>
<PermitIssuingPOState>' . $retailerState . '</PermitIssuingPOState>
<PermitIssuingPOZip5>' . $retailerZip . '</PermitIssuingPOZip5>
<PDUPOBox>' . $PDUPoBox . '</PDUPOBox>
<PDUCity>' . $PDUCity . '</PDUCity>
<PDUState>' . $PDUState . '</PDUState>
<PDUZip5>' . $PDUZip . '</PDUZip5>
<PDUZip4>' . $PDUZip2 . '</PDUZip4>
<ServiceType>Priority Mail</ServiceType>
<DeliveryConfirmation>False</DeliveryConfirmation>
<InsuranceValue />
<MailingAckPackageID>' . $packageId . '</MailingAckPackageID>
<WeightInPounds>0</WeightInPounds>
<WeightInOunces>10</WeightInOunces>
<RMA>RMA 123456</RMA>
<RMAPICFlag>False</RMAPICFlag>
<ImageType>TIF</ImageType>
<RMABarcode>False</RMABarcode>
<AllowNonCleansedDestAddr>False</AllowNonCleansedDestAddr>
</EMRSV4.0Request>';
$result = $this->connectToUSPS('https://secure.shippingapis.com/ShippingAPI.dll', 'API=MerchandiseReturnV4&XML=', $xml);
$xml = new SimpleXMLElement($result);
$string = base64_decode($xml->MerchandiseReturnLabel);
if ($string) {
$img_file = fopen(__USPSLABELIMAGE__ . "uspsLabel.tif", "w");
fwrite($img_file, $string);
fclose($img_file);
$imageMagickPath = "/usr/bin/convert";
$dest = __USPSLABELIMAGE__ . "uspsLabel.tif";
$filename = time() . ".png";
$pngDestPath = __USPSLABELIMAGE__ . $filename;
exec("$imageMagickPath -density 72 -channel RGBA -colorspace RGB -background none -fill none -dither None $dest $pngDestPath");
return $filename;
} else {
return "error";
}
}

How to get the road map image between two addresses using php, google map or mapquest

I want road map image two addresses, I have tried Google map API and MapQuest API, I want data in static image so that I can use that image to generate PDF file, how can I do this
I have tried
Start address is 6100 Richmond Ave, Houston TX 77057
Google Map
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
$address = $data['address1'].$data['address2']." ".$data['state']." ".$data['city']." ".$data['zip'];
$address = urlencode($address);
$url = "http://maps.googleapis.com/maps/api/staticmap?size=710x300&sensor=true";
$url .= "&path=color:0x0000ff|weight:10|6100+Richmond+Ave+Houston+TX+77057";
$url .= "|".$address ;
$url .= "&markers=color:red|label:A|6100+Richmond+Ave+Houston+TX+77057";
$url .= "&markers=color:green|label:B|".$address;
grab_image($url, $upload_dir.$plan['ID'].".png");
MapQuest Map
First scrapped longitude and latitude each source and destination address
function getLatLong($myaddress) {
$myaddress = urlencode($myaddress);
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$myaddress."&sensor=false";
//get the content from the api using file_get_contents
$getmap = file_get_contents_curl($url);
//the result is in json format. To decode it use json_decode
$googlemap = json_decode($getmap);
//get the latitute, longitude from the json result by doing a for loop
foreach($googlemap->results as $res){
$address = $res->geometry;
$latlng = $address->location;
//$formattedaddress = $res->formatted_address;
return $latlng;
}
}
http://open.mapquestapi.com/staticmap/v4/getmap?size=600,200&zoom=14&shapeformat=cmp&center=40.770021,-73.984003&shape=y_zwFjsrbMxWkz#??}DoC??a#}CyBt#ySiN??fDeP&scenter=40.77069,-73.992378&ecenter=40.770935,-73.97644
for shape check this link
http://www.mapquestapi.com/common/encodedecode.html
How can I get the route via road or we can say driving directions on map in image format.
This is how I have solved above problem
function file_get_contents_curl($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$mapquest_key = "YOUR_API_KEY";
$source_address = "6100 Richmond Ave, Houston TX 77057";
$sLat = "29.73189";
$sLan = "-95.48736";
$plan_add = $plan['address1']." ".$plan['address2']." ".$plan['state']." ".$plan['city']." ".$plan['zip'];
# Step 1: Mapquest API url to get session_key and lng and lat
$mapquest_url1 = "http://www.mapquestapi.com/directions/v1/route?key=".$mapquest_key."&outFormat=json";
$mapquest_url1 .= "&from=".urlencode($wocg_address)."&to=".urlencode($plan_add);
$mapquest_data = file_get_contents_curl($mapquest_url1);
$mapquest_data_array = json_decode($mapquest_data);
$session_id = isset($mapquest_data_array->route->sessionId) ? $mapquest_data_array->route->sessionId : "";
$eLat = isset($mapquest_data_array->route->locations[1]->latLng->lat) ? $mapquest_data_array->route->locations[1]->latLng->lat : "";
$eLan = isset($mapquest_data_array->route->locations[1]->latLng->lng) ? $mapquest_data_array->route->locations[1]->latLng->lng : "";
# Step 2: Get images based on start and end location and session id
if(!empty($session_id) && !empty($eLat) && !empty($eLan)) {
$mapquest_url2 = "http://www.mapquestapi.com/staticmap/v3/getmap?key=".$mapquest_key;
$mapquest_url2 .= "&size=710,300&type=map";
$mapquest_url2 .= "&session=".$session_id;
$mapquest_url2 .= "&scenter=".$sLat.",".$sLan;
$mapquest_url2 .= "&ecenter=".$eLat.",".$eLan;
grab_image($mapquest_url2, $upload_dir.$plan['ID'].".png");
} else {
# If failure with mapquest then scrap image from google map
$plan_address = urlencode($plan_add);
$url = "http://maps.googleapis.com/maps/api/staticmap?size=710x300&sensor=true";
$url .= "&path=color:0x0000ff|weight:10|77001+TX+Houston+USA";
$url .= "|".$plan_address;
$url .= "&markers=color:red|label:A|77001+TX+Houston+USA";
$url .= "&markers=color:green|label:B|".$plan_address;
grab_image($url, $upload_dir.$plan['ID'].".png");
}

How to use Constant Contact API?

I want to use API of the constant contact and want to insert user email using PHP while user register to the site.
please reply if any help.
Thanks in advance.
// fill in your Constant Contact login and API key
$ccuser = 'USERNAME_HERE';
$ccpass = 'PASS_HERE';
$cckey = 'APIKEY_HERE';
// fill in these values
$firstName = "";
$lastName = "";
$emailAddr = "";
$zip = "";
// represents the contact list identification number(s)
$contactListId = INTEGER_OR_ARRAY_OF_INTEGERS_HERE;
$contactListId = (!is_array($contactListId)) ? array($contactListId) : $contactListId;
$post = new SimpleXMLElement('<entry></entry>');
$post->addAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$title = $post->addChild('title', "");
$title->addAttribute('type', 'text');
$post->addChild('updated', date('c'));
$post->addChild('author', "");
$post->addChild('id', 'data:,none');
$summary = $post->addChild('summary', 'Contact');
$summary->addAttribute('type', 'text');
$content = $post->addChild('content');
$content->addAttribute('type', 'application/vnd.ctct+xml');
$contact = $content->addChild('Contact');
$contact->addAttribute('xmlns', 'http://ws.constantcontact.com/ns/1.0/');
$contact->addChild('EmailAddress', $emailAddr);
$contact->addChild('FirstName', $firstName);
$contact->addChild('LastName', $lastName);
$contact->addChild('PostalCode', $zip);
$contact->addChild('OptInSource', 'ACTION_BY_CUSTOMER');
$contactlists = $contact->addChild('ContactLists');
// loop through each of the defined contact lists
foreach($contactListId AS $listId) {
$contactlist = $contactlists->addChild('ContactList');
$contactlist->addAttribute('id', 'http://api.constantcontact.com/ws/customers/' . $ccuser . '/lists/' . $listId);
}
$posturl = "https://api.constantcontact.com/ws/customers/{$ccuser}/contacts";
$authstr = $cckey . '%' . $ccuser . ':' . $ccpass;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $authstr);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/atom+xml"));
curl_setopt($ch, CURLOPT_HEADER, false); // Do not return headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // If you set this to 0, it will take you to a page with the http response
$response = curl_exec($ch);
curl_close($ch);
// returns true on success, false on error
return (!is_numeric($response));
The developers of ConstantContact have launched PHP library to handle such kind of tasks.
Following version is for older PHP versions (5.2 or lesser). Download code from here: https://github.com/constantcontact/ctct_php_library
Following is an example to add a subscriber's email in your constant contact lists.
After downloading the above library, use following code to add an email in Constant Contact list(s).
session_start();
include_once('ConstantContact.php'); // Set path accordingly
$username = 'YOUR_CONSTANT_CONTACT_USER_NAME';
$apiKey = 'YOUR_API_KEY';
$password = 'YOUR_CONSTANT_CONTACT_PASSWORD';
$ConstantContact = new Constantcontact("basic", $apiKey, $username, $password);
$emailAddress = "new_email#test.com";
// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);
// If the search did not return a contact object
if($search == false){
$Contact = new Contact();
$Contact->emailAddress = $emailAddress;
//$Contact->firstName = $firstName;
//$Contact->lastName = $lastName;
// represents the contact list identification link(s)
$contactList = LINK_OR_ARRAY_OF_LINKS_HERE;
// For example,
// "http://api.constantcontact.com/ws/customers/USER_NAME/lists/14";
$Contact->lists = (!is_array($contactList)) ? array($contactList) : $contactList;
$NewContact = $ConstantContact->addContact($Contact);
if($NewContact){
echo "Contact Added. This is your newly created contact's information<br /><pre>";
print_r($NewContact);
echo "</pre>";
}
} else {
echo "Contact already exist.";
}
Note: The latest version can be found on the GitHub links given in following URL: http://developer.constantcontact.com/libraries/sample-code.html
But I am not sure if the above example code works with the newer library or not.
If you can't get this to work, you might have to add this curl_setopt:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

Categories