Issues with sending $_POST data to an outside server via cURL - php

The company I work for stores contacts into a 1shoppingcart database. We recently signed up for FreshAddress to validate emails before the information is sent to 1shoppingcart.
In order to get this information to 1shoppingcart I stored the name in a session - since it seemed that after the validation script ran that it cleared any form data aside from the email address it was validating, and the remaining hidden values that would normally be in the form as hidden input fields.
Everything transfers over except for the second ar variable. This is how it would normally look inside the form itself:
<input name="ar" type="hidden" id="ar" value="000000">
<input name="ar" type="hidden" id="ar" value="000000">
<input name="ar" type="hidden" id="ar" value="000000">
In order to send the information over I stored what normally would be hidden values in the form as php variables and placed them into an array to be sent over through. Again, the name, e-mail and everything else works except that $ar2 is not being stored for some reason. Here is the code I have:
if($submitPage === true) {
$name = $_SESSION['Name'];
$email = $_POST['Email1'];
$merchId = '000000';
$arTY = 'Url to redirect goes here';
$copyarresponse = '0';
$custom = '0';
$ar1 = '000000';
$ar2 = '000000';
$ar3 = '000000';
$allwMulti = '0';
$visiblefields = 'Name, Email1';
$requiredFields = 'Name, Email';
// where are we posting to?
$url = 'http://www.mcssl.com/app/contactsave.asp';
// what post fields?
$fields = array(
'merchantid' => $merchId,
'ARThankyouURL' => $arTY,
'copyarresponse' => $copyarresponse,
'custom' => $custom,
'ar' => $ar1, $ar2, $ar3,
'allowmulti' => $allwMulti,
'visiblefields' => $visiblefields,
'requiredfields' => $requiredFields,
'Name' => $name,
'Email1' => $email
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);
session_destroy();
}
The code basically runs when the e-mail that has been validated, returns as safe to send and $submitPage is set to true.
I have looked through this forum and various other sources online as well as contacted 1shoppingcart and fresh address and have had no luck as to what could possibly be preventing the second ar variable from being stored.
Any help would be much appreciated!

Related

Why is HubSpot Autogenerating Forms?

