Wordpress + Constant Contact PHP SDK include path - php

I'm current trying to implement the Constant Contact PHP sdk into a wordpress site. Ask part of the SDK you have to include some core PHP files in order for the email code to work. If those files aren't found, the page dies with no PHP error. Currently I have the folder called "src" 9their naming convention not mine) in the root of the site's theme (/wp-content/themes/mytheme/src...).
Here is the email form code that calls the files:
<?php
// require the autoloader
require_once(TEMPLATEPATH . '/src/Ctct/autoload.php');
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Exceptions\CtctException;
// Enter your Constant Contact APIKEY and ACCESS_TOKEN
define("APIKEY", "XXXXXX");
define("ACCESS_TOKEN", "XXXXXX");
$cc = new ConstantContact(APIKEY);
// attempt to fetch lists in the account, catching any exceptions and printing the errors to screen
try {
$lists = $cc->getLists(ACCESS_TOKEN);
} catch (CtctException $ex) {
foreach ($ex->getErrors() as $error) {
print_r($error);
}
}
// 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 addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $_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($_POST['list']);
$contact->first_name = $_POST['first_name'];
$contact->last_name = $_POST['last_name'];
/*
* The third parameter of addContact 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->addContact(ACCESS_TOKEN, $contact, false);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$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->updateContact(ACCESS_TOKEN, $contact, false);
}
// 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();
}
}
?>
autoload.php is available where it should be at http://www.thedaileymethod.com/_main_site/wp-content/themes/dailey-method/src/Ctct/autoload.php which is what I thought I called in the PHP file, but the page keeps on breaking for me.
Do I have the require_once path incorrect?
EDIT:
When the for code is loaded, the page 500 errors. When I remove the form code, that error goes away and the page loads fine. Nothing nothing in the log from a PHP error standpoint.

Remove statements with use use keyword and change
$cc = new ConstantContact(APIKEY);
to
$cc = new \Ctct\ConstantContact(APIKEY);

Related

How can I trigger an email from this php script?

I'm new to php and I'm trying to work out how to send myself an email upon successful payment. How would I go about that? If you see half way down the script there is an 'if' statement that defines a successful Stripe Payment Call - so that is the point where an email ought to be sent.
Do I include a POST Email request - like this:
($_POST['email'])) {
$email_to = "me#example.com";
$email_subject = "Email subject line";
And here's the php script that currently works - you'll see the 'IF' statement half way throught the script.
<?php
require('config.inc.php');
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email=$_POST['email'];
// Stores errors:
$errors = array();
// Need a payment token:
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
// Check for a duplicate submission, just in case:
// Uses sessions, you could use a cookie instead.
if (isset($_SESSION['token']) && ($_SESSION['token'] == $token)) {
$errors['token'] = 'You have apparently resubmitted the form.';
} else { // New submission.
$_SESSION['token'] = $token;
}
} else {
$errors['token'] = 'Your subscription cannot be processed because you must have JavaScript enabled. Please try again.';
}
// Set the order amount somehow:
$amount = 2700; // $20, in cents
// Validate other form data!
// If no errors, process the order:
if (empty($errors)) {
// create the charge on Stripe's servers - this will charge the user's card
try {
// Include the Stripe library:
require_once('lib/Stripe.php');
// set your secret key: remember to change this to your live secret key in production
// see your keys here https://manage.stripe.com/account
Stripe::setApiKey(STRIPE_PRIVATE_KEY);
// Charge the order:
$charge=Stripe_Customer::create(array(
"card"=>$token,
"email" => $email,
"plan" =>"newsletter",
));
// Check that it was paid:
if (!empty($charge)) {
//echo $amount;
// Store the order in the database.
// Send the email.
// Celebrate!
/*$cookie_name = "success_msg";
$cookie_value = "Your Payment is successfully done";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");*/
$_SESSION['success_msg']="Your subcription was successfull - thank you!<br><br>We will send you further details shortly on how to access your account.";
echo "<script>window.location.href='index.php'</script>";
exit(0);
} else { // Charge was not paid!
echo '<div class="alert alert-error"><h4>Payment System Error!</h4>Your payment could NOT be processed (i.e., you have not been charged) because the payment system rejected the transaction. You can try again or use another card.</div>';
}
} catch (Stripe_CardError $e) {
// Card was declined.
$e_json = $e->getJsonBody();
$err = $e_json['error'];
$errors['stripe'] = $err['message'];
} catch (Stripe_ApiConnectionError $e) {
// Network problem, perhaps try again.
} catch (Stripe_InvalidRequestError $e) {
// You screwed up in your programming. Shouldn't happen!
} catch (Stripe_ApiError $e) {
// Stripe's servers are down!
} catch (Stripe_CardError $e) {
// Something else that's not the customer's fault.
}
} // A user form submission error occurred, handled below.
} // Form submission.
?>
asdasd
You could create a function that sends the email:
function sendEmail () {
$email_to = "me#example.com";
$email_subject = "Email subject line";
... ETC ...
}
Then in your script where the payment is successful, just before notifying the user you can include the function:
...
if (!empty($charge)) {
...
// Include your function if you wrote this to an external script
require_once '/path/to/php/sendEmail.function.php';
// Then make use of it:
sendEmail();
/*$cookie_name = "success_msg";
$cookie_value = "Your Payment is successfully done";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");*/
$_SESSION['success_msg']="Your subcription was successfull - thank you!<br><br>We will send you further details shortly on how to access your account.";
// Redirect the user to a new page
echo "<script>window.location.href='index.php'</script>";
// Then you can exit runtime
exit(0);
}
// Charge was not paid!
else {
echo '<div class="alert alert-error"><h4>Payment System Error!</h4>Your payment could NOT be processed (i.e., you have not been charged) because the payment system rejected the transaction. You can try again or use another card.</div>';
}
...
It's pretty important that the email function will either send the email or just continue as normal as you'd not want a failed email to interupt the users experience. You could have a fallback so that if the email doesnt send it writes it to the database or something but do not exit with an error during this process.

