<?php
include 'dbconfig.php';
$viewurl="app/paymentsuccess.php";
if(isset($_POST)){
	$response = $_POST;
	
	/* It is very important to calculate the hash using the returned value and compare it against the hash that was sent while payment request, to make sure the response is legitimate */
	$salt = "";
	$result=$conn->query("SELECT * from payment_settings");
    if(mysqli_num_rows($result)>0){
     $payrow=mysqli_fetch_array($result);
     $salt=$payrow['salt_key']; /* put your salt provided by Basispay here */
    }
	if(isset($salt) && !empty($salt)){
		$response['calculated_hash']=hashCalculate($salt, $response);
		$response['valid_hash'] = ($response['hash']==$response['calculated_hash'])?'Yes':'No';
		$response_code=$response['response_code'];
		if(!empty($response_code)){
		if($response_code==1073 || $response_code==0){
		$amount=$response['amount'];   
		$response_message=$response['response_message'];
		$created=date("Y-m-d H:i:s");
        $order_id=$response['order_id'];
        $query=$conn->query("update save_order SET payment_mode='basispay' WHERE id='$order_id'");
		$payment=$conn->query("insert into payment_transaction SET order_id='".$response['order_id']."',name='".$response['name']."',transaction_id='".$response['transaction_id']."',payment_mode='".$response['payment_mode']."',payment_channel='".$response['payment_channel']."',payment_datetime='".$response['payment_datetime']."',amount='".$amount."'");
		header("Location:".$base_url.$viewurl."");
		}else{
		 $response_message=$response['response_message'];  
		}}
	} else {
		$response['valid_hash']='Set your salt in return_page.php to do a hash check on receiving response from Basispay';
	}
}

function hashCalculate($salt,$input){
	/* Remove hash key if it is present */
	unset($input['hash']);
	/*Sort the array before hashing*/
	ksort($input);
	
	/*first value of hash data will be salt*/
	$hash_data = $salt;
	
	/*Create a | (pipe) separated string of all the $input values which are available in $hash_columns*/
	foreach ($input as $key=>$value) {
		if (strlen($value) > 0) {
			$hash_data .= '|' . $value;
		}
	}

	$hash = null;
	if (strlen($hash_data) > 0) {
		$hash = strtoupper(hash("sha512", $hash_data));
	}
	return $hash;
}
?>
