Passing and Parse PayPal IPN Custom field - php

I have setup a PayPal IPN file. When the user is at the site and press submit details about the transaction is uploaded to the db. The relevant id is sent via PayPal as the custom field. When payment complete IPN used to update DB as transaction completed based on id.
All is fine.
However, this is the tricky bit. I also need to update another table - a discount/coupon code db. The update is based on the code entered and also the number of times the code can still be used. Basically if it was 50 times, after used once the db would be updated with 49. So I need to pass the code and the remaining uses allowed so can say update table where code = XXXX (update new value of 49 etc).
I can work out how to pass all these values in the custom field, but cannot work out how to parse them out again? Read about separating them with : etc, but need some advice from someone who has done before.
This is how IPN details currently comes back:
$custom = $_POST['custom'];
Thank you.

I did just this recently,
Send your paypal custom field to data as your would, inside that custom field, use a separator to split your data.
In the below example, the values are split using a "|", you can use any character you want available in your charset.
$member_id = 1;
$some_other_id = 2;
<input type="hidden" name="custom" value="<?php echo $member_id.'|'.$some_other_id ?>"/>
This will output:
<input type="hidden" name="custom" value="1|2"/>
When you get the information from paypal (the IPN response) process it like so:
$ids = explode('|', $_POST['custom']); // Split up our string by '|'
// Now $ids is an array containing your 2 values in the order you put them.
$member_id = $ids[0]; // Our member id was the first value in the hidden custom field
$some_other_ud = $ids[1]; // some_other_id was the second value in our string.
So basically, we send a string with a custom delimiter that we choose to paypal, paypal will return it to us in the IPN response. We then need to split it up (using the explode() function) and then do what you would like with it.
When you get your value from the database your select it using normal methods, then just decrement it by 1 using:
$val_from_db--; // Thats it!, Takes the current number, and minus 1 from it.

This expands on JustAnil's solution.
HTML:
<input type="hidden" name="custom" value="some-id=1&some-type=2&some-thing=xyz"/>
and your IPN script would look something like this:
<?php
parse_str($_POST['custom'],$_CUSTOMPOST);
echo $_CUSTOMPOST['some-id'];
echo $_CUSTOMPOST['some-type'];
echo $_CUSTOMPOST['some-price'];
?>
You may want to double check that parse_str performs urldecode on resulting array elements.

Here is an example using JSON:
<?php
$arr = array($member_id, $coupon);
$data = json_encode($arr);
?>
<input type="hidden" name="custom" value="<?= $data ?>"/>
Then on the other side:
$custom = json_decode($_POST['custom'], true);
$member_id = $custom[0];
$coupon = $custom[1];
You can also parse associative arrays too:
<?php
$arr = array('id' => $member_id, 'coupon' => $coupon);
$data = json_encode($arr);
?>
<input type="hidden" name="custom" value="<?= $data ?>"/>
Then on the other side:
$custom = json_decode($_POST['custom'], true);
$member_id = $custom['id'];
$coupon = $custom['coupon'];
There's a nice symmetry when using JSON to parse the data.

Related

How to Send Multiple Variables Through PayPal IPN

This is the flow of customers:
Visit Website -> Fill Out Form With Their Info -> Click "Buy Now" and Checkout with PayPal -> Be Returned Back To The Website -> Use Information Passed From Checkout From to Run PHP script on server via ajax (assuming the checkout was successful). Well, that's the plan anyways. The problem I am having is figuring out how to actually pass the variables (there are 8 total... array???. I currently have a quick checkout button on the website, which redirects the user away to PayPal to complete the transaction. I've been searching for a good tutorial on YouTube or here at S.O., but have been unsuccessful. Any ideas how I may accomplish this?
Thanks
In your PayPal form, simply use something like the following for your custom field..
Example:
<input type="hidden" name="custom" value="<?php echo $custom1.','.$custom2.','.$custom3; ?>">
or;
<input type="hidden" name="custom" value="custom1,custom2,custom3">
In short the custom name is accepted by PayPal, and you would use commas to separate the variables.
PayPal will pass the custom field back to you, in the IPN.
EDIT:
Here's an example of what you might do with custom:
$custom = $_POST['custom'];
$pattern = ",";
$pieces = explode($pattern,$custom, 3);
// 3 is how many custom fields there are
$custom1 = $pieces[0];
$custom2 = $pieces[1];
if (isset($pieces[2])) {
//an example checking to see if there is a third custom variable
$custom3 = $pieces[2];
}
You can use json to pass multiple values via the custom variable in PayPal..
Create your values:
$custom = array();
$custom['value1'] = "foo";
$custom['value2'] = "bar";
$custom = json_encode($custom);
Then you can POST this data to somewhere:
<input type="hidden" name="custom" value="<?php echo htmlentities($custom) ?>"/>
then get the data from somewhere like this:
$data = json_decode($_POST['custom']);
echo $data->value2;
The output should be bar