PHPMailerAutoload Completion Error

Edit: Jawish has explained why a blank page occurs when submitting my code. I simply forgot an echo statement. This has been marked as the correct answer even though it hasn't gotten my code to successfully run. My question was vague and Jawish found an issue that will help me with error reporting. I'll post another edit if I can find the issue with the code.
I'm having a small problem sending information using the following code to login to my gmail account. As soon as I run my form and submit it, I'm just shown a blank page. I've attempted to find some kind of error, but I can't get the error to display. I've followed the answer from this post, but even making those changes and adding the code does nothing that I can tell. This code is supposed to run the mailer and once the email is sent, the user is supposed to be redirected to a 'thank you' page with never happens. So the issue happens in one of the two codes listed. The strange thing is this use to work. I went on vacation then came back and now it doesn't work. I'm sure I messed something up somehow, but I'm at a loss for ideas.
Any help is appreciated, thanks. (asterisks are shown to hide personal information)
<?php
session_start();
require_once '../PHPMailer-master/PHPMailerAutoload.php';
if(isset($_POST['icon'])){
$m = new PHPMailer();
$m->isSMTP();
$m->SMTPAuth = true;
$m->Host = 'smtp.gmail.com';
$m->Username = '*********#gmail.com';
$m->Password = '****';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->isHTML(true);
$m->Subject = 'Contact form submitted';
$m->Body = $_POST['icon'];
$m->FromName = 'Contact';
$m->AddAddress('********#gmail.com','***Name Here****');
if($m->send()) {
header('Location: contact_thanks.php');
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $m->ErrorInfo;
die();
} else {
'Sorry, could not send email';
}
} else {'something went wrong';}
?>
This is the PHPMailerAutoload.php referenced in the previous code.
<?php
function PHPMailerAutoload($classname)
{
//Can't use __DIR__ as it's only in PHP 5.3+
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
if (is_readable($filename)) {
require $filename;
}
}
if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
//SPL autoloading was introduced in PHP 5.1.2
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register('PHPMailerAutoload', true, true);
} else {
spl_autoload_register('PHPMailerAutoload');
}
} else {
/**
* Fall back to traditional autoload for old PHP versions
* #param string $classname The name of the class to load
*/
function __autoload($classname)
{
PHPMailerAutoload($classname);
}
}
?>
You are missing "echo" statements on the last else blocks so you would not get any output on those branches.
Should be:
} else {
echo 'Sorry, could not send email';
}
} else {
echo 'something went wrong';
}

