local payment api failed to verify the transaction using php - php

This is the API provided by https://www.cashmaal.com/api I deposited some cash in my cashmaal account and the transaction id I got whenever I try to verify the payment by transaction id it shows me an error
Error: Error! Transaction Id () is invalid.
$web_id=""; // Your Web ID here (you can found this on cashmaal account where you add site)
if(isset($_POST['CM_TID'])) {
$CM_TID=$_POST['CM_TID']; // getting TID with user redirection
$url="https://www.cashmaal.com/Pay/verify_v2.php?CM_TID=".urlencode($CM_TID)."&web_id=".urlencode($web_id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result,true);
if($obj['status'] == 1)
{ // it means payment received....
//response format in JSON
//Example Response
/*
{"status":"1","receiver_account":"8","USD_amount":"1.670","fee_in_USD":"0.000","PKR_amount":"280","fee_in_PKR":"0","USD_amount_with_fee":"1.670","PKR_amount_with_fee":"280","trx_website":"website.com","transaction_id":"2JW9651118P","trx_date":"25-03-2020 9:13:48 PM","order_id":"12345678","addi_info":"Test Payment","sender_details":"Fund Received From 161919","trx_details":"$1.67 Receive against TID: '2JW9651118P'"}
*/
// Verify All things and Confirm user order here
if($obj['USD_amount'] == '2')
{
echo 'we received your payment';
}
else
{
echo "we didn't received the your mentioned payment ";
}
}
else
{
echo "Error:".$obj['error'];
}
}

Just found a solution of this that this cashmaal api verify the transaction id only if the transaction is done by other cashmaal account

Related

Payment gateway development - Handling and Processing parameters/keys PHP to Json, Json to PHP

