How to send lead via API to Getresponse - php

I have a html form where name and email address are getting collected. I try to submit these informations to a GetResponse list using this script:
<?php
function mytheme_save_to_getresponse($form)
{
require_once 'jsonRPCClient.php';
$api_key = 'myAPIkey';
$api_url = 'http://api2.getresponse.com';
$client = new jsonRPCClient($api_url);
$result = NULL;
try {
$result = $client->get_campaigns(
$api_key,
array (
# find by name literally
'name' => array ( 'EQUALS' => 'testlist' )
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
$campaigns = array_keys($result);
$CAMPAIGN_ID = array_pop($campaigns);
$subscriberEmail = $_GET['email'];
try {
$result = $client->add_contact(
$api_key,
array (
'campaign' => $CAMPAIGN_ID,
'name' => $subscriberName,
'email' => $subscriberEmail,
'cycle_day' => '0'
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
}
?>
The script doesn't show any errors but GetResponse is not saving the lead to my list. Am I doing something wrong?
Thanks
James

If u are getting a response as [queued]=>1 then your script is working fine..
It will be added to your contact only after a validation/confirmation of entered email
$subscriberEmail will recieve a confirmation email...after the user click on the link contact will get added

This line is wrong:
'name' => $subscriberName,
because you have undefined variable and post it to then GetResponse API 'name' params without value so GetResponse API return Invalid params.
Change to:
$subscriberName => "Some_test_name", // for test only
In this line:
$subscriberEmail = $_GET['email'];
you should set some email in GET table maybe for test just change to:
$subscriberEmail = "test#domain.com"; // or sth like this.
Last idea is var_dump $result variable then you see response from GetResponse API
$result = null; // before try {
var_dump($result); // before end of function } ?>

Your code is looks good and You have to set the call back url for error handling

Related

Mailchimp PHP api v.2, User already exists or unsubscribe returns error

I'm using the Mailchimp v.2 API PHP wrapper to handle subscriptions... https://bitbucket.org/mailchimp/mailchimp-api-php however if a subscriber already exists on the list or the subscriber was unsubscribed, it returns an error, and I want to know a way I can code this to where if either of those cases exist, it will continue running the code without displaying an error. I apologize if this is a simple question.
$api_key = "XXXXXXXXX";
$list_id = "XXXXXX";
require('Mailchimp.php');
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$merge_vars = array('FNAME'=>htmlentities($_POST['stripeFirstName']), 'LNAME'=>htmlentities($_POST['stripeLastName']) );
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['stripeEmail']) ), $merge_vars );
You'll want to make use of try and catch. Mailchimp is pretty verbose about what goes wrong.
try {
$result = $Mailchimp_Lists->subscribe(
$list_id,
array(/* ... */), // primary subscriber data
array(/* ... */), // merge fields
'html', // email-type preference
false // double-opt-in
);
// Action for successful subscribe attempt.
} catch (\Exception $e) {
if ($e instanceof \Mailchimp_List_AlreadySubscribed) {
// In case they are already subscribed:
$errors[] = $e->getMessage();
} else {
// In case something else went wrong.
$errors[] = 'There was an error adding your email to the list. Would you mind trying again?';
}
// Debug time!
var_dump($errors);
}

PHP MusicBrainz get the first release date

i am trying to get the first release date of a song using Musicbrainz. To get this i am using the mikealmond musicBrainz library.
The problem i have is that when i try to execute exactly the same code as in this example (https://github.com/mikealmond/MusicBrainz/blob/master/examples/first-recording-search.php) i always get an authentication error.
Client error response [status code] 401 [reason phrase] Unauthorized [url] http://musicbrainz.org/ws/2/artist/0383dadf-2a4e-4d10-a46a-e9e041da8eb3?inc=releases+recordings+release-groups+user-ratings&fmt=json
Therefore i tried to add my username and password to the request:
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()),'myusername','mypassword');
$brainz->setUserAgent('myapplicationname', '0.2', 'http://localhost:443/');
If i call the url in the error message manually and enter my username and password i get the array i expect.
I just had a discovery: If I removed -"+ user - ratings"- it does not require authentication.
Therefore i commented the lines with "user - ratings" in my project
Now i think it works, but the performance of the query is very bad and often i get Error 503 // The MusicBrainz web server is currently busy. Please try again later. //
It takes a few seconds just for one song. Does someone know if this is normal or if i still have some kind of mistake?
My code....
//Create new MusicBrainz object
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()), 'username', 'password');
$brainz->setUserAgent('applicationname', '0.2', 'http://localhost:443/');
// set defaults
$artistId = null;
$songId = null;
$lastScore = null;
$firstRecording = array(
'releaseDate' => new DateTime()
);
// Set the search arguments to pass into the RecordingFilter
$args = array(
"recording" => 'we will rock you',
"artist" => 'Queen',
);
try {
// Find all the recordings that match the search and loop through them
$recordings = $brainz->search(new RecordingFilter($args));
$recorings i can print and in the loop i can print each $recording, but the error comes when i extract the informations
/** #var $recording \MusicBrainz\Recording */
foreach ($recordings as $recording) {
// if the recording has a lower score than the previous recording, stop the loop.
// This is because scores less than 100 usually don't match the search well
if (null != $lastScore && $recording->getScore() < $lastScore) {
break;
}
$lastScore = $recording->getScore();
$releaseDates = $recording->getReleaseDates();
$oldestReleaseKey = key($releaseDates);
if (strtoupper($recording->getArtist()->getName()) == strtoupper($args['artist'])
&& $releaseDates[$oldestReleaseKey] < $firstRecording['releaseDate']
) {
$firstRecording = array(
'releaseDate' => $recording->releases[$oldestReleaseKey]->getReleaseDate()
);
}
}
pr($firstRecording);
} catch (Exception $e) {
pr($e->getMessage());
}
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()), 'username', 'password');
You must set your MusicBrainz account credentials. Replace 'username' with your account username, and 'password' with the password used to login to MusicBrainz.org