Save variables until redirected back on PHP [duplicate]

I have setup a PayPal IPN file. When the user is at the site and press submit details about the transaction is uploaded to the db. The relevant id is sent via PayPal as the custom field. When payment complete IPN used to update DB as transaction completed based on id.
All is fine.
However, this is the tricky bit. I also need to update another table - a discount/coupon code db. The update is based on the code entered and also the number of times the code can still be used. Basically if it was 50 times, after used once the db would be updated with 49. So I need to pass the code and the remaining uses allowed so can say update table where code = XXXX (update new value of 49 etc).
I can work out how to pass all these values in the custom field, but cannot work out how to parse them out again? Read about separating them with : etc, but need some advice from someone who has done before.
This is how IPN details currently comes back:
$custom = $_POST['custom'];
Thank you.
I did just this recently,
Send your paypal custom field to data as your would, inside that custom field, use a separator to split your data.
In the below example, the values are split using a "|", you can use any character you want available in your charset.
$member_id = 1;
$some_other_id = 2;
<input type="hidden" name="custom" value="<?php echo $member_id.'|'.$some_other_id ?>"/>
This will output:
<input type="hidden" name="custom" value="1|2"/>
When you get the information from paypal (the IPN response) process it like so:
$ids = explode('|', $_POST['custom']); // Split up our string by '|'
// Now $ids is an array containing your 2 values in the order you put them.
$member_id = $ids[0]; // Our member id was the first value in the hidden custom field
$some_other_ud = $ids[1]; // some_other_id was the second value in our string.
So basically, we send a string with a custom delimiter that we choose to paypal, paypal will return it to us in the IPN response. We then need to split it up (using the explode() function) and then do what you would like with it.
When you get your value from the database your select it using normal methods, then just decrement it by 1 using:
$val_from_db--; // Thats it!, Takes the current number, and minus 1 from it.
This expands on JustAnil's solution.
HTML:
<input type="hidden" name="custom" value="some-id=1&some-type=2&some-thing=xyz"/>
and your IPN script would look something like this:
<?php
parse_str($_POST['custom'],$_CUSTOMPOST);
echo $_CUSTOMPOST['some-id'];
echo $_CUSTOMPOST['some-type'];
echo $_CUSTOMPOST['some-price'];
?>
You may want to double check that parse_str performs urldecode on resulting array elements.
Here is an example using JSON:
<?php
$arr = array($member_id, $coupon);
$data = json_encode($arr);
?>
<input type="hidden" name="custom" value="<?= $data ?>"/>
Then on the other side:
$custom = json_decode($_POST['custom'], true);
$member_id = $custom[0];
$coupon = $custom[1];
You can also parse associative arrays too:
<?php
$arr = array('id' => $member_id, 'coupon' => $coupon);
$data = json_encode($arr);
?>
<input type="hidden" name="custom" value="<?= $data ?>"/>
Then on the other side:
$custom = json_decode($_POST['custom'], true);
$member_id = $custom['id'];
$coupon = $custom['coupon'];
There's a nice symmetry when using JSON to parse the data.

Proper way to pass an array through post?