I have written a Payment processor.php file to receive parameters from an ecommerce system then post to a PSP (Payment Service Provider), then this Json response from the PSP will be decoded, verified and Keys converted and parsed to the ecommerce system this way:
header("Location: ".$hosturl."orderprocessor?
orderid=$custref&sig=".$_POST['SessionId']);
Before giving out item in cart to users.
$hosturl has been defined as
$hosturl="localhost:8080/ekp/";
in another file
The result I get each time I do cart checkout with "Payment processor.php" file is just a white screen. I am supposed to see the PSP's interface to receive user's card details instead.
The PSP's URL is; " https://developers.paystack.co/reference#paystack-standard-x" I am following the cURL PHP sample for reference.
kindly assist if corrections are spotted in my code.
This is my Payment processor.php file:
<?php require_once 'includes/config.inc.php' ?>
<?php
$parameters = array();
if (isset($_POST['amount'])) { /* came the LMS; about to send data to
Paystack */
$sig=hash_hmac("md5","amount=".urlencode($_POST['amount']).
"&currency=".urlencode($_POST['currency']).
"&orderid=".urlencode($_POST['orderid']), $KEY);
$parameters['UserName']=$username;
$parameters['Password']=$password;
$parameters['reference']=$_POST['orderid'];
$parameters['Amount']=($_POST['amount'] * 100);
//should change SessionId' to be named reference
$parameters['SessionId']=$sig;
$parameters['SessionKey']=$encryptionKey;
$parameters['DL']="activ_purchase";
$parameters['ServerURL']=
base64_encode("http://localhost/nse/ecommerce/paystack.php");
$parameters['UserURL']=
base64_encode("http://localhost/nse/ecommerce/paystack.php");
$parameters['AccountNumber']=$accountnumber;
//$parameters['UserDeclinedURL']=
base64_encode($hosturl."externalpaymentcancel?
orderid=".$_POST['orderid']);
// print_r($parameters);
$cart=$_POST['cart'];
// var_dump($cart); die;
$cartitems=objectToArray(json_decode($cart));
foreach ( $cartitems['items'] as $item )
{
$productName=$item['description'];
$quantity=1;
$price=$item['price']['amount'];
$parameters['Reference4']=$productName." Qty
".$quantity." # $".$price."\r\n" ;
}
// created parameters for Paystack $postdata here
$postdata = array('email' => 'customer#gmail.com',
'amount' => $parameters['Amount'],
'reference' => $parameters['reference'],
);
//$url = "https://api.paystack.co/transaction/initialize";
//My codes for $ch here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$paystackUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($postdata)); //Post
Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Authorization: Bearer sk_test_*****************************',
'Content-Type: application/json'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
curl_close ($ch);
//My code for $ch ends here
//starting to setup redirect url
if ($result) {
$request = json_decode($result, true);
//print_r($request);
foreach ($request as $input) {
if($input ['data']['reference']){
$sst=['data']['reference'];
break;
}
}
header('Location:'.$result['data']
['authorization_url'].$parameters['SessionId'].$sst);
}
//Use the $result array to get redirect URL paystack
//var_dump($result);
}
else {
$result = array();
$url = 'https://api.paystack.co/transaction/verify/'.$_GET['reference'];
// print_r($parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer sk_test_*****************************']
);
$request = curl_exec($ch);
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
// print_r($result);
if($result){
if($result['data']){
//something came in
if($result['data']['status'] == 'success'){
header("Location: ".$hosturl."orderprocessor?
orderid=$reference&sig=".$_POST['SessionId']);
//echo "success";
// the transaction was successful, you can deliver value
/*
# also remember that if this was a card transaction, you can store
the
# card authorization to enable you charge the customer
subsequently.
# The card authorization is in:
# $result['data']['authorization']['authorization_code'];
# PS: Store the authorization with this email address used for this
transaction.
# The authorization will only work with this particular email.
# If the user changes his email on your system, it will be unusable
*/
echo "Transaction was successful";
}else{
// the transaction was not successful, do not deliver value'
// print_r($result); //uncomment this line to inspect the result,
to check why it failed.
echo "Transaction was not successful: Last gateway response was:
".$result['data']['gateway_response'];
}
}else{
echo $result['message'];
}
}else{
//print_r($result);
die("Something went wrong while trying to convert the request variable
to json. Uncomment the print_r command to see what is in the result
variable.");
}
}else{
echo "<html><head><meta http-equiv=\"refresh\"
content=\"5;URL=$hosturl"."externalpaymentcancel?orderid=$custref\">
</head><body style=\"text-align:center; font-family:'Open Sans', Arial,
Helvetica, sans-serif;\"><p><img
src=\"/nd/repository/EKP000000414.jpg\" alt=\"Activ logo\" /></p>
<p>Unfortunately, we were unable to process your payment.</p><p>The
response from your financial institution was "$declinedmessage"
</p><p>You will be redirected to the LMS shortly.</p></body></html>";
}
//echo $payresult;
//if ($payresult=="1") {
//header("Location: ".$hosturl."orderprocessor?
orderid=$custref&sig=".$_POST['SessionId']);
//echo "success";
//} else {
//echo "fail";
//echo "<html><head><meta http-equiv=\"refresh\"
content=\"5;URL=$hosturl"."externalpaymentcancel?orderid=$custref\">
</head><body style=\"text-align:center; font-family:'Open Sans', Arial,
Helvetica, sans-serif;\"><p><img
src=\"/nd/repository/EKP000000414.jpg\" alt=\"Activ logo\" /></p>
<p>Unfortunately, we were unable to process your payment.</p><p>The
response from your financial institution was "$declinedmessage"
</p><p>You will be redirected to the LMS shortly.</p></body></html>";
//header("Location: ".$hosturl."externalpaymentcancel?orderid=$custref");
// }
}
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
?>

Search FB Messenger Message for Specific Word in PHP

So I'm trying to create a Facebook Messenger Chatbot, a very simple one. I have it working with a hardcoded response, but I want it to be able to read the senders message and respond in a specific way if it finds that word - like how chatbots should. I' trying to do so by using preg_match() but when I use my current code, the bot doesn't reply at all. Here's my code:
<?php
/**
* Webhook for Facebook Messenger Bot
*/
$access_token = "{mytoken}";
$verify_token = "{mytoken2}";
$hub_verify_token = null;
if (isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token == $verify_token) {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
// perform a case-Insensitive search for the word "time"
if (preg_match('[hi|hello|sup]', $message)) {
$answer = "Hiya!";
}
else {
$answer = "IDK.";
}
// send the response back to sender
// 'text': 'Hiya!'
$jsonData = "{
'recipient': {
'id': $sender
},
'message': {
'text': $answer
}
}";
// initiate cURL.
$ch = curl_init("https://graph.facebook.com/v2.6/me/messages?access_token=$access_token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
curl_exec($ch);
}
Do you know whether you actually receive messages from the Messenger Platform? Your webhook verification ends in an echo, where in fact you need to respond to the platform with a status code 200. You can also check your Facebook Apps dashboard to figure out whether your webhook is verified and being sent messages.
Documentation: https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup
Once you know that your webhook is verified and you are receiving messages, start with a fixed reply and then work towards dynamic responses. As #Toto suggested, adding logging will be very helpful to debug your code.

How to resend android push notification first try failed

I have this methode :
$oAndroidService = new GoogleGNCService($message);
# divide per batch with 1000 users
$a_batch = array_chunk($a_users, 1000);
for($i = 0; $i < count($a_batch); $i++){
# get the liste of tokens
foreach($a_batch[$i] as $batch){
$a_tokens[] = $batch['token'];
}
# if push sent with success
if($oAndroidService->sendPush($a_tokens)){
foreach($a_batch[$i] as $userToProcess){
// update push token history
}
}
echo 'PUSH SENT !';
# unset the array with tokens
unset($a_tokens);
}else{
echo 'ERROR SENT PUSH'
}
}
And the method that sent pushes :
public function sendPush($a_token){
# init the curl connection
$ch = curl_init();
# if success connection
if($ch){
# array that will be send in post with curl call
$a_post = array(
'registration_ids' => $a_token,
'data' => $this->getMessage(),
);
# set the options of curl request
curl_setopt($ch, CURLOPT_URL, self::ANDROID_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($a_post));
# execute the request
$result = curl_exec($ch);
if($result === false){
echo('Curl failed : ' . curl_error($ch));
return false;
}
# close the request
curl_close($ch);
return true;
}
echo 'Connection failed';
return false;
}
I have 2 questions :
If I sent 1000 tokens and curl failed, I need to resend this array with tokens one more time ? If failed the second time, I need to resent third time ?
If curl failed how to know what are the token that poses problems ?
Thx for you help in advance

Showing a simple text to the user when the user pays from my site

I have two php file: 1- get.php 2- send.php. Consider the user clicks on the buy button and requests to connect in the payment gateway page. the send.php for the user is as follows:
<?php
session_start();
if(isset($_SESSION['login_user'])) {
$username = $_SESSION['login_user'];
function send($url,$api,$amount,$redirect){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS,"api=$api&amount=$amount&redirect=$redirect");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
$url = 'http://payment.com/payment-test/gateway-send';
$api = 'adxcv-zzadq-polkjsad-opp13opoz-1sdf455aadzmck1244567';
$amount = 1000;
$redirect = urlencode('http://localhost/get.php');
$result = send($url,$api,$amount,$redirect);
if($result > 0 && is_numeric($result)){
$go = "http://payment.com/payment-test/gateway-$result";
//save the username and the get_id in a table.
header("Location: $go");
}}
esle {echo "found an error in connecting to payment gateway";} ?>
Now, the user goes to the payment gateway page and he does operation payment successfully. Now the payment gateway page from the bank sends trans_id and id_get to the get.php file and the get.php file is as follows:
function get($url,$api,$trans_id,$id_get){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS,"api=$api&id_get=$id_get&trans_id=$trans_id");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
$url = 'http://payment.com/payment-test/gateway-result-second';
$api = 'adxcv-zzadq-polkjsad-opp13opoz-1sdf455aadzmck1244567';
$trans_id = $_POST['trans_id'];
$id_get = $_POST['id_get'];
$result = get($url,$api,$trans_id,$id_get);
if($result == '1') {
//find the `$id_get`value in the table and put the `trans_id` within the same raw that the id_get is
echo "successfully"; }
else {echo "Unsuccessfully";}
The problem in the get.phpis the echo does not know that sends the messages to which user.And If I use the session in the top of the get.phpfile, as the result the session_start() gets a session from the payment gateway website.

Track user activity when recurring payment occurs using paypal subscribe button

I have a working IPN script. It is updating the data correctly in database according to the logged in user. So, Once the payment is successfully made user account will be upgraded as a paid member. And since i am using a paypal subscribe button. So, from the next month billing process will occur automatically.
So, here what i think(I am not sure), Paypal will not interact with my IPN script stored in my server.
So, My question is :-
If my assumption about IPN script is correct then how could i track which user has made a payment for the next billing cycle? (I don't want to be involved with manual work like tracking user payment information from my Paypal merchant account. I just want to do it through a script. So, once the subscription amount has been deducted from user Paypal account his account on my website will be upgraded as a paid member.)
For the reference what exactly i wanted to update through my ipn script. Below is my IPN script.
<?php
// STEP 1: Read POST data
// reading posted data from directly from $_POST causes serialization
// issues with array data in POST
// reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.sandbox.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// In wamp like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below.
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// check whether the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_name=strip_tags($item_name);
$item_number = strip_tags($_POST['item_number']);
$payment_status = strip_tags($_POST['payment_status']);
$payment_amount = strip_tags($_POST['mc_gross']);
$payment_currency = strip_tags($_POST['mc_currency']);
$txn_id = strip_tags($_POST['txn_id']);
$user_id=strip_tags($_POST['custom']);
$receiver_email = strip_tags($_POST['receiver_email']);
$payer_email = strip_tags($_POST['payer_email']);
//if(strcmp($receiver_email, "h_1356964205_per#gmail.com") == 0)
//{
/*if($payment_status != "Completed")
{
$msg="Transaction with id ".$txn_id." status is not completed..";
mail("support#example.com","Transaction with the same id already exists in database.",$msg,"From:admin#leadstool.net");
exit();
}*/
include_once('connection.php');
//$user_id=getfield('id');
// Query to check the duplicate transaction id.
$query="SELECT `User_id` FROM `transaction` WHERE `Transaction_id`='".mysql_real_escape_string($txn_id)."'";
if($query_run=mysql_query($query))
{
$num=mysql_num_rows($query_run);
if($num == 0)
{
// Query to check the number of times for subscription.
$query="SELECT `Transaction_id` FROM `transaction` WHERE `User_id`='".mysql_real_escape_string($user_id)."'";
if($query_run=mysql_query($query))
{
$num=mysql_num_rows($query_run);
if($num>=1)
{
$type_of_subscription=2;// This 2 will denote the user is rnewing his account
} else {
$type_of_subscription=1;// Here 1 is denoting that user has subscribed for the 1st time.
}
$query="SELECT `B_ad_no_paid_user`,`T_ad_no_paid_user` FROM `WebsiteContent` WHERE `Creator_id`='1' ORDER BY `Date_of_update` DESC LIMIT 1";
if($query_run=mysql_query($query))
{
while($rows=mysql_fetch_array($query_run))
{
$banner_ad_limit=$rows['B_ad_no_paid_user'];
$text_ad_limit=$rows['T_ad_no_paid_user'];
}
}
}// Query to check the number of times for subscription ends here.
//Query to insert the transaction details in database.
$query="INSERT INTO `transaction` VALUES('".$txn_id."','".$user_id."','".$payment_amount."','".$type_of_subscription."','".$payment_status."','1','".$payer_email."',now())";
if($query_run=mysql_query($query))
{
$query="UPDATE `user` SET `User_type`='1', `Banner_ad_limit`='".$banner_ad_limit."', `Text_ad_limit`='".$text_ad_limit."' WHERE `id`='".mysql_real_escape_string($user_id)."'";
if($query_run=mysql_query($query))
{
$msg="Thank you for subscribing to our service. Your Transaction Id is $txn_id.";
mail("$payer_email","Subscription confirmation mail",$msg,"From:admin#example.com");
} else {
$msg="Thank you! Your transaction is successful with transaction id:- $txn_id. But we are unable to upgrade your profile right now. Please contact admin to resolve the problem.";
mail("$payer_email","Subscription confirmation mail",$msg,"From:admin#example.com");
}
} else {
$msg="For Transaction with id ".$txn_id." failed to update in database.";
mail("support#example.com","Unable to update the details in database.",$msg,"From:admin#example.com");
exit();
}
// Query to insert data in database ends here.
} else {
$msg="Transaction with id $txn_id already exists in database. Admin please verify the details manually and contact the user. Email id of user is: $payer_email";
mail("support#example.com","Transaction with the same id already exists in database.",$msg,"From:admin#example.com");
exit();
}// Query to check the duplicate transaction id ends here.
}
//} else {
//$msg="Investigate the reason why the registered email id with paypal does not matched with this id $receiver_email";
//mail("support#example.com","Receiver email address do not matched",$msg,"From:admin#example.com");
//exit();
//}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
$msg="Dear administrator please verify the reason why the transaction failure occures. The details is:- $res";
mail("support#example.com","IPN interaction was not verified.",$msg,"From:admin#example.com");
exit();
}
?>
This is possible using the IPN and notify_url.
Here is a good tutorial:
http://www.techrepublic.com/article/handling-recurring-payments-with-paypal-subscriptions-and-ipn/5331883

Categories