Constant Contact API

I'm trying to write a simple Constant Contact script for adding and updating emails. The script is simple enough and should've ran smoothly. But when I start to include 'src/Ctct/autoload.php' the page just returns blank. I tried running it on another server and it works. But on my working server, it returns blank. It uses OAuth authentication from CTCT. I think it's a setting in the server, but I have no control over the server and any changes need to be forwarded to an admin, I just don't know what I need to change.
Here's the code:
require "Scripts/ConstantContact/src/Ctct/autoload.php";
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Exceptions\CtctException;
define("APIKEY", "*** Censored Media (18+ only) ***");
define("ACCESS_TOKEN", "*** Censored Media (18+ only) ***");
$cc = new ConstantContact(APIKEY);
// attempt to fetch lists in the account, catching any exceptions and printing the errors to screen
$lists = $cc->getLists(ACCESS_TOKEN);
$action = "Getting Contact By Email Address";
$Email = "asdf#asdf.com";
$FirstName = "Asdf";
$LastName = "Ghjk";
// check to see if a contact with the email addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $Email);
// create a new contact if one does not exist
if (empty($response->results)) {
$action = "Creating Contact";
$contact = new Contact();
$contact->addEmail($Email);
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->addContact(ACCESS_TOKEN, $contact);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$contact->addList('1');
$contact->first_name = $FirstName;
$contact->last_name = $LastName;
$returnContact = $cc->updateContact(ACCESS_TOKEN, $contact);
}
// catch any exceptions thrown during the process and print the errors to screen
if (isset($returnContact)) {
echo '<div class="container alert-success"><pre class="success-pre">';
print_r($returnContact);
echo '</pre></div>';
}
print '<p>'.$action.'</p>';
Again, this works on another server I tried, but doesn't work on my working server.
Any help would be appreciated.
Thanks!
Are you running PHP 5.3 or higher on the other server? Also did the domain change at all, if so that may throw an exception resulting in a blank page as your API key is domain specific. Feel free to shoot me an email and I will be glad to help you out with this - mstowe [at] constantcontact.com
-Mike

Undefined variable with OpenID

I have a website running on a less well known CMS called Ushahidi. There is built in OpenID functionality where folk can login with Facebook or Google.
I don't have enough dev skills to understand whats happening here but, it appears that I've almost got it working, except, I'm receiving the following error when trying to test it out on my own Google login:
An error was detected which prevented the loading of this page. If
this problem persists, please contact the website administrator.
application/controllers/login.php [503]: Undefined variable: user
I suspect, but am not sure, that defining a variable is easy enough but since I lack the knowledge I hoped to ask someone on here if they could see where I need to define the variable. Line 503 is part of a larger code block of about 100 lines, I know that it's not good practice to post larger chunks of code on here but I'm really unsure of what is and is not relevant. So forgive me. I have highlighted in bold where line 503 is. Can anyone point out what I must do here?
// OpenID Post
try
{
$openid = new OpenID;
// Retrieve the Name (if available) and Email
$openid->required = array("namePerson", "contact/email");
if( ! $openid->mode)
{
if(isset($_POST["openid_identifier"]))
{
$openid->identity = $_POST["openid_identifier"];
header("Location: " . $openid->authUrl());
}
}
elseif ($openid->mode == "cancel")
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = "You have canceled authentication!";
}
else
{
if ($openid->validate())
{
// Does User Exist?
$openid_user = ORM::factory("openid")
->where("openid", $openid->identity)
->find();
if ($openid_user->loaded AND $openid_user->user)
{
// First log all other sessions out
$auth->logout();
// Initiate Ushahidi side login + AutoLogin
$auth->force_login($openid_user->user->username);
// Exists Redirect to Dashboard
**(THIS IS LINE 503)** url::redirect($user->dashboard());
}
else
{
// Does this openid have the required email??
$new_openid = $openid->getAttributes();
if ( ! isset($new_openid["contact/email"]) OR
empty($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . " has not been logged in. No Email Address Found.";
}
else
{
// Create new User and save OpenID
$user = ORM::factory("user");
// But first... does this email address already exist
// in the system?
if ($user->email_exists($new_openid["contact/email"]))
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $new_openid["contact/email"] . " is already registered in our system.";
}
else
{
$username = "user".time(); // Random User Name from TimeStamp - can be changed later
$password = text::random("alnum", 16); // Create Random Strong Password
// Name Available?
$user->name = (isset($new_openid["namePerson"]) AND ! empty($new_openid["namePerson"]))
? $new_openid["namePerson"]
: $username;
$user->username = $username;
$user->password = $password;
$user->email = $new_openid["contact/email"];
// Add New Roles
$user->add(ORM::factory('role', 'login'));
$user->add(ORM::factory('role', 'member'));
$user->save();
// Save OpenID and Association
$openid_user->user_id = $user->id;
$openid_user->openid = $openid->identity;
$openid_user->openid_email = $new_openid["contact/email"];
$openid_user->openid_server = $openid->server;
$openid_user->openid_date = date("Y-m-d H:i:s");
$openid_user->save();
// Initiate Ushahidi side login + AutoLogin
$auth->login($username, $password, TRUE);
// Redirect to Dashboard
url::redirect($user->dashboard());
}
}
}
}
else
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $openid->identity . "has not been logged in.";
}
}
}
catch (ErrorException $e)
{
$openid_error = TRUE;
$message_class = 'login_error';
$message = $e->getMessage();
}
The problem is that the code is using $user several lines before it's actually defined. It might be a typo, though - maybe $openid_user->user->dashboard() at line 503 might work, though it's a WAG.

INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session

Similar issues -
INVALID_SESSION_ID using partner/enterprise wsdl for two different SF users - Tried solution but didn't work.
I was trying to use Salesforce PHP toolkit with ZF 2. I have added namespace to php files in salesforce soap client and used it in zend controller.
Added follwing line to all php files in Salesforce SOAP client library.
namespace Salesforce\Soapclient;
Then included it in ZF controller.
use Salesforce\Soapclient;
Here is the connetion code -
$empid = 'e1234567';
$sf_WSDL = 'C:\wamp\www\myapp\app\vendor\salesforce\wsdl\enterprise.wsdl.xml';
$sf_username = $config['salesforce']['username'];
$sf_password = $config['salesforce']['password'];
$sf_token = $config['salesforce']['token'];
/***********/
try {
// Create SOAP client instance
$sfSoapClient = new Soapclient\SforceEnterpriseClient();
// Create connection
$sfSoapClient->createConnection($sf_WSDL);
var_dump($_SESSION['enterpriseSessionId']);
if (isset($_SESSION['enterpriseSessionId'])) {
$location = $_SESSION['enterpriseLocation'];
$sessionId = $_SESSION['enterpriseSessionId'];
$sfSoapClient->setEndpoint($location);
$sfSoapClient->setSessionHeader($sessionId);
} else {
// Login to SF
$sfSoapClient->login($sf_username,$sf_password . $sf_token);
$_SESSION['enterpriseLocation'] = $sfSoapClient->getLocation();
$_SESSION['enterpriseSessionId'] = $sfSoapClient->getSessionId();
}
var_dump($_SESSION['enterpriseSessionId']);
// Get candidate profile by employee id
$candidate_profile = $this->getCandidateTable()->getCandidateByEmpId($empid);
$ids = array();
array_push($ids, $empid);
// If no profile for logged internal employee
if (!$candidate_profile){
$query = "SELECT Id, First_Name__c from Employee__c";
$response = $sfSoapClient->query($query);
echo "Results of query '$query'<br/><br/>\n";
foreach ($response->records as $record) {
echo $record->Id . ": " . $record->First_Name__c . "<br/>\n";
}
}
} catch (Exception $exc) {
//TODO Handle error login exception
die('Connection could not established.');
}
But I'm getting following error -
INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal
Session
Note that "Lock sessions to the IP address from which they originated" setting is turned off.

Categories