I am trying to validate bitcoin engine respond once executing with correct amount within the account balance and correct wallet I am getting transaction ID, but if I enter amount too much and fake wallet I am not receiving any error in return just a blank page with html, head and body elements. Is there is any debug mode or what I can do to receive any response?
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
I am using jsonRPCClient to connect with bitcoin engine.
however when I do that in console using RPC commands
I am getting this : Account has insufficient funds (code -6)
code for redirection
if ($message !== '') {
ob_start();
header("Location: mywallet.php?error=done");
die();
} else {
ob_start();
header("Location: mywallet.php?error=true");
die();
}
Update Yes correct I will more ob_start(); above, thing is that once trying (try,catch) event I am getting blank page upon SUCCESS (so not transaction ID like with normal way I am doing I am getting back transaction ID) upon FAIL I am getting Unable to connect to Bitcoin Server. What I just need sounds very simple, how do I verified that transaction is SUCCESSFUL or FAIL, SUCCESSFUL -> I got ID in return, FAIL -> I have got Error in return. SO I can divert users to right places on the page after form is submitted. Actualy I am doing is withdraw funds form, where user inserts amount and his wallet to get funds back from bitcoin account to his private account. Hope this will helps to understand.
UPDATE 2 I have changed construction for that and seems to is working very well, basically is looking for "Unable" word as transaction ID doesn't have that word and other exception I am getting is "Unable to connect to server..." Thank you for guiding me. Any feedback ?
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$e->getMessage();
}
// exit;
if (!strpos($e,'Unable') !== false){
header("Location: mywallet.php?error=done");
die();
} else {
header("Location: mywallet.php?error=true");
die();
}
What bitcoin php library are you using? Looks like maybe this one?
If that's the case, it doesn't return an error message, it throws BitCoinClientException
So you need something like
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
echo $e->getMessage();
}
Updating
The ob_start seems superfluous because you don't output anything before the header location. Unless you have output something before you've reached this point in which case you can't send a header. So you'd need to move the ob_start up towards the top of the script before any output.
Also you aren't sending message to the wallet.php script. Or are you done with it at that point?
RE: update 2
One thing I might add is the possibility of some other exception message occuring we haven't thought of yet that doesn't contain the "Unable." I'd do something more like:
$errorOccured = false;
try {
$message = ($bitcoin->sendfrom($mywallet,$to_wallet,$wammount));
}
catch (Exception $e) {
$errrorMessage = $e->getMessage();
$errorOccured = true;
}
if (!$errorOccured) {
...
}
else {
header("Location: mywallet.php?error=true&errormsg=" . $errorMessage);
...
}
This would require modifying mywallet.php to accept $errorMessage as an additional GET parameter so you can send it back to the user. Might be nice to additionally use another parameter for sending $message on success which would contain the transaction ID.
Related
Im developing an API in php, and i ran into a problem, basically http_response_code(int $code); behaviour is unpredictable, it just always gets sent at all costs if present anywhere in the code, and after that, naturally i cannot set another http_response_code(int $otherCode) as headers are already sent. I do not know what i am doing wrong, but i think i can boldly assume that http_response_code(int $code); can be used conditionally because it makes all the sense for me.
My question is, how this problem should be solved? I have to use the correct response codes, is there a working alternative which does not use rng to decide if it obeys an if statement?
PHP version is 7.4.5
smol version:
/* CASE 1 */
if(false){
http_response_code(401);
echo json_encode($someErrorMessage);
die;
}
http_response_code(200);
echo json_encode($someResponse);
//Expectation: 200 response code & $someResponse json
//Result: 401 response with no message at all
/* CASE 2 */
if(false){
//http_response_code(401);
echo json_encode($someErrorMessage);
die;
}
http_response_code(200);
echo json_encode($someResponse);
//Expectation: 200 response code & $someResponse json
//Result: 200 response code & json
Actual code:
try{
if(empty(getallheaders()['Authorization'])){
throw new WSException("oAuth access token missing from request");
}
$user = new Admin(getallheaders()['Authorization']);//Authenticate user, get data(throws WSException)
}
catch(WSException $e){ //Unauthenticated, send 401 header + message
http_response_code(401);
echo $e->getMessage();
die;
}
/* GET USER DATA (SELF) */
#region GET USER DATA (SELF)
if($r == "get_self"){ //Return user object as json
try{
/* BASIC DATA //$user already has all user data after authentication with `new Admin();` */
if(!empty($user->profile_picture)){ //TODO: Function needed to filePHP
$user->profile_picture = "{path/to/file.php}".$user->profile_picture;
}
http_response_code(200);
echo json_encode($user, JSON_UNESCAPED_SLASHES); //Unescaped slashes to send correct urls
//An error cant really happen here rn, but when there is a possibility, it would be:
//if($someError){
// http_response_code(401);
// throw new WSException("Something gone wrong");
//}
}catch(WSException $e){
echo json_encode($e->getMessage());
}
die;
}
#endregion
The actual problem was that empty(getallheaders()['Authorization']) returned true.
var_dump(empty(getallheaders()['Authorization']));
//Result: boolean: false
The thing is, if the value of getallheaders()['Authorization'] is not used, or loaded into a variable, it's actually empty in an if statement
if(empty(getallheaders()['Authorization'])){
//statement true, code gets executed
}
Solution:
if(empty($authHeader = getallheaders()['Authorization'])){
//statement false, code does not get executed
}
I am using Amazon SES for sending emails, my final sending code being
try {
$result = $sesClient->sendEmail($email);
$messageId = $result->get('MessageId');
$result['success'] = $messageId;
} catch (Aws\Ses\Exception\SesException $e) {
$result['error'] = $e;
}
At the end of my query loop I want to gather all the errors and having them sent by email, but the problem is that only one error has about 7000 characters and that is because either if I catch Exception or Aws\Ses\Exception\SesException, I also get information from GuzzleHttp\Exception\RequestException: 'GuzzleHttp\Exception\ClientException' and many other infos which I do not realy need. Is there any way I can restrict the message with the main error message, which, in my case, was using an email with no #domain.com attached.
} catch (Aws\Ses\Exception\SesException $e) {
$result['error'] = $e->getMessage();
}
I'm trying to make a website by using PHP and when I run it, it comes back The sharedweb.uniwebsite.ac.uk page isn't working sharedweb.uniwebsite.ac.uk is currently unable to handle this request. 500 And when I click on the Details tab, I get Press the reload button to resubmit the data needed to load the page. Which I have done. The previous pages do work and I'm trying to work on the login page and when I go Register button, that's when I get the error
EDIT
The code that's causing the error is
<?php
// include function files for this application
require_once('bookmark_fns.php');
//create short variable names
$email=$_POST['email'];
$username=$_POST['username'];
$passwd=$_POST['passwd'];
$passwd2=$_POST['passwd2'];
// start session which may be needed later
// start it now because it must go before headers
session_start();
try {
// check forms filled in
if (!filled_out($_POST)) {
throw new Exception('You have not filled the form out correctly. Please go back and try again.');
}
// email address not valid
if (!valid_email($email)) {
throw new Exception('That is not a valid email address. Please go back and try again.');
}
// passwords not the same
if ($passwd != $passwd2) {
throw new Exception('The passwords you entered do not match. Please go back and try again.');
}
// check password length is ok
// ok if username truncates, but passwords will get
// munged if they are too long.
if (!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z]{6,12}$/)', $passwd)) {
throw new Exception('Your password must be between 6 and 12 characters inclusive. Please go back and try again.');
}
// attempt to register
// this function can also throw an exception
register($username, $email, $passwd);
// register session variable
$_SESSION['valid_user'] = $username;
// provide link to members page
do_html_header('Registration successful');
echo "Welcome " $_POST["username"];
echo 'Your registration was successful. Go to the members page to start setting up your bookmarks!';
do_html_url('member.php', 'Go to members page');
// end page
do_html_footer();
}
catch (Exception $e) {
do_html_header('Warning:');
echo $e->getMessage();
do_html_footer();
exit;
}
?>
EDIT #2
It's still not working
There is an PHP error somewhere. To show the error add the following lines at the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
(remove them after fixing the error, to not expose any secrets later)
Possibility 2 would be to check your error.log, which will tell you why its not working too.
Currently, i am trying a simple code of sending/receiving messages using ZMQ. The code is as below
/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$retries = 5;
$sending = true;
/* Start a loop */
do {
try {
/* Try to send / receive */
if ($sending) {
echo "Sending message\n";
$queue->send("This is a message", ZMQ::MODE_NOBLOCK);
$sending = false;
} else {
echo "Got response: " . $queue->recv(ZMQ::MODE_NOBLOCK) . "\n";
echo 'Complete';
break;
}
} catch (ZMQSocketException $e) {
/* EAGAIN means that the operation would have blocked, retry */
if ($e->getCode() === ZMQ::ERR_EAGAIN) {
echo " - Got EAGAIN, retrying ($retries)\n";
} else {
die(" - Error: " . $e->getMessage());
}
}
/* Sleep a bit between operations */
usleep(5);
} while (--$retries);
When i run this script in console, my output is
Sending message
Got response:
Complete
I believe that though there are no errors thrown, but still my message is not actually sent. I also ran netstat command but i didn't found any process listening on port 5555. Ideally there should be one(current). But no exception is thrown while making connection.
Is there something which i am missing?
When you say no process is listening on port 5555, it probably means that your server is not up and running. Your client will not throw any errors even if there is no server, it just sets up and waits for the server to come online (with your particular setup here, at least).
In this case, since you're using non-blocking mode, it'll send your message on the first pass through the loop (why are you sending the message in the loop at all?), but it won't actually send anything because the server isn't there. Then it'll attempt to receive on the second pass through the loop, but since the socket isn't ready to receive it looks like it'll just fail silently, without throwing an exception. Since no exception is thrown, it gets to your break statement, quits the loop, and you're done.
First things first, your send call should happen before the loop, it's something you want to do only once.
Then, when you recv, store the result in a variable and test for emptiness. Leave the try/catch code. The result should be something like this:
/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$retries = 5;
echo "Sending message\n";
$queue->send("This is a message", ZMQ::MODE_NOBLOCK);
/* Start a loop */
do {
try {
/* Try to receive */
$response = $queue->recv(ZMQ::MODE_NOBLOCK);
if (!empty($response)) {
echo "Got response: " . $response . "\n";
echo 'Complete';
break;
}
else {
echo "we probably haven't even sent the original request yet, retrying ($retries)\n";
}
}
catch (ZMQSocketException $e) {
/* EAGAIN means that the operation would have blocked, retry */
if ($e->getCode() === ZMQ::ERR_EAGAIN) {
echo " - Got EAGAIN, retrying ($retries)\n";
} else {
die(" - Error: " . $e->getMessage());
}
}
/* Sleep a bit between operations */
usleep(5);
} while (--$retries);
echo "END OF LINE";
... keep in mind this is a minor fix to the client code that makes it behave a little more rationally, I still believe your actual problem is that the server isn't running.
Please add the server code. You are showing the client code. Since the problem seems to be in the server, and you also state that the server is not visible with netstat, the problem is most probably there.
I am having trouble validating callbacks from WorldPay for an e-commerce website.
According to the documentation WorldPay should POST a parameter named "transStatus" with a value of "Y" for successful transactions.
This seems straightforward enough so I have written a simple validation function that looks for this value:
private function validateRequest() {
if ($_POST['transStatus'] == "Y"){
return true;
} else {
throw new Exception("Transaction failed");
die();
}
}
}
And when the callback page is run this function is called with a try like so:
try {$this->validateRequest()}
catch (Exception $e) {
mail("email#address.com", $e->getMessage(), $e->getTraceAsString());
throw new Exception("Could not validate payment.")
die();
}
Unfortunately when I test this WorldPay processes the payment successfully but the order is not completed by the rest of my code. I have checked my log files but am unable to see any exceptions or errors.
What is the best approach to take from here? How should I proceed in resolving this issue?
Here's how I resolved this in case anyone encounters a similar problem and stumbles across this in the future:
When I checked the contents of $_POST I realized that it was receiving "Y\n" instead of simply "Y", which it was expecting. Here's what I replaced the code with
if (strpos($_POST['transStatus'], 'Y') !== FALSE) { /* Order is verified */ } else { /* Order is not verified */ }
As you can, now the code checks if 'Y' is found anywhere in the response. This works because there are only three possible responses worldpay will send: 'Y', 'N', 'C'.