I'm having trouble sending JSON object back to Angular application from PHP script. I tried to do it by URL but I am unable to send JSON:
header("Location: http://localhost:8000/index.html#/AnotherPage/abcd");
Here is my PHP code
<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
$paytmChecksum = "";
$parameterList1;
$paramList = array();
$isValidChecksum = "FALSE";
$parameterList1 = $_POST;
$paramList = $_POST;
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg
//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your application’s MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.
if($isValidChecksum == "TRUE") {
echo "<b>Checksum matched and following are the transaction details:</b>" . "<br/>";
if ($_POST["STATUS"] == "TXN_SUCCESS") {
echo "<b>Transaction status is success</b>" . "<br/>";
print_r($paramList);
echo $paramList;
//Process your transaction here as success transaction.
//Verify amount & order id received from Payment gateway with your application's order id and amount.
}
else {
echo "<b>Transaction status is failure</b>" . "<br/>";
}
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
echo "<br/>" . $paramName . " = " . $paramValue;
}
print_r($paramList);
}
}
else {
echo "<b>Checksum mismatched.</b>";
//Process transaction as suspicious.
}
header("Location: http://localhost:8000/index.html#/AnotherPage/abcd");
?>
here is my Angular project typescript code , which will receive json data sent by php ,
#Component({
selector: 'page-another',
templateUrl: 'another.html',
})
export class AnotherPage {
userData:any;
id:any;''
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.userData = navParams.get('data');
// this.id = navParams.get('id');
console.log(navParams.get('id'));
console.log(this.userData);
}
}
Related
Angular Post api with php sends query successfuly to the data base but doesnt reach .subscribe code after that :
Here is my code in my comp:
postdata(data:any)
{
this.DataService.Userregister(data).subscribe(data=>{console.log('success');})
};
and here is php code :
<?php
include_once("db_connection.php");
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
$request =json_decode($postdata);
$email = trim($request->email);
$password = trim($request->passw);
$username =trim($request->name);
$fname =trim($request->fname);
$sql = "INSERT INTO users (Email,Passw,u_name,fname)
VALUES ('$email','$password','$username', '$fname') ";
if( $conn->query($sql)===TRUE)
{
$res = "Success";
echo json_encode($res);
}
else{
$res = "Faild";
echo json_encode($res);
}
}
?>
i wrote this script to sign in the user in PHP in order to save the data to the server, if the user has been created the scrip should return a simple json with true or false.
<?php
require "../private/autoload.php";
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
print_r($_POST);
$Error = "";
$staff = $_POST['staff_ID'];
$email = $_POST['email'];
$pass = $_POST['password'];
$name = $_POST['Name'];
$cpt = $_POST['isCPT'];
$date = date("Y-m-d H:i:s",time()); // date of creation
// check if user alrady exixt
$sqlexixst = "SELECT * FROM `users` WHERE staff_ID = ?";
$st = $pdo->prepare($sqlexixst);
$st->execute(array($staff));
$result = $st->fetchAll();
if (count($result) > 0){
$array = array(
"user_created"=>false
);
$js = json_encode($array);
echo $js;
} else {
// user not exixt creo utente
$regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex,$email)){
// ok email
if (is_numeric($staff)){
// ok id
$sql = "INSERT INTO users (staff_ID,password,email,isCPT,Name, date) VALUES (?,?,?,?,?,?)";
$statement = $pdo->prepare($sql);
$statement ->execute([$staff,$pass,$email,$cpt,$name,$date]);
$array = array(
"user_created"=>true,
"staff_ID"=>$staff
);
$js = json_encode($array);
echo $js;
}
}else{
$Error = "pls enter valid email";
echo $Error;
}
}
}else {
echo 'no post';
}
?>
i'm sending the request using Alamofire... if i post the request using respondeString i can see the corret print out of the json, if i use respondJSON i cant get the json print out.. i get error say 'JSON could not be serialized. thata could not be read because it isn't in the correct format'
Alamofire and swiftyjson code:
func nxTest (){
let parm : [String : Any] = ["staff_ID": "3879","password":"12345678","email":"damiano.miai#gmail.com", "isCPT":false,"Name":"Marco Frizzi"]
AF.request("http://192.168.50.10/nx/public/register.php", method: .post, parameters: parm,headers: nil, interceptor: nil, requestModifier: nil).validate()
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
.responseString { st in
print(st)
}
}
Let’s get detailed…cause I’m stumped.
Server File structure:
/home/name/public_html/CryptlexApi.php
/home/name/public_html/generate-license.php see below
/home/name/public_html/generate-license-IPN_combined.php
/home/name/public_html/paypalIPN.php
source
generate-license.php:
<?php
require('CryptlexApi.php');
// pass this secret as query param in the url e.g. https://yourserver.com/generate-license.php?cryptlex_secret=SOME_RANDOM_STRING
$CRYPTLEX_SECRET = "SOME_RANDOM_STRING";
// access token must have following permissions (scope): license:write, user:read, user:write
$PERSONAL_ACCESS_TOKEN = "Yes, I have my PAT here";
// utility functions
function IsNullOrEmptyString($str){
return (!isset($str) || trim($str) === '');
}
function ForbiddenRequest() {
http_response_code(403);
$message['error'] = 'You are not authorized to perform this action!';
echo json_encode($message);
}
function BadRequest($error) {
http_response_code(400);
$message['error'] = $error;
echo json_encode($message);
}
function VerifySecret($secret) {
if($secret == $GLOBALS['CRYPTLEX_SECRET']) {
return true;
}
return false;
}
function parsePayPalPostData() {
$postBody['company'] = $_POST['payer_email'];
if(IsNullOrEmptyString($postBody['email'])) {
$postBody['company'] = "";
}
$postBody['quantity'] = $_POST['quantity'];
if(IsNullOrEmptyString($postBody['quantity'])) {
$postBody['quantity'] = NULL;
}
$postBody['email'] = $_POST['payer_email'];
if(IsNullOrEmptyString($postBody['email'])) {
BadRequest('email is missing!');
return NULL;
}
$postBody['last_name'] = $_POST['last_name'];
if(IsNullOrEmptyString($_POST['last_name'])) {
BadRequest('last name is missing!');
return NULL;
}
$postBody['first_name'] = $_POST['first_name'];
if(IsNullOrEmptyString($_POST['first_name'])) {
BadRequest('first name is missing!');
return NULL;
}
$postBody['order_id'] = $_POST['txn_id'];
if(IsNullOrEmptyString($postBody['order_id'])) {
BadRequest('reference is missing!');
return NULL;
}
return $postBody;
}
try {
if(VerifySecret($_GET['cryptlex_secret']) == false) {
return ForbiddenRequest();
}
CryptlexApi::SetAccessToken($GLOBALS['PERSONAL_ACCESS_TOKEN']);
$product_id = "this is my product id";
$postBody = parsePayPalPostData();
if($postBody == NULL) {
echo "no data \n";
return;
}
$email = $postBody['email'];
$first_name = $postBody['first_name'];
$last_name = $postBody['last_name'];
$quantity = $postBody['quantity'];
// required for renewing the license subscription
$order_id = $postBody['order_id'];
// creating user is optional
$user_exists = false;
$user = CryptlexApi::GetUser($email);
if($user == NULL) {
$user_body["email"] = $email;
$user_body["firstName"] = $first_name;
$user_body["lastName"] = $last_name;
$user_body["company"] = $last_name;
// generate a random 8 character password
$user_body["password"] = substr(md5(uniqid()), 0, 8);
$user_body["role"] = "user";
$user = CryptlexApi::CreateUser($user_body);
} else {
$user_exists = true;
}
echo "Quantity = $quantity \n";
// creating license
if($quantity != NULL) {
$license_body["allowedActivations"] = (int)$quantity;
}
$license_body["productId"] = $product_id;
$license_body["userId"] = $user->id;
$metadata["key"] = "order_id";
$metadata["value"] = $order_id;
$metadata["visible"] = false;
$license_body["metadata"] = array($metadata);
$license = CryptlexApi::CreateLicense($license_body);
http_response_code(200);
echo $license->key;
} catch(Exception $e) {
http_response_code(500);
echo 'message: ' .$e->getMessage();
}
Ok, So if I do the following in the terminal, I will successfully create a user/license
curl -d "payer_email=emailaddress%40gmail.com&quantity=1&last_name=smith&first_name=bob&txn_id=ordernumber" -X POST https://mywebsite.com/generate-license.php?cryptlex_secret=SOME_RANDOM_STRING
So, I take that code and put it in paypalIPN.php and renamed to generate-license-IPN_combined.php
In the paypalIPN.php file, I inserted the above code here:
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
######## I put all of my code above right here #########
return true;
} else {
return false;
}
The IPN code seems to work since the Paypal IPN simulator says it does. Nothing happens on the database side though. I’ve removed checks and even went as far as putting this code before the IPN but it’s not working. Please help.
A quick way to generate test IPNs in sandbox is to pay with a link of the form:
https://www.sandbox.paypal.com/webscr?cmd=_xclick&item_name=test&amount=100¤cy_code=USD&business=sandboxbusinessemail#domain.com¬ify_url={URL_ENCODE_YOUR_IPN_LISTENER_URL}
(Reference: HTML Variables for PayPal Payments Standard )
Get a sandbox business account to sub into the above, and a sandbox personal account to pay with, via: https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Faccounts%2F
Review the business account's IPN history via: https://www.sandbox.paypal.com/webscr?cmd=_display-ipns-history
I wrote some code that handles the callback request from my payment service. But I get MethodNotAllowedHttpException. No message.
Here is my controller :
if(isset($_POST['State']) && $_POST['State'] == "OK") {
$soapclient = new soapclient('https://verify.sep.ir/Payments/ReferencePayment.asmx?WSDL');
$res = $soapclient->VerifyTransaction($_POST['RefNum'], $MerchantCode);
if( $res <= 0 )
{
// Transaction Failed
echo "Transaction Failed";
} else {
// Transaction Successful
echo "Transaction Successful";
echo "Ref : {$_POST['RefNum']}<br />";
echo "Res : {$res}<br />";
}
} else {
// Transaction Failed
echo "Transaction Failed";
}
What is wrong with my code?
Probably you used the GET method for the route, update it to a POST and will be working fine since the API seems to expect that.
I am quite new to php and payment integration.
But I have successfully integrated the payment system but the problem I am facing is how to store those confirmation values in database.
Here is my response.php code where the confirmation response from gateway is sent back to response page. With the code I am able to get the confirmation status output, problem is how to store it in db.
[this is the output][1]
<?php
include 'header.php';
include 'dbconnect.php';
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
?>
<html>
<head></head>
<body>
<?php
// following files need to be included
require_once("./paytm/PaytmKit/lib/config_paytm.php");
require_once("./paytm/PaytmKit/lib/encdec_paytm.php");
$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";
$paramList = $_POST;
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg
//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your application’s MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.
if($isValidChecksum == "TRUE") {
echo "<b>Checksum matched and following are the transaction details:</b>" . "<br/>";
if ($_POST["STATUS"] == "TXN_SUCCESS") {
echo "<b>Transaction status is success</b>" . "<br/>";
//Process your transaction here as success transaction.
//Verify amount & order id received from Payment gateway with your application's order id and amount.
}
else {
echo "<b>Transaction status is failure</b>" . "<br/>";
}
if (isset($_POST) && count($_POST)>0 )
{
//here iam trying to store it but it is not working as shows undefined functions
foreach($_POST as $paramName => $paramValue) {
echo "<br/>" . $paramName . " = " . $paramValue;
$sql = "INSERT INTO txn_details (MID, ORDERID, TXNAMOUNT, CURRENCY, TXNID, BANKTXNID, STATUS, RESPCODE, RESPMSG, TXNDATE, GATEWAYNAME, BANKNAME, PAYMENTMODE)
VALUES ('$MID', '$ORDERID', '$TXNAMOUNT', '$CURRENCY', '$TXNID', '$BANKTXNID', '$STATUS', '$RESPCODE', '$RESPMSG', '$TXNDATE', '$GATEWAYNAME', '$BANKNAME', '$PAYMENTMODE')";
$result = $conn->query($sql);
}
}
}
else {
echo "<b>Checksum mismatched.</b>";
//Process transaction as suspicious.
}
include 'footer.php';
?>
</body>
</html>
[1]: https://i.stack.imgur.com/DnNRg.png
These is the pgredirect.php where i Mid AND OTHERS ARE defined.
<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
$checkSum = "";
$paramList = array();
$ORDER_ID = $_POST["ORDER_ID"];
$CUST_ID = $_POST["CUST_ID"];
$INDUSTRY_TYPE_ID = $_POST["INDUSTRY_TYPE_ID"];
$CHANNEL_ID = $_POST["CHANNEL_ID"];
$TXN_AMOUNT = $_POST["TXN_AMOUNT"];
$EMAIL = $_POST["EMAIL"];
$MSISDN = $_POST["MSISDN"];
// Create an array having all required parameters for creating checksum.
$paramList["MID"] = PAYTM_MERCHANT_MID;
$paramList["ORDER_ID"] = $ORDER_ID;
$paramList["CUST_ID"] = $CUST_ID;
$paramList["INDUSTRY_TYPE_ID"] = $INDUSTRY_TYPE_ID;
$paramList["CHANNEL_ID"] = $CHANNEL_ID;
$paramList["TXN_AMOUNT"] = $TXN_AMOUNT;
$paramList["WEBSITE"] = PAYTM_MERCHANT_WEBSITE;
$paramList["CALLBACK_URL"] = "http://localhost/wd/response.php";
$paramList["MSISDN"] = $MSISDN; //Mobile number of customer
$paramList["EMAIL"] = $EMAIL; //Email ID of customer
$paramList["VERIFIED_BY"] = "EMAIL"; //
$paramList["IS_USER_VERIFIED"] = "YES"; //
//Here checksum string will return by getChecksumFromArray() function.
$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
?>
<html>
<head>
<title>Merchant Check Out Page</title>
</head>
<body>
<center><h1>Please do not refresh this page...</h1></center>
<form method="post" action="<?php echo PAYTM_TXN_URL ?>" name="f1">
<table border="1">
<tbody>
<?php
foreach($paramList as $name => $value) {
echo '<input type="hidden" name="' . $name .'" value="' . $value . '">';
}
?>
<input type="hidden" name="CHECKSUMHASH" value="<?php echo $checkSum ?>">
</tbody>
</table>
<script type="text/javascript">
document.f1.submit();
</script>
</form>
</body>
</html>
You have to define all variables value and write INSERT statement out side of foreach loop.
your insert statement should look like.
if (isset($_POST) && count($_POST)>0 )
{ //here iam trying to store it but it is not working as shows undefined functions
$sql = "INSERT INTO txn_details (MID, ORDERID, TXNAMOUNT, CURRENCY, TXNID, BANKTXNID, STATUS, RESPCODE, RESPMSG, TXNDATE, GATEWAYNAME, BANKNAME, PAYMENTMODE)
VALUES ('".$_POST['MID']."', '".$_POST['ORDERID']."', '".$_POST['TXNAMOUNT'].", '".$_POST['CURRENCY']."', '"..$_POST['TXNID']."', '"..$_POST['BANKTXNID']."', '".$_POST['STATUS']."', '".$_POST['RESPCODE']."', '".$_POST['RESPMSG']."', '".$_POST['TXNDATE']."', '".$_POST['GATEWAYNAME']."', '".$_POST['BANKNAME']."', '".$_POST['PAYMENTMODE']."')";
$result = $conn->query($sql);
}