I have two pages:
Graph.php
List.php
The Graph page does exactly what it is named, graphs data. If there is no post/get data it displays all the data in a given table.
The List page is a huge table which loads around 500-600 rows of data. In the table you can sort and filter the rows using JavaScript. The table is around 14 columns wide.
After sorting the rows in the List page you can press a button 'Graph' that will take the visible rows and graph them on the graph page.
What I am having trouble with is passing these ID's over to the graph page. I started with:
<?php
if(isset($_POST['data']))
{
echo "FOUND SERIALIZED ARRAY<br>";
$afterSerializeArray = unserialize($_POST['data']);
print_r($afterSerializeArray);
}
$beforeSerializeArray = array();
$beforeSerializeArray[] = 1;
$beforeSerializeArray[] = 2;
$beforeSerializeArray[] = 3;
$serializeArray = serialize($beforeSerializeArray);
?>
<form action="" method="post">
<input type="hidden" name="data" value="<?php echo $serializeArray; ?>"/>
<input type="submit" value="Serialize"/>
</form>
I have written the small snippet to grab the ID's of the visible rows and load them into an array, serialize it and pump it into a variable to post it over to the graph.
Should I be using GET? Should I be doing this a different way?
The reason I wanted the filter and sort on a different page than the graph is because users have a lot of columns and options to filter and sort by.
Rather than trying to send array over post you should concatenate these ids with any special character (say ','). This way you will get all IDs as comma separated values in $_POST['data']. Now you can use PHP explode function to get all the values in an array and use them as you wish.
This code sample might help you
<?php
if(isset($_POST['data']))
{
echo "FOUND Ids<br>";
$IdArray = explode(',',$_POST['data']);
print_r($IdArray );
}
$idarray = array('1','2','3');
$ids = implode(',',$idarray);
?>
<form action="" method="post">
<input type="hidden" name="data" value="<?php echo $ids;?>"/>
<input type="submit" value="Serialize"/>
</form>

String Encode, Array Decode

I'm new to PHP, I started about 3 weeks ago.
I have a string, which is used with $_POST to pass it to another page, the second page uses $_GET to get these url and split it as desired.
My problem is that, in my first page I use a String, and I want to encrypt it, so that I can pass it as a plan text. In the second page I must decrypt it and get it as an array.
So is there any encryption method or function I can use which is compatible with $_POST ( so I can send it to another page ) and decrypt it as an array ?
I need this method, because the second page is actually connecting to website and is a payment method. So i don't want users to manually edit the url and lower the amount of $ for the product they get.
tnx for your help.
You're thinking about this wrong. You NEVER trust information coming from the user's side.
For example, if your user sends a form that says what item they want, DO NOT include the price in the form. Instead, get the price from the server (database), where it can be trusted.
What you probably want to do is pass the contents of the users cart (i.e. the items he'd like to order) to the payment site.
Therefore, you should create a form like:
<form action="URL/to/paymentPage.php" method="post">
<!-- Item 1 -->
<input type="hidden" name="items[0]" value="productID1"/>
<input type="hidden" name="quantity[0]" value="quantity1"/>
<!-- Item 2 -->
<input type="hidden" name="items[1]" value="productID2"/>
<input type="hidden" name="quantity[1]" value="quantity2"/>
<!-- ... -->
<!-- Item n -->
<input type="hidden" name="items[n]" value="productIDn"/>
<input type="hidden" name="quantity[n]" value="quantityn"/>
<input type="submit" value="Order"/>
</form>
On the server in the file "URL/to/paymentPage.php" you can access the items using the following code:
<?php
$items = $_POST['items']; // Array of items ..
$quantities = $_POST['quantity']; // The array of quantities for each item ..
// Calculate the total price ..
$totalPrice = 0;
foreach($items as $idx => $itemID) {
if($quantities[$idx]>0) {
totalPrice += getPriceFromDB($itemID) * $quantities[$idx];
}
}
echo 'Total Price to pay: '.$totalPrice;
?>
where the function getPriceFromDB actually retrieves the price for the item/product with the id $itemID from your database or elsewhere... :)
However, the user items are usually stored in the session, and, therefore, there is no need to submit the again.. ;)
Despite not fully understanding what you're trying to achieve, you can use base64 encoding:
$encoded_string = base64_encode ($string);
$decoded_string = base64_decode ($encoded_string);

php - filling in form fields from database values

I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}
Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.
From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity
My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");

Categories