PHP Transaction confirm with javascript - javascript

I want to confirm transaction from other third-party, e.g I pay goods of $50 to juma Joe after click pay button and pay page is still loading and tell me to wait almost 5 seconds to check if the transaction is processing succeed, and if the transaction succeeds, it redirects to a success page.
So i need javascript and html confirmation code call from php to check if transaction is success then to show redirect seconds.
Thank you
Bellow is code for for validate transaction
$result = array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
echo "Transaction was successful";
//Compete transaction
}else{
// Not complete
echo "Transaction not complete";
}

So. You can using ajax to request and response in you code.
Example:
PHP Code: validate.php
//....above you code here
// my code config response
$res = [
'mess' => null,
'status' => 404
];
//...you code validation result
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
//Compete transaction
$res['mess'] = "Transaction was successful";
$res['status'] = 200;
}else{
// Not complete
$res['mess'] = "Transaction not complete";
$res['status'] = 404;
}
// my code response mess
echo json_encode($res);
So, below my front-end code, using jQuery Ajax to send POST request.
Document you can check here
$(document).ready(function() {
function validate(){
$.ajax({
url: 'validate.php',
type: 'POST',
dataType: 'json',
success: function(res) {
if (res.status === 200) {
console.log("you code here for success");
} else {
console.log("you code here for fail");
}
},
error: function(err) {
console.log("Request is error with: " + err);
}
});
}
});
HTML for submit button. Call to javascript
<button id="submit" type="submit" onclick="validate();">Send Request</button>

function checking(){
$.ajax({
dataType: "json",
url: status.php,
success: function(data){
if (data.done=='y') window.location = 'done.html';
}
});
}
setInterval(checking,5000);
With this script, you can call for every 5 seconds. But the best practice is to use a webhook. For more information, search it up on your payment gateway API documentation.
status.php
$result = array();
$respond=array();
$url = 'https://api.xxxx.co/transaction/verify/reference';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer xxxxxxx']
);
$request = curl_exec($ch);
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
curl_close($ch);
if ($request) {
$result = json_decode($request, true);
}
if (array_key_exists('data', $result) && array_key_exists('status', $result['data']) && ($result['data']['status'] === 'success')) {
$respond[done]='y';
//Compete transaction
}else{
// Not complete
$respond[done]='n';
}
echo json_encode($respond);

Related

Login to site with PHP cURL

I'm trying login to a remote site, by having curl to the login form.
I want to redirect to another subdomain and get content.
The code I have doesn't seem to work and only tries to show the main page of the site.
<?php
$username = 'user';
$password = 'pass';
$loginUrl = 'https://site_url';
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&password='.$password);
//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt ($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request (the login)
$store = curl_exec($ch);
//the login is now done and you can continue to get the
//protected content.
//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'https://site_url/statistics');
//execute the request
$content = curl_exec($ch);
curl_close($ch);
//save the data to disk
file_put_contents('~/file.txt', $content);
?>
Does it have to be via cURL?
Have you considered leveraging a library like Guzzle?
They have good documentation that covers scenarios as you have described.
https://docs.guzzlephp.org/en/stable/quickstart.html#post-form-requests
Something like the below but could be laid out better
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
$client = new Client(['base_uri' => 'https://url_site/', 'cookies' => true]);
// Login
try {
$client->request(
'POST',
'login/',
[
'form_params' => [
'username' => $username,
'password' => $password,
],
]
);
} catch (BadResponseException $e) {
echo "Error Logging On for User {$username}";
exit;
}
// Navigate
$response = $client->request('GET', '/statistics');
$content = $response->getBody()->getContents();
file_put_contents('~/file.txt', $content);