twilio catching error does not work

I am implementing twilio in my laravel 5 application. To use it in the framework I use aloha/laravel-twilio integration.
Sending a valid request with test-credentials works fine. I have problems when I want to implement an error-handling.
For some reason the catch does not get the error, which results in a crash of the app. The error seems to be in the twilio-sdk if I read the error message correctly.
Here is what I've done so far:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Aloha\Twilio\TwilioInterface;
class Activation extends Model {
protected $fillable = array( 'a', 'b', 'c');
public static function send() {
// Testaccount
// $toNumber = '+15005550006'; // valid number; works fine
$toNumber = '+15005550001'; // #todo will throw an exeption, and breaks the app
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ ); // this is not called when an twilio error occurs
}
}
}
This results in the following error:
Whoops, looks like something went wrong.
Services_Twilio_RestException in /path/to/my/laravel/vendor/twilio/sdk/Services/Twilio.php line 297
Exception_message: The 'To' number +15005550001 is not a valid phone number.
From the documentation this error (not valid phone numer) shall be thrown, but I should have a possiblity to catch and process it. Currently, this does not work. I do not get the error catched...
How can I get the twilio-errors catched and processed?
The class is in a namespace, so I have to reference the absolut class exception - \Services_Twilio_RestException - in the catch .
It works with this code:
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( \Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ );
}
See below which is valid as of today. TwilioException is not valid and neither is Services_Twilio_RestException. You should use Exception instead.
UPDATE
You need to import Twilio\Exceptions\TwilioException for TwilioException to work.
My use case is I had to send to a database of numbers and not have an invalid phone number break my script. We did some work-around a month or two ago which involved logging when a message was sent and had a cron job checking where we left off every two minutes... not efficient when you're sending tens of thousands of text messages.
require_once '../Twilio/autoload.php'; // Loads the library
use Twilio\Rest\Client;
//some test fail numbers
$arr = array(1234567890,"11855976lend1",321619819815,198198195616516);
/* ==================================================================================
//create a function to send SMS using copilot (uses an SID instead of a phone number)
================================================================================*/
function sendSMS($to){
// Download the PHP helper library from twilio.com/docs/php/install
// These vars are your accountSid and authToken from twilio.com/user/account
$account_sid = 'xxx';
$auth_token = 'xxx';
$client = new Client($account_sid, $auth_token);
//this nifty little try/catch will save us pain when we encounter bad phone numbers
try{
$client->messages->create(
$to,
array(
'messagingServiceSid' => "MGxxx",
'body' => "This is the body we're sending."
)
);
//sent successfully
echo "sent to $to successfully<br>";
}catch(Exception $e){
echo $e->getCode() . ' : ' . $e->getMessage()."<br>";
}
}
foreach($arr as &$value){
sendSMS($value);
}
//remember to unset the pointer so you don't run into issues if re-using
unset($value);
Today (19-May-2017) the code is like this :
// Step 1: set our AccountSid and AuthToken from https://twilio.com/console
$AccountSid = "XXX";
$AuthToken = "XXX";
$client = new Client($AccountSid, $AuthToken);
try {
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 2: Change the 'From' number below to be a valid Twilio number
// that you've purchased
'from' => "+XXXXXXXXXXX",
// the sms body
'body' => $sms
)
);
// Display a confirmation message on the screen
echo "Sent message to $name";
} catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
This is what worked for me:
$twilioCli = new \Twilio\Rest\Client(config('app.twilioAccountSID'), config('app.twilioAuthToken'));
try {
$twilioCli->messages->create(
$formattedToNum,
[
'from' => config('app.twilioFromNumber'),
'body' => "sms body goes here"
]
);
}
catch (\Twilio\Exceptions\RestException $e) {
echo "Error sending SMS: ".$e->getCode() . ' : ' . $e->getMessage()."\n";
}