I am submitting a contact form to HubSpot using their api (https://developers.hubspot.com/docs/methods/forms/submit_form), which is working out great, except that every time I do it, HubSpot autogenerates a new form in its site under Marketing -> Forms, with a name like #form_5dd7ee368739f. It says that this is a non-Hubspot form and gives this explanation:
What is a non-HubSpot form
Non-HubSpot forms are HTML forms on your
website that weren't created in HubSpot. Based on your settings,
data for these forms is automatically collected in HubSpot. Learn
more.
"Learn more" isn't a link; I can't click on it. The submission of the api request is recorded both in this new form that it autogenerated each time the form is submitted, as well as in the form that I built in HubSpot that supposed to handle this request. Here is my code:
<?php
// wp-config.php
define('HUBSPOT_PORTAL_ID', getenv('hubspot_portal_id'));
define('HUBSPOT_CONTACT_FORM_GUID', getenv('hubspot_contact_form_guid'));
define('HUBSPOT_CONTACT_FORM_ENDPOINT', "https://forms.hubspot.com/uploads/form/v2/".HUBSPOT_PORTAL_ID."/{form_guid}");
?>
<?php
// hubspot.php
function hubspot_form_submit($page_url, $page_name, $endpoint, $data) {
$hs_context = array(
'ipAddress' => $_SERVER['REMOTE_ADDR'],
'pageUrl' => $page_url,
'pageName' => $page_name,
);
if (array_key_exists('hubspotutk', $_COOKIE)) {
$hs_context['hutk'] = $_COOKIE['hubspotutk'];
}
$data['hs_context'] = $hs_context;
$data_string = "";
foreach ($data as $key => $value) {
if (is_string($value)) {
$value = urlencode($value);
}
else if (is_array($value)) {
$value = json_encode($value);
}
$data_string = $data_string.$key."=".$value."&";
}
$data = rtrim($data_string, "&");
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
#curl_setopt($ch, CURLOPT_URL, $endpoint);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = #curl_exec($ch);
if(curl_error($ch)) {
$result = curl_error($curl);
}
$status_code = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
#curl_close($ch);
return $result;
}
?>
<?php
// contact.php
require_once("inc/hubspot.php");
$hubspot_form_submission = hubspot_form_submit(
"https://www.example.com/contact/",
"Contact",
str_replace("{form_guid}", HUBSPOT_CONTACT_FORM_GUID, HUBSPOT_CONTACT_FORM_ENDPOINT),
array(
"firstname" => $form->data["first_name"],
"lastname" => $form->data["last_name"],
"email" => $form->data["email"],
"phone" => $form->data["phone"],
"preferred_contact_method" => $form->data["contact_method"],
"message" => $form->data["comments"],
)
);
?>
Anyone know how I can prevent HubSpot from autogenerating these forms? Otherwise my forms box will quickly become filled up with hundreds of autogenerated forms that I will keep having to delete. Something to note: the actual form that I created for this purpose is located within a folder, whereas the autogenerated forms are always located outside of any folders, if that makes any difference.
Found the problem: the client had enabled the use of Non-HubSpot forms in their settings, so all that is required to fix it is just to turn this functionality off. The documentation is here:
https://knowledge.hubspot.com/forms/use-non-hubspot-forms
The setting is located in
Settings -> Marketing -> Forms -> Non-HubSpot Forms

Contact form 7, post data to seperate php file

Im using CF7 to get user details.
When user submit his form, i wanna get the input fields to my custom.php file and do some stuff in there.
I tried doing that with the js on_sent_ok: URL/custom.php?.....fields data.... but i think this is not the right method. But anyway that is working for me.
Is there a way to do that with hook action? I tried this.
function wpcf7_do_something (&$cfdata) {
$goURL = 'http://contactform7.com';
$cfdata->set_properties( array( 'additional_settings' => "on_sent_ok: \"location = '".$goURL."';\"" ) );
}
add_action("wpcf7_before_send_mail", "wpcf7_do_something");
I tried to echo something , triger a js console.log, and to redirect inside the wpcf7_do_something function but nothing is works. I really dont know if it works at all.
Is there a way to test if this action is working?
Is there a way to redirect to onother location?
Thnx
Once you forward the user after a successful submission, your form data is lost. You can intercept the form data processing in WP by hooking into the before_send_mail action hook provided by CF7. This allows you to access the form data on the server, preprocess it if necessary, and then POST the data to your custom processor script.
// Create the new wordpress action hook before sending the email from CF7
add_action( 'wpcf7_before_send_mail', 'my_conversion' );
function my_conversion( $contact_form ) {
$submission = WPCF7_Submission::get_instance();
// Get the post data and other post meta values.
if ( $submission ) {
$posted_data = $submission->get_posted_data();
// these variables are examples of other things you may want to pass to your custom handler
$remote_ip = $submission->get_meta( 'remote_ip' );
$url = $submission->get_meta( 'url' );
$timestamp = gmdate("Y-m-d H:i:s", $submission->get_meta( 'timestamp' ));
$title = wpcf7_special_mail_tag( '', '_post_title', '' );
// If you have checkboxes or other multi-select fields, make sure you convert the values to a string
$mycheckbox1 = implode(", ", $posted_data["checkbox-465"]);
$mycheckbox2 = implode(", ", $posted_data["checkbox-466"]);
// Encode the data in a new array in JSON format
$data = json_encode(array(
"posted_key_name_1" => "{$posted_data['input-name-1']}",
"posted_key_name_2" => "{$posted_data['input-name-2']}",
"posted_key_name_..." => "{$posted_data['input-name-...']}",
"posted_key_name_n" => "{$posted_data['input-name-n']}",
// any additional data to include that wasn't part of the form post?
"From URL" => "$url",
"From IP" => "$remote_ip",
"Page Title" => "$title"
));
// Finally send the data to your custom endpoint
$ch = curl_init("https://www.YOURDOMAIN.com/custom.php");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); //Optional timeout value
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //Optional timeout value
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
}
This will post the selected form data to your custom processor right before CF7 processes the form and sends the confirmation mail. You'll still want to make sure the user experience is satisfactory by either displaying the CF7 confirmation message that the form has been submitted, or forwarding the user to a thank you page using the JS redirect -> on_sent_ok: https://yourdomain.com/thanks/
If it is necessary that the user visits your custom processor page because the processor page generates information important to the user, you could package up all the form data into a URL string and append that onto the processing URL. Then, in your processing.php code, you'd use $_GET[] to access the data.
See this article for details on how to dynamically update set the redirect URL: How to change contact form 7 Redirecting URL dynamically - WordPress
Submitting data to a webhook code from this page: http://moometric.com/integrations/wp/contact-form-7-zapier-webhook-json-post/

salesforce api add leads from form

I am trying to add leads from my contact form to salesforce. Currently I am using this solution that passes them through what I assume is the Web-to-Lead solution they have:
if (isset($_POST['submit'])) {
$ch_register_first_name = $_POST['ch_register_first_name'];
$ch_register_last_name = $_POST['ch_register_last_name'];
$ch_register_dob = $_POST['ch_register_dob'];
$ch_register_phone = $_POST['ch_register_phone'];
$ch_register_email = $_POST['ch_register_email'];
$ch_register_street = $_POST['ch_register_street'];
$ch_register_street2 = $_POST['ch_register_street2'];
$ch_register_city = $_POST['ch_register_city'];
$ch_register_state = $_POST['ch_register_state'];
$ch_register_zip = $_POST['ch_register_zip'];
//set POST variables
$url = 'https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';
$fields = array(
'last_name'=>urlencode($ch_register_first_name),
'first_name'=>urlencode($ch_register_last_name),
'street'=>urlencode($ch_register_street),
'city'=>urlencode($ch_register_city),
'state'=>urlencode($ch_register_state),
'zip'=>urlencode($ch_register_zip),
'company'=>urlencode($company),
'description'=>urlencode($ch_register_dob),
'email'=>urlencode($ch_register_phone),
'phone'=>urlencode($ch_register_email),
'mycustomefieldid' => urlencode($ch_register_dob), // custom field
'oid' => $ch_register_salesforce_id, // insert with your id
'retURL' => urlencode('http://thank-you/'), // sending this just in case
'debug' => '1',
'debugEmail' => urlencode("email#email.com"), // your debugging email
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, TRUE);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
}
The issue by doing this (if I am correct that its using the Web-to-Lead solution) the max limit is 500 in 24hrs. Some events this form will be used at day of will have more than 500 for sure. How can I use just their API I have read about? Or should I save the locally to the database then run a batch using the Force api?

How to authenticate the post using curl?

I have two sites one is a.com another is b.com i am passing data using curl from a.com to b.com ,i am successfully able to pass data but the problem is i want to make it more secure so that site b.com responses after ensuring that the post was from site a.com.How to obtain this?
Code in site a.com
<?php
$some_data = array(
'message' =--> 'Hello World',
'name' => 'Chad'
);
$curl = curl_init();
// You can also set the URL you want to communicate with by doing this:
// $curl = curl_init('http://localhost/echoservice');
// We POST the data
curl_setopt($curl, CURLOPT_POST, 1);
// Set the url path we want to call
curl_setopt($curl, CURLOPT_URL, 'http://localhost/b.com');
// Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Insert the data
curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data);
// You can also bunch the above commands into an array if you choose using: curl_setopt_array
// Send the request
$result = curl_exec($curl);
// Free up the resources $curl is using
curl_close($curl);
echo $result;
?>
Code in B.com
//I want to check here that the request was from a.com ,if it is ensured then i want to do //the rest of the work
echo 'Your message was: ' . $_REQUEST["message"] . ' and your name is: ' . $_REQUEST["name"];
?
You could check the $_SERVER['REFERER'] property, but it's very unreliable / unsafe.
A better approach would be to set up the B site with Basic Auth, or something similar, that you can authenticate against when you make the request from site A. Then you can add basic auth to your curl request from A to B. B checks the authentication, and if correct proceeds with the rest of the processing.
$_SERVER['REMOTE_ADDR'] would be the solution
if($_SERVER['REMOTE_ADDR']=="IP OF A.com"){
//exec code
}else{
log_error($_SERVER['REMOTE_ADDR'] has tried to access B.com at date());//that's an ex .
}
The simplest way to achive this, would be to create a Key that site a.com know and site b.com knows.
Then you could pass the key from one server to the other via curl, and as long as know one else knows what the key is they won't be able to access it (assuming you program it that way).
This is how most API's work, such as Facebook, Twitter, Linkedin, etc.
Your post data would then look like this for example (a.com):
$some_data = array(
'message' =--> 'Hello World',
'name' => 'Chad',
'key' => '4h9rj8wj49tj0wgj0ejwrkw0jt0ekv0ijspxodxk9rje0rg9tskvep9rrgt9wkrgte'
);
Then on b.com you would just do this:
if(!isset($_POST['key']) && $_POST['key'] != '4h9rj8wj49tj0wgj0ejwrkw0jt0ekv0ijspxodxk9rje0rg9tskvep9rrgt9wkrgte'){
die("Invalid Key");
}
You can use a public/private pair system. A simple version would be like this:
//a.com
$keys = array(
'publicKey1' => 'privateKey1',
'publicKey2' => 'privateKey2',
//...
'ksjdlfksjdlf' => '989384kjd90903#kjskdjdsd'
);
$publicKeys = array_keys($keys);
//get a random key from pool
$publicKey = $publicKeys[rand(0, count($publicKeys))];
$privateKey = $keys[$publicKey];
//your data...
$some_data = array(
'message' => 'Hello World',
'name' => 'Chad'
);
/*generate a verification code from data...*/
//add public key to data
$some_data['key'] = $publicKey;
//sort data (to always generate same verification code regardless of params order)
uksort($some_data);
//generate code with your private key
$verificationKey = sha1($privateKey . http_build_query($some_data) . $privateKey);
//add verification code to sent data
$some_data['verification_code'] = $verificationKey;
//send data
curl_exec(...);
and on b.com:
$keys = "same keys that exist on a.com";
if (!isset($_POST['key']) || !isset($_POST['verification_code']) || !isset($keys[$_POST['key'])) {
//do something to handle invalid request
}
$verificationKey = $_POST['verification_code'];
$privateKey = $keys[$_POST['key']];
//remove verification code from data
unset($_POST['verification_code']);
//sort data
uksort($_POST);
$checkKey = sha1($privateKey . http_build_query($_POST) . $privateKey);
//validate key
if ($checkKey != $verificationKey) {
//handle invalid data
}
//verified. do something with $_POST

How to post a variable with a number for name

I know this is bad form, but we can't change the hidden input name as it is set by SalesForce. I have a form with an input like this:
<input type="hidden" name="00N5000000XXXXX" value="Demo_Account" />
and my PHP to post to them via cURL
$00N5000000XXXXX = $_POST['00N5000000XXXXX'];
which obviously won't work as it has number for a variable name.
When I change the name to:
$Foo = $_POST['00N5000000XXXXX'];
the back end doesn't work because it is expecting the form to submit a value with a name of 00N5000000XXXXX, not Foo or whatever I want to call it.
Obviously, Im not a PHP developer but need some advice on how to get around this.
Thank you.
You don't have to save it to a variable first:
<?php
$transferPostFields = array(
'00N5000000XXXXX'
);
$postFields = array();
foreach ($_POST as $key => $value) {
if (in_array($key, $transferPostFields)) {
$postFields[$key] = $value;
}
}
$curlHandle = curl_init();
curl_setopt_array($curlHandle, array(
CURLOPT_URL => 'http://api.salesforce.com/whatever/urls/they/use',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($postFields)
));
$output = curl_exec($curlHandle);
echo 'The output we received from SalesForce was: ' . $output;
?>
If you want to transfer all post fields, simply change the top part (anything above $curlHandle = curl_init() to:
$postFields = $_POST;
If you don't need to go past your own server first, then simply change your form:
<form method="post" action="http://api.salesforce.com/whatever/urls/they/use">

Categories