Getting 500 error when trying to call PHP function via AJAX [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to send trigger an email when a user completes a webform.
However I am getting the following error
Appreciate any advise on how to resolve this error.
JS file that will call the php function
$(function() {
$('.error').hide();
$(".request_demo").click(function() {
// validate and process form here
$('.error').hide();
var email = $("#email").val();
if (email == "") {
$("#email_error").show();
$("#email").focus();
return false;
}
var email = $("#email").val();
var dataString = '<p><strong>Email: </strong> ' + email + '</p>';
$.ajax({
type: "POST",
url: "/script/send.php",
data: { data: dataString, senderAddress: email },
success: function() {
// show a success message to your visitors
// clear input field values
$("#email").val('');
}
});
return false;
});
});
PHP file
<?php
if( isset($_POST) ){
$postData = $_POST;
$mailgun = sendMailgun($postData);
if($mailgun) {
echo "Great success.";
} else {
echo "Mailgun did not connect properly.";
}
}
function sendMailgun($data) {
$api_key = 'xxxxxxx1234';
$api_domain = 'our_domain';
$send_to = 'some#email.com';
// sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
// form data
$postcontent = $data['data'];
$reply = $data['senderAddress'];
$messageBody = "<p>You have received a new message from the contact form on your website.</p>
{$postcontent}
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
$config = array();
$config['api_key'] = $api_key;
$config['api_url'] = 'https://api.mailgun.net/v2/'.$api_domain.'/messages';
$message = array();
$message['from'] = $reply;
$message['to'] = $send_to;
$message['h:Reply-To'] = $reply;
$message['subject'] = "New Message from your Mailgun Contact Form";
$message['html'] = $messageBody;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $config['api_url']);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:{$config['api_key']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,$message);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
?>
I am not sure this will solve your problem or not, but this may help you.
Please check what DATA TYPE is your server expecting. In your ajax request you haven't mentioned any Content-Type. As this is a POST request, jQuery will consider form data as default Content-Type. As I can see you are providing a JS Object as data, by default it will be converted to a query string before sending the request to the server.
If your server is expecting a json payload in the request, then you need to do JSON.stringify() you payload to convert the JS object into a JSON object.
ie. data : JSON.stringify({ data: dataString, senderAddress: email })

XmlHttpRequest - post JSON - json string too many quotes (i think) [duplicate]

I looked around a lot before posting this question so my apologies if it is on another post and this is only my second quesiton on here so apologies if I don't format this question correctly.
I have a really simple web service that I have created that needs to take post values and return a JSON encoded array. That all worked fine until I was told I would need to post the form data with a content-type of application/json. Since then I cannot return any values from the web service and it is definitely something to do with how I am filtering their post values.
Basically in my local setup I have created a test page that does the following -
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
On the webservice I have this (I have stripped out some of the functions) -
<?php
header('Content-type: application/json');
/* connect to the db */
$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('webservice',$link) or die('Cannot select the DB');
if(isset($_POST['action']) && $_POST['action'] == 'login') {
$statusCode = array('statusCode'=>1, 'statusDescription'=>'Login Process - Fail');
$posts[] = array('status'=>$statusCode);
header('Content-type: application/json');
echo json_encode($posts);
/* disconnect from the db */
}
#mysql_close($link);
?>
Basically I know that it is due to the $_POST values not being set but I can't find what I need to put instead of the $_POST. I tried
json_decode($_POST), file_get_contents("php://input") and a number of other ways but I was shooting in the dark a bit.
Any help would be greatly appreciated.
Thanks, Steve
Thanks Michael for the help, that was a definite step forward I now have at least got a repsonse when I echo the post....even if it is null
updated CURL -
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
updated php on the page that the data is posted to -
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array
print_r(json_encode($input));
As I say at least I see a response now wheras prior it was returning a blank page
You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.
Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.
$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
getUserLocation($ip_srv);
Function:
function getUserLocation($services) {
$ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
for ($i = 0; $i < count($services); $i++) {
// Configuring curl options
$options = array (
CURLOPT_RETURNTRANSFER => true, // return web page
//CURLOPT_HEADER => false, // don't return headers
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
);
// Initializing curl
$ch = curl_init($services[$i]);
curl_setopt_array ( $ch, $options );
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
//echo 'service: ' . $services[$i] . '</br>';
//echo 'err: '.$err.'</br>';
//echo 'errmsg: '.$errmsg.'</br>';
//echo 'httpCode: '.$httpCode.'</br>';
//print_r($header);
//print_r(json_decode($content, true));
if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
return json_decode($content, true);
}
}
}
you can put your json in a parameter and send it instead of put only your json in header:
$post_string= 'json_param=' . json_encode($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
//execute post
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
on the service side you can get your json string as a parameter:
$json_string = $_POST['json_param'];
$obj = json_decode($json_string);
then you can use your converted data as object.

Why I can't fetch data on the sometime by using curl_setopt and Ajax jquery?

I'm query data from another sever by using curl_setopt PHP and Ajax
I've already to test my below function it is work but it seem not smooth enough because sometime when I try to refresh and internet got a little big slow I will never got data.How ever when i check on firebug in Firefox I found as below json respond.
"<html><head>
<meta http-equiv="refresh" content="0;url=http:MyPartnerWebsite!queryLuckNumberRecordByPeriods.action?gwqqnhmpepceiqqn">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
</head><body></body></html>
"
*I'm got stuck right now because I don't know how to do with this respond *
private function http_code() {
$ch = curl_init();
if (!$ch) {
die("Couldn't initialize a cURL handle");
}
$ret = curl_setopt($ch, CURLOPT_URL, "http://Mypartnerwebsite!queryLuckNumberRecordByPeriods.action");
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 0.1);
$ret = curl_setopt($ch, CURLINFO_HTTP_CODE, true);
$ret = curl_setopt($ch, CURLOPT_PRIVATE, false);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$ret = curl_exec($ch);
$data;
$res;
if (empty($ret)) {
$res = 0;
$data = 0; // Partner server slow.
curl_close($ch);
} else {
$info = curl_getinfo($ch);
curl_close($ch);
if (empty($info['http_code'])) {
$res = 01;
$data = 01; // Got empty date from partner server
} else {
if ($this->errorType($info['http_code']) == TRUE) { // errors type
$data = $ret;
$res = $this->errorType($info['http_code']);
} else {
$data = $ret;
$res = 'unknowError';
}
}
}
echo json_encode(array('res' => $res, 'data' => $ret));
}
This is a function to check to know what type of server errors respond
Purpose I want to checking when my partner server errors and I will send this kind of errors to my website for make sure what kind of errors.
private function errorType($haystack) {
$errors = array(404, 200, 201, 204, 500, 501, 502, 503, 504, 505, 100, 203);
if (in_array($haystack, $errors)) {
return $haystack;
} else {
return FALSE;
}
}
Here is Jquery Ajax to fetch data from my own server
$.ajax({
method: "GET",
url: "<?PHP echo base_url('getcurrentday'); ?>",
dataType: "JSON",
beforeSend: function (xhr) {
},
success: function (data, textStatus, jqXHR) {
$(".loading").html("");
if (data.res !== 200) {
$("<p>Errors type:"+data.res+"</p>").appendTo(".errors");
} else {
if (data.data == false) {
getdata();// I want to reload Ajax if I got respond false and my data = '';
}
$.each(eval(ldata), function (i, val) {
$(val.anydata").appendTo(".result");
})
}
}
});
Please help.
It seems that your ajax call gets a timeout and therefor it is not always working. You can increase the timeout setting of ajax.
Furthermore you can add an error function to see when errors like timeouts occur.
$.ajax({
//your ajax code here...
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
},
timeout: 10000 // sets timeout to 10 seconds
});
The reason you still see the response in firebug is that the browser will anyways receive the server response, even on timeout, but it will not reach your jquery code.

