Clicking an icon on a webpage triggers a jQuery AJAX call to a PHP script that synchs a local database to a SugarCRM database using SOAP.
By sending myself emails before and after the problematic statements, I can see that the SOAP connection succeeds, but the ensuing login() fails without throwing a SoapFault or a normal Exception.
From the command line, it works.
Thanks in advance for any suggestions
UPDATE: some code...
//Javascript from the webpage
url = 'http://apps.net/synch_with_CRM.php?clientGuid=141516'
// Submit via Ajax if there aren't any errors
jQuery.ajax({
url: url,
success: function(){
jQuery("#dialog-message").dialog({
buttons: {
Ok: function() {
jQuery(this).dialog('close'); /* Closes popup */
}
}
})
jQuery( "#loading_" + crm ).hide();
jQuery( "#icon_sync_" + crm ).show();
}
});
// PHP code from .../apps.net/synch_with_CRM.php
<?php
if ( $_REQUEST['clientGuid'] ) { # get the URL parameter
$client_guid = $_REQUEST['clientGuid'];
}
else if ( $argv ) { # get the command-line parameter
$client_guid = $argv[$argc - 1]; # clientGuid must be last
}
$client = new Client( $client_guid );
$client_id = $client->GetId( );
# connection information is the same for AJAX or command-line
$connection_info = getConnectionInfo( $client_id, 'SugarCRM' );
$API_soap_client = get_connection( $connection_info );
if ( !$API_soap_client ) {
exit( "SOAP client connection failed\n" );
}
# do other stuff here...
# SNIP!
function get_connection( $connection_info ) {
global $soap_session_id;
try {
$options = array( 'location' => $connection_info['url'],
'uri' => $connection_info['uri'],
'trace' => 1 );
$auth_array = array( 'user_name' => $connection_info['username'],
'password' => md5( $connection_info['password'] ) );
$API_soap_client = new soapclient( NULL, $options );
# I get the following email whether by AJAX or command-line
mail( 'programmer#apps.net', 'soapclient', print_r( $API_soap_client, true ) );
$soap_session = $API_soap_client->login( $auth_array );
# I only get this email if the script is run from the command-line
mail( 'programmer#apps.net', 'soap id', print_r( $soap_session, true ) );
$soap_session_id = $soap_session->id;
if ( $soap_session_id != -1 ) return $API_soap_client;
else return false;
}
catch( SoapFault $fault ) { # there is no SoapFault thrown
mail( 'programmer#apps.net', 'soap fault', print_r( $fault, true ) );
}
catch( Exception $e ) { # there is no Exception thrown
mail( 'programmer#apps.net', 'exception', print_r( $e, true ) );
}
} # end get_connection
?>
Anyway you could post some code to highlight the issue? Also, you may want to try doing it over REST versus SOAP since REST will be much faster.
Related
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);
}
Here's my issue, I have contact form 7 for wordpress installed and during the wpcf7_before_send_mail I make a call to an API, I need to invalidate the form if the API returns an error then I need to invalidate the request and return the error passed back from the API call.
I set a flag to false on API failure and the error message is also stored but my form is going through as success despite the failure I induce.
add_action("wpcf7_before_send_mail", "wpcf7_send_contact_builder");
function wpcf7_send_contact_builder($form) {
$submission = WPCF7_Submission::get_instance();
$wpcf7_data = $submission->get_posted_data();
... api call and set $success to true if ok and false if not ...
if (!$success) {
$form->status = 'validation_failed (statuscode:' . $xml->status->statuscode[0] . ').';
$form->valid = false;
$form->response = $xml->status->statusdesc[0];
return $forml
}
}
I've also tried using:
$form->invalidate('validation_failed (statuscode:' . $xml->status->statuscode[0] . ').', $xml->status->statusdesc[0]);
But whichever way I am unable to prevent the success email being sent and the form validates as successful. Debugging proved that the !success in the if statement is working and the code contained is added to the variable. I also tried as if form was an array ($form['valid'] = false) but this also didn't work and the form submits as successful. Any ideas of what I'm missing here? I've omitted the code for the API call itself and the determining of the correct form id, both of these work correctly, only the form I'm after is parsed and the API call is returning the expected data.
I needed the same. After going through the CF7 plugin files, I found the following solution:
//To make it working, we must need at least CF7-v5.0;
add_action( 'wpcf7_before_send_mail', 'cf7_validate_api', 15, 3 );
function cf7_validate_api($cf7, &$abort, $submission){
if ( $cf7->id() !== 789 ) //CF7 post-id from admin settings;
return;
$errMsg = '';
//$submission = WPCF7_Submission::get_instance();
$postedData = $submission->get_posted_data();
//$postedData['more-data'] = 'something';
unset($postedData['not-sending-data']);
//-----API posting------
$url = "http://my-web.com/wp-admin/admin-ajax.php?action=get-something";
$username = 'apiUserName';
$password = 'apiUserPass';
$args = [
'headers' => [
'Authorization' => "Basic ".base64_encode( $username . ':' . $password ),
'Accept' => 'application/json; charset=utf-8', // The API returns JSON
//'Content-Type' => 'application/json; charset=utf-8'
],
'body' => $postedData
];
$response = wp_remote_post( $url, $args );
//------------------
if( is_wp_error( $response ) ){
$error_message = $response->get_error_message();
$errMsg = "Something went wrong:\n{$error_message}";
} else {
$response_body = wp_remote_retrieve_body( $response );
$data = json_decode( $response_body );
if( empty($data) || $data->status==0 ){ //API validation error!
$errMsg = $data->msg->title."\n".$data->msg->description;
}
}
if( $errMsg ){ //do not send mail;
//$cf7->skip_mail = true; //for older versions!
$abort = true; //==> Here, it is with 'called by reference' since CF7-v5.0 :)
$submission->set_status( 'validation_failed' );
//$submission->set_response( $cf7->message( 'validation_error' ) ); //msg from admin settings;
$submission->set_response( $cf7->filter_message($errMsg) ); //custom msg;
}
}
Hopefully, it will help someone. Happy Coding :)
i want to use http://graph.facebook.com/XXX in my site
how i do a php file that have use this system and show my facebook details when i enter the link?
XXX = userrname
i want that the site show the details of the facebook user that enter the site
i tried everything but nothing, i dont want to make ap like this:
<?php
session_start();
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
$api_key = 'FACEBOOK_APP_ID';
$api_secret = 'FACEBOOK_APP_SECRET';
$redirect_login_url = 'http://www.yoursite.com/somefolder/file.php';
// https://www.webniraj.com/2014/05/01/facebook-api-php-sdk-updated-to-v4-0-0/
// initialize your app using your key and secret
FacebookSession::setDefaultApplication($api_key, $api_secret);
// create a helper opject which is needed to create a login URL
// the $redirect_login_url is the page a visitor will come to after login
$helper = new FacebookRedirectLoginHelper( $redirect_login_url);
// First check if this is an existing PHP session
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from the existing PHP sesson
$session = new FacebookSession( $_SESSION['fb_token'] );
try {
// validate the access_token to make sure it's still valid
if ( !$session->validate() ) $session = null;
} catch ( Exception $e ) {
// catch any exceptions and set the sesson null
$session = null;
echo 'No session: '.$e->getMessage();
}
} elseif ( empty( $session ) ) {
// the session is empty, we create a new one
try {
// the visitor is redirected from the login, let's pickup the session
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $e ) {
// Facebook has returned an error
echo 'Facebook (session) request error: '.$e->getMessage();
} catch( Exception $e ) {
// Any other error
echo 'Other (session) request error: '.$e->getMessage();
}
}
if ( isset( $session ) ) {
// store the session token into a PHP session
$_SESSION['fb_token'] = $session->getToken();
// and create a new Facebook session using the cururent token
// or from the new token we got after login
$session = new FacebookSession( $session->getToken() );
try {
// with this session I will post a message to my own timeline
$request = new FacebookRequest(
$session,
'POST',
'/me/feed',
array(
'link' => 'www.finalwebsites.com/facebook-api-php-tutorial/',
'message' => 'A step by step tutorial on how to use Facebook PHP SDK v4.0'
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
// the POST response object
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
$msgid = $graphObject->getProperty('id');
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (post) request error: '.$e->getMessage();
}
// now we create a second request to get the posted message in return
if ( isset ( $msgid ) ) {
// we only need to the sec. part of this ID
$parts = explode('_', $msgid);
try {
$request2 = new FacebookRequest(
$session,
'GET',
'/'.$parts[1]
);
$response2 = $request2->execute();
$graphObject2 = $response2->getGraphObject();
// the GET response object
echo '<pre>' . print_r( $graphObject2, 1 ) . '</pre>';
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (get) request error: '.$e->getMessage();
}
}
} else {
// we need to create a new session, provide a login link
echo 'No session, please login.';
}
// use this for testing only
//unset($_SESSION['fb_token']);
thanks,
mtj
I'm using artdarek/oauth-4-laravel so the user can login via Facebook and post to their feed. I'm able to login in via Facebook using the following bit of code
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
$token = $fb->requestAccessToken( $code );
$_SESSION['facebook_access_token'] = $token->getAccessToken();
// Send a request with it
$user = json_decode( $fb->request( '/me' ), true );
...
And everything works as expected. In the App I also have a share button, but when I try and share I get the following error
{"error":{"type":"OAuth\\Common\\Http\\Exception\\TokenResponseException","message":"Failed to request resource.","file":"\/var\/www\/html\/myApp\/vendor\/lusitanian\/oauth\/src\/OAuth\/Common\/Http\/Client\/StreamClient.php","line":68}}
Here is the code that I'm using for posting
if ( isset($_SESSION['facebook_access_token']) ) {
$fb = OAuth::consumer( 'Facebook' );
// $user = json_decode( $fb->request( "/me?access_token={$_SESSION['facebook_access_token']}" ), true );
$postMessage = json_decode( $fb->request
(
'POST',
"/me/feed?access_token={$_SESSION['facebook_access_token']}",
array (
'message' => 'This is a test message'
)
),
true );
return $postMessage;
}
I know that the $_SESSION[] is set because I ran the commented out line first and it was returning what I expected. But the code for posting on the wall is giving me that error mentioned earlier.
Please help.
Thanks
I found the mistake ... The call is supposed to be as follows
$postMessage = json_decode( $fb->request
(
"/me/feed?access_token={$_SESSION['facebook_access_token']}",
'POST',
array (
'message' => 'This is a test message'
)
),
true );
The route is supposed to be first and then the POST.
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