Magento update order shipping address

At the end of the purchase, the user has the possibility to change your shipping address. Im trying to update this information, but it dosen't work. This is my code:
$customer = Mage::getModel('customer/session')->getCustomer();
$order = Mage::getSingleton('checkout/session')->getLastOrder();
$postData = Mage::app()->getRequest()->getPost();
$_new_address = array (
'firstname' => $postData['nombre'],
'lastname' => $postData['apellidos'],
'street' => array ('0' => $postData['direccion']),
'city' => $postData['localidad'],
'region_id' => $postData['provincia_id'],
'region' => '',
'postcode' => $postData['codigo_postal'],
'country_id'=> 'ES',
'telephone' => $postData['telefono']
);
$customAddress = Mage::getModel('customer/address');
$customAddress->setData($_new_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
// Save address
try {
$customAddress->save();
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError($e->getMessage());
header('Location: /');
exit;
}
// Update the order
try {
$order->setShippingAddress($customAddress)->save();
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError($e->getMessage());
header('Location: /');
exit;
}
Can I update an order or is not allowed? Can anyone give me a tip?
My problem was that the Billing address and shipping address in the order, are different than having the user has as default addresses.
At the end the code looks like this:
$order = Mage::getSingleton('checkout/session')->getLastOrder();
$postData = Mage::app()->getRequest()->getPost();
// Try to get shipping and billing address data.
$orderShippingAddress = $order->getShippingAddress()->getId();
$orderShipping = Mage::getModel('sales/order_address')->load($orderShippingAddress);
$orderBillingAddress = $order->getBillingAddress()->getId();
$orderBilling = Mage::getModel('sales/order_address')->load($orderBillingAddress);
// Updating data.
$orderShipping->addData($postData);
$orderBilling->addData($postData);
try {
$orderShipping->implodeStreetAddress()->save();
$orderBilling->implodeStreetAddress()->save();
} catch (Exception $e) {
Mage::logException($e);
Mage::getSingleton('core/session')->addError($e->getMessage());
header('Location: /after/success/envio');
exit;
}
Now, it works. Thanks for your help #R.S
Assuming that you want to update the shipping address for an order, take a look # addressSaveAction() in /app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
$order = Mage::getSingleton('checkout/session')->getLastOrder();
//Get shipping address Id
$addressId = $order->getShippingAddress()->getId();
$address = Mage::getModel('sales/order_address')->load($addressId);
$data = $this->getRequest()->getPost();
$address->addData($data);
$address->implodeStreetAddress()->save();
Also i'm not sure if Mage::getSingleton('checkout/session')->getLastOrder() will still contain a valid order id after you submit your form since you will be loading a new page
While functioning correctly both other answers have an excessive address loading. The getShippingAddress already returns instance of sales/order_address. So the procedure can be simplified to following:
$order = Mage::getSingleton('checkout/session')->getLastOrder();
$data = $this->getRequest()->getPost();
$order->getShippingAddress()->addData($data)
->save();
Also implodeStreetAddress method call only required if you use multiline street address.

Salesforce API: Error on ->update(), "INVALID_TYPE: Must send a concrete entity type."

I've been researching this and trying many variations based off my understanding of how to update a record in an SObject, but I keep getting the following error:
SoapFault exception: [sf:INVALID_TYPE] INVALID_TYPE: Must send a concrete entity type. in /home/public_html/soapclient/SforceBaseClient.php:509
I am able to login successfully to the page, but when I execute the code below, I am getting the error listed above.
$fieldsToUpdate = array (
"Name"=>$_POST['Name']
);
$sObject = new SObject();
$sObject->Id = $_POST['prospectID']; // this is the Id of the record
$sObject->fields = $fieldsToUpdate;
$sObject->type = 'Prospect__c'; // this is the API name of custom object
try {
$response = $mySforceConnection->update($sObject);
} catch (Exception $e) {
echo $e;
}
I am using PHP Toolkit 13.0 from the Force.com developer docs, but not able to get to the bottom of this error. Also, I am using the Enterprise WSDL in sandbox mode, and have the proper wsdl xml assigned.
Thanks.
sObject is the base type for all other Salesforce objects that can be updated. When using the enterprise API (SOAP), you'll need to pass instances that derive from sObject. (Lead, Contact, and Account are examples)
Here is the documentation for the update() method as well.
You need to supply an object type as the second update() argument. Also, the first argument of the update() method must be an array of objects you'd like to update:
$response = $mySforceConnection->update(array($object), 'Prospect__c');
Also, you do not need to use any object classes provided by the toolkit, a simple StdClass should work:
$prospect = new StdClass();
$prospect->Id = '006....';
$prospect->Name 'Foobar';
$response = $mySforceConnection->update(array($prospect), 'Prospect__c');
FYI, I have never found a way to update multiple object types at once, but you can update a batch of the same type of objects, hence why the first parameter needs to be an array. The Salesforce toolkit doesn't automatically account for someone passing a single object (i.e. it doesn't wrap it in an array for you). I have always used an abstraction layer between my application logic and Salesforce's SOAP toolkit, which provides conveniences like I just described.
if your are using Partner wsdl
<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.com password
define("SOAP_CLIENT_BASEDIR", "../../soapclient");
require_once (SOAP_CLIENT_BASEDIR.'/SforcePartnerClient.php');
require_once ('../userAuth.php');
try {
$mySforceConnection = new SforcePartnerClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR.'/partner.wsdl.xml');
$mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
/*--------------------------------------------------------\
| Please manage the values for OBJECT ID from file
| userAuth.php
\--------------------------------------------------------*/
$fieldsToUpdate = array (
'FirstName' => 'testupdate',
'City' => 'testupdateCity',
'Country' => 'US'
);
$sObject1 = new SObject();
$sObject1->fields = $fieldsToUpdate;
$sObject1->type = 'Lead';
$sObject1->Id = $UPDATEOBJECTID1;
$fieldsToUpdate = array (
'FirstName' => 'testupdate',
'City' => 'testupdate',
'State' => 'testupdate',
'Country' => 'US'
);
$sObject2 = new SObject();
$sObject2->fields = $fieldsToUpdate;
$sObject2->type = 'Lead';
$sObject2->Id = $UPDATEOBJECTID2;
$sObject2->fieldsToNull = array('Fax', 'Email');
$response = $mySforceConnection->update(array ($sObject1, $sObject2));
print_r($response);
} catch (Exception $e) {
print_r($mySforceConnection->getLastRequest());
echo $e->faultstring;
}
?>
else for enterprises wsdl use
<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.com password
define("SOAP_CLIENT_BASEDIR", "../../soapclient");
require_once (SOAP_CLIENT_BASEDIR.'/SforceEnterpriseClient.php');
require_once ('../userAuth.php');
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR.'/enterprise.wsdl.xml');
$mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
/*--------------------------------------------------------\
| Please manage the values for OBJECT ID from file
| userAuth.php
\--------------------------------------------------------*/
$sObject1 = new stdclass();
$sObject1->Id = $UPDATEOBJECTID1;
$sObject1->FirstName = 'testupdate';
$sObject1->City = 'testupdateCity';
$sObject1->Country = 'US';
$sObject2 = new stdclass();
$sObject2->Id = $UPDATEOBJECTID2;
$sObject2->FirstName = 'testupdate';
$sObject2->City = 'testupdate';
$sObject2->State = 'testupdate';
$sObject2->Country = 'US';
$sObject2->fieldsToNull = array('Fax', 'Email');
$response = $mySforceConnection->update(array ($sObject1, $sObject2), 'Lead');
print_r($response);
} catch (Exception $e) {
print_r($mySforceConnection->getLastRequest());
echo $e->faultstring;
}
?>

Categories