How to display instagram API response in javascript alert?

I am trying to send a delete request to instagram api using ajax but my current javascript code display the response in alert box as:
<pre></pre><pre></pre>
so i cant find the problem why delete request is not successful! if i call the same php script(doit.php) from the browser and pass it media id then the delete will be successful!
could any one tell me what is wrong with my current delete ajax request that fails to make delete request to instagram api?
Instagram API Docs for Deleting Like
sample api response:
{
"meta": {
"code": 200
},
"data": null
}
javascript:
<script>
function deleteLike(a,b)
{
alert("MediaID:"+a+"\nId:"+b);
var url = "./doit.php";
$.post(url, {
"method": "post",
//"method": "delete",
"MediaID": a,
}, function(data)
{
var ajaxResponse = data;
alert("Response:"+ajaxResponse);
if (data.meta.code == 200) {
alert("sucessDelete");
}
})
}
</script>
PHP CODE:
$MediaIDvar= $_POST["MediaID"];
//$MediaIDvar= $_GET["MediaID"];
$url2 = "https://api.instagram.com/v1/media/".$MediaIDvar."/likes?xxxxx";
$api_response2 = get_data2(''.$url2);
$record2 = json_decode($api_response2); // JSON decode
echo '<pre>' . print_r($api_response2, true) . '</pre>';
echo '<pre>' . print_r($record2, true) . '</pre>';
// to see what is in the $api_response and $record object
/* gets the data from a URL */
function get_data2($url2) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$MediaIDvar= $_POST["MediaID"];
$MediaIDvar= $_GET["MediaID"]; // => this will overwrite the previous $MediaIDvar
it will work if you call the php script with a GET variable, not through ajax using POST ;-)

Categories

Resources