Facebook Payments – Order ID

One of the main problems when implementing facebook payments in your app is how to retrieve and store the ID of each placed order.

As easy as this sounds, this could become a titanic task, just because the way the jsondecode is used on the facebook callback example.

Normally, what you would like to achieve inside the callback is just saving to the database the placed orders.  So you can retrieve them after.   This is done by inserting a field on your order’s table with all the content from the client’s order.

It all stars with the json_decode:

$request = parse_signed_request($_POST[‘signed_request’], $app_secret);

// Get order details.
$order_details = json_decode($request['credits']['order_details'], true);

Here you’re just simply ask for the order details and you convert them to an array variable named $order_details.

Now if the order status is ‘placed’, you proceed to save the order on the database:

inside the following IF:

if ($current_order_status == 'placed') {

Grab the item details and save it to the database:

$item_details = $order_details['items'][0];

 if ($item_details) {
 // Fulfill order based on the information below...
 $product = $item_details['item_id'];
 $product_title = $item_details['title'];
 $product_price = $item_details['price'];
 $product_url = $item_details['product_url'];
 $image_url = $item_details['image_url'];

 $order_id = number_format( $order_details['order_id'], 0, '', '').PHP_EOL;

 $con = mysql_connect("host","user","password");
 if (!$con) die('Could not connect: ' . mysql_error());
 mysql_select_db ('my_table');

 $query = "INSERT INTO my_table (order_id, product, title, price, product_url, created, modified) VALUES ('$order_id','$product','$product_title','$product_price','$product_url',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)";

 mysql_query($query) or DIE ('Error updating database');
 mysql_close($con);
 }

The table that you use for saving the order on the database can be name as you want and can have as many fields you want, but those fields are the most important ones.

The use of ‘number_format’ is strictly neccesary.  The ID comming from the database is converted to FLOAT and will not be saved correctly if you don’t use this PHP function.

This way, you’ll have your order saved on the database with an order ID that identifies the purchase and can be used on the facebook graph to get more information about it.

See more about how json_decode works:

http://php.net/manual/en/function.json-decode.php

 

Leave a Reply