Jump to content

imgrooot

Members
  • Content Count

    331
  • Joined

  • Last visited

  • Days Won

    1

imgrooot last won the day on May 16 2018

imgrooot had the most liked content!

Community Reputation

1 Neutral

About imgrooot

  • Rank
    Advanced Member

Recent Profile Visitors

2,164 profile views
  1. Good to know. Now I have another problem. How do I pass a value of a variable from another page to a json processing page? See the code below. Look at "'amount' => 1099". I would like to replace this number with my own product amount($total_amount = 20) that's listed on the index.php. If I call it directly on this server.php file, it'll get me that error again "Unexpected token < in JSON at position". //SERVER.PHP PAGE require_once '../library/stripe/init.php'; \Stripe\Stripe::setApiKey('sk_test_GPxllXVIfWnuczEjLAGh7BaX'); header('Content-Type: application/json'); # retrieve JSON from POST body $json_str = file_get_contents('php://input'); $json_obj = json_decode($json_str); try { // Create the PaymentIntent $intent = \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'payment_method' => $json_obj->payment_method_id, # A PaymentIntent can be confirmed some time after creation, # but here we want to confirm (collect payment) immediately. 'confirm' => true, # If the payment requires any follow-up actions from the # customer, like two-factor authentication, Stripe will error # and you will need to prompt them for a new payment method. 'error_on_requires_action' => true, ]); generateResponse($intent); } catch (\Stripe\Exception\ApiErrorException $e) { // Display error on client echo json_encode(['error' => $e->getMessage()]); } function generateResponse($intent) { if ($intent->status == 'succeeded') { // Handle post-payment fulfillment echo json_encode(['success' => true]); } else { // Any other status would be unexpected, so error echo json_encode(['error' => 'Invalid PaymentIntent status']); } }
  2. Actually no "/site/server.php" won't work. I've tried it and for some reason it duplicates the site name like this "http://localhost/site/site/server.php". So it seems like the only way is with absolute urls. And yes I will have to change it when on live server.
  3. Alright so I think I may have solved the problem. Stripe's documentation sucks at explaining it properly. // REPLACE /pay WITH YOUR OWN URL THAT PROCESSES THE SERVER SIDE CODE. THAT CODE FILE HAS TO BE JSON AND NOT HTML. fetch('/pay', // THE URL HAS TO BE GLOBAL AND NOT RELATIVE. // SO FOR MY EXAMPLE, I HAD TO PUT THE FULL URL INSTEAD OF JUST THE PAGE FILE. fetch('http://localhost/site/server.php', I still have to do additional testing but so far it works. No errors.
  4. Yes but I think the reason why is because the url doesn't seem to be correct. // USING THIS URL /server.php // WILL GIVE ME THIS http://localhost/server.php //BUT I NEED THE URL TO BE LIKE THIS http://localhost/site/server.php How do do this? I've tried "../server.php" but that's all it shows. It doesn't show the main site directory.
  5. So if I do /server.php url in it's place, i still get the same error "Unexpected token < in JSON at position" error. Why would it do that if it's a correct url?
  6. I am using the Stripe API. Been at it for a day and still no luck. I keep getting this error. POST http://localhost/pay 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position // this error is because of this line .then(handleServerResponse); It has specifically to do with this function. function handlePaymentMethodResult(result) { if (result.error) { // An error happened when collecting card details, show it in the payment form resultContainer.textContent = result.error.message; } else { // Otherwise send paymentMethod.id to your server (see Step 3) fetch('/pay', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ payment_method_id: result.paymentMethod.id }) }).then(function(result) { return result.json(); }).then(handleServerResponse); } } What is "/pay" suppose to be exactly? I assumed it was a page where i run my server process code. But it keeps giving me that error no matter what I try it. Here is my full mode. INDEX.php <?php require_once 'library/stripe/init.php'; ?> <!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title>Title</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="---"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="shortcut icon" href="/images/favicon.png" /> <link href="css/screen.css?v=1.1" media="screen, projection" rel="stylesheet" /> <script src="javascripts/jquery-3.2.0.min.js"></script> <script src="https://js.stripe.com/v3/"></script> <script src="javascripts/client.js" defer></script> </head> <body> <?php $total_amount = 20; ?> <div id="payment-box"> <div id="p-box-heading"> Total Amount: <span>$<?php if(empty($total_amount)){echo '0.00';}else{echo $total_amount;} ?> CAD</span> </div> <div id="p-box-body"> <form id="payment-form"> <div id="card-element"><!-- placeholder for Elements --></div> <button id="card-button">Submit Payment</button> <p id="payment-result"><!-- we'll pass the response from the server here --></p> </form> </div> </div> </body> CLIENT.js var stripe = Stripe("pk_test_ROlyXpDaTbqIvSpndWp7IdxW"); var elements = stripe.elements(); var cardElement = elements.create('card'); cardElement.mount('#card-element'); var form = document.getElementById('payment-form'); var resultContainer = document.getElementById('payment-result'); cardElement.on('change', function(event) { if (event.error) { resultContainer.textContent = event.error.message; } else { resultContainer.textContent = ''; } }); form.addEventListener('submit', function(event) { event.preventDefault(); resultContainer.textContent = ""; stripe.createPaymentMethod({ type: 'card', card: cardElement, }).then(handlePaymentMethodResult); }); function handlePaymentMethodResult(result) { if (result.error) { // An error happened when collecting card details, show it in the payment form resultContainer.textContent = result.error.message; } else { // Otherwise send paymentMethod.id to your server (see Step 3) fetch('/pay', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ payment_method_id: result.paymentMethod.id }) }).then(function(result) { return result.json(); }).then(handleServerResponse); } } function handleServerResponse(responseJson) { if (responseJson.error) { // An error happened when charging the card, show it in the payment form resultContainer.textContent = responseJson.error; } else { // Show a success message resultContainer.textContent = 'Success!'; } } SERVER.php \Stripe\Stripe::setApiKey('sk_test_GPxllXVIfWnuczEjLAGh7BaX'); header('Content-Type: application/json'); # retrieve JSON from POST body $json_str = file_get_contents('php://input'); $json_obj = json_decode($json_str); try { // Create the PaymentIntent $intent = \Stripe\PaymentIntent::create([ 'amount' => 1099, 'currency' => 'usd', 'payment_method' => $json_obj->payment_method_id, # A PaymentIntent can be confirmed some time after creation, # but here we want to confirm (collect payment) immediately. 'confirm' => true, # If the payment requires any follow-up actions from the # customer, like two-factor authentication, Stripe will error # and you will need to prompt them for a new payment method. 'error_on_requires_action' => true, ]); generateResponse($intent); } catch (\Stripe\Exception\ApiErrorException $e) { // Display error on client echo json_encode(['error' => $e->getMessage()]); } function generateResponse($intent) { if ($intent->status == 'succeeded') { // Handle post-payment fulfillment echo json_encode(['success' => true]); } else { // Any other status would be unexpected, so error echo json_encode(['error' => 'Invalid PaymentIntent status']); } }
  7. I have a "Users" table. I would like to find out the average users sign up in total. This table has a "joined date" column so I can track how many users sign up in a single day. For e.g. August 16 - 10 users August 17 - 20 users Auguest 18 - 30 users The total average of user sign ups would be 20 users based on the above results. So I am wondering how can I create this function? This is my starting query. $get_users = $db->prepare("SELECT user_id FROM users"); $get_users->execute(); $result_users = $get_users->fetchAll(PDO::FETCH_ASSOC); if(count($result_users) > 0) { foreach($result_users as $row) { $user_id = $row['user_id']; } }
  8. 1. What I meant was that originally I had a single browse.php page and included cities as parameters. For e.g. /browse.php?city=new-york. So I changed it to having each city as a separate page like /browse.php/new-york.php. So I am asking if I should leave it as is or change it back? 2. I am using IDs to retrieve the results from the database. If a city parameter ID is ''123", I can grab it form the url and search all the records in that city from the database. Isn't that how it's suppose to be done? If I use both, it would look like this. /browse.php?city=new-york&id=123. I don't know how to do pretty urls so I can't make it like your example.
  9. Really? That's how I had it originally but now I changed it to have a separate page for each city. Guess I'll change it back. Second question, is it okay to have an ID of a city and category as oppose to the name in the URL? Like this. /browse.php?city=123&category=456 Having an ID would make it a lot easier to retrieve data.
  10. This is more of an SEO question. I have a site with couple hundred categories within each city. I was wondering what the best approach is to do them? www.mysite.com/browse/apples?city=new-york www.mysite.com/browse/new-york?category=apples Which one is the better way to do it for seo purposes? If it's the first method, that would mean I would have to create couple hundred pages for those categories yes?
  11. I just realized what the issue was. The votes in the table have a different user_id than what I am currently logged in as. So naturally it will not return any results. Here's a new code based on your suggestion. Works fine. $count_votes = $db->prepare("SELECT SUM(votes) FROM entries WHERE user_id = :user_id"); $count_votes->bindParam(':user_id', $user_id); $count_votes->execute(); $get_votes = $count_votes->fetchColumn();
  12. I have a table with "votes" column. I basically want to retrieve the sum of all the votes columns associated with a user. This is the full code. It gives me "NULL" output. $count_votes = $db->prepare("SELECT SUM(votes) as total FROM entries WHERE user_id = :user_id"); $count_votes->bindParam(':user_id', $user_id); $count_votes->execute(); $t_votes = $count_votes->fetchColumn(); $get_votes = $t_votes['total']; echo $get_votes; But if I remove the user_id bind paramter, it gives me the results. But I need that parameter to show which user has how many votes. $count_votes = $db->prepare("SELECT SUM(votes) as total FROM entries"); $count_votes->execute(); $t_votes = $count_votes->fetchColumn(); $get_votes = $t_votes['total']; echo $get_votes; What am I doing wrong?
  13. Got it. Here is the updated form. It seems to work fine. // Message ID being an ID of individual message rows retrived from the DB. $message_id if(isset($_POST['submit']) AND $_POST['message-id'] == $message_id) { $post_message = trim($_POST['message']); $errors = array(); $db->beginTransaction(); if(empty($post_message)) { $errors[] = 'The message field can not be empty!'; } else { // ADD CODE HERE } if(empty($errors)) { $db->commit(); echo 'success'; } else { $db->rollBack(); } } <form action="" method="post"> <fieldset> <textarea name="message" maxlength="10000" placeholder="What would you like to say?"></textarea> </fieldset> <fieldset> <input type="hidden" name="message-id" value="<?php echo $message_id; ?>" /> <input type="submit" name="submit" value="Submit" /> </fieldset> </form>
  14. I am creating a user inbox system. I am retrieving all the unread messages. Each message row contains a "reply" form. So say I have 10 messages showing on a single page. That's 10 forms. What I would like to know is how can I submit any one of the 10 forms and not have it affect the remaining 9 forms? Here is the basic code. if(isset($_POST['submit'])) { $post_message = trim($_POST['message']); $errors = array(); $db->beginTransaction(); if(empty($post_message)) { $errors[] = 'The message field can not be empty!'; } if(empty($errors)) { $db->commit(); echo 'success'; } else { $db->rollBack(); } } <form action="" method="post"> <fieldset> <textarea name="message" maxlength="10000" placeholder="What would you like to say?"></textarea> </fieldset> <fieldset> <input type="submit" name="submit" value="Submit" /> </fieldset> </form>
  15. Good to know. I will do that from now on.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.