skip to Main Content

I’ve been struggling with a problem that when I try to send an email to the customer and redirect him to paypal website (to pay for a product), then he’s redirected to the paypal website, but the email is not sent (unless i remove the form that is responsible for redirecting to paypal site).

The way I tried was to put it all in one form and then name the button as send, as it is shown in the script.

 <form method="post" action="/order/createOrder.php">
            First Name: <input type="text" name="first_name"><br>
            Last Name: <input type="text" name="last_name"><br>
            Phone number:<br><textarea rows="5" name="phone_num" cols="30"></textarea><br>
                </div>
                    <button class="btn btn-primary float-right" name="send">Order!</button>
                </div>
            </form>

and this is the script for email

<?php

    if (isset($_POST["send"])) {

        $to = "[email protected]";
        $first_name =  $_POST['first_name'];
        $last_name = $_POST['last_name'];
        $phone_num = $_POST['phone_num'];
        $subject = "Zamowienie";

        foreach(Cart::GetRooms() as $room)

        $message = "Name: " . $first_name . "<br>Last name: " . $last_name . "<br>Phone Number:" . $phone_num . "<br> Room:" . $room->GetData()["title"];



        $headers = "From: [email protected]";
        $headers.= "MIME-Version: 1.0rn";
        $headers.= "Content-Type: text/html; charset=ISO-8859-1rn";
        $headers.= "X-Priority: 1rn";


        mail($to, $subject, $message, $headers);
    }

this is the redirection code

<?php
require_once "../settings.php";
require_once BASE_DIR."/lib/PayPal/autoload.php";

use PayPalAuthOAuthTokenCredential;
use PayPalRestApiContext;
use PayPalApiAmount;
use PayPalApiDetails;
use PayPalApiItem;
use PayPalApiItemList;
use PayPalApiPayer;
use PayPalApiPayment;
use PayPalApiRedirectUrls;
use PayPalApiTransaction;


$apiContext = new ApiContext(
    new OAuthTokenCredential(
        PAYPAL_CLIENT_ID,
        PAYPAL_SECRET
    )
);

$apiContext->setConfig([
    "mode" => PAYPAL_MODE
]);

// Create new payer and method
$payer = new Payer();
$payer->setPaymentMethod("paypal");

// Set redirect URLs
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl(PAYPAL_REDIRECT_SUCCESS)
  ->setCancelUrl(PAYPAL_REDIRECT_CANCEL);

$total = 0.0;
$order = [];


$item_list = new ItemList();

foreach (Cart::GetRooms() as $offer) {
      $row = $offer->GetData();
      $item_list = new ItemList();
      $item = new Item();
      $item->setQuantity(1);
      $item->setPrice($row["price"]);
      $item->setCurrency("USD");
      $item->setName( $row["title"]);
      $item->setDescription( $row["short_description"]);
      $item_list->addItem($item);

      $total += $row["price"];
      $order = $row["id"];
}

if ($total === 0.0) {
    http_response_code(404);
    exit("Error: Empty!");
}

// Set payment amount
$amount = new Amount();
$amount->setCurrency("USD")
  ->setTotal($total);

Cart::ClearCart();

// Set transaction object
$transaction = new Transaction();
$transaction->setAmount($amount)
  ->setDescription("Order #2131")
  ->setItemList($item_list);

  // Create the full payment object
$payment = new Payment();
$payment->setIntent('sale')
  ->setPayer($payer)
  ->setRedirectUrls($redirectUrls)
  ->setTransactions(array($transaction));

// Create payment with valid API context
try {
    $payment->create($apiContext);

    // Get PayPal redirect URL and redirect the customer
    $approvalUrl = $payment->getApprovalLink();

    // Redirect the customer to $approvalUrl
    header("Location: $approvalUrl");
  } catch (PayPalExceptionPayPalConnectionException $ex) {
    echo $ex->getCode();
    echo $ex->getData();
    die($ex);
  } catch (Exception $ex) {
    die($ex);
  }

2

Answers


  1. Not being a PHP expert, the way I would solve this is to not use a header redirect:

    header("Location: $approvalUrl");
    

    And instead return some HTML with a <script> that modifies window.location.href to be the $approvalUrl


    Actually I wouldn’t use redirects at all, and would instead upgrade the checkout to this “in context” front-end: https://developer.paypal.com/demo/checkout/#/pattern/server (which keeps your site loaded in the background).

    (If you haven’t seen that front-end in action, you can check out the client-side demo here which will actually load the checkout when a button is clicked: https://developer.paypal.com/demo/checkout/#/pattern/client)

    Furthermore, it looks like you’re using the old v1/payments PayPal-PHP-SDK, so if this is a new integration you should switch over to the latest v2 SDK https://github.com/paypal/Checkout-PHP-SDK

    Login or Signup to reply.
  2. Here an actual JQuery Example:

          paypal.Buttons({
          
        style: {
            layout: 'horizontal',
            color: 'gold',
            shape: 'pill',
            label: 'checkout',
            size: 'responsive',
            tagline: 'true',
        },
        
        // Set up the transaction
        createOrder: function(data, actions) {
            $('#paypalmsg').hide();
            $('#transmsg').show();
            $('#transmsg').html('<b>'+'WAITING ON AUTHORIZATION...'+'</b>');
            $('#chkoutmsg').hide()
            return actions.order.create({
                purchase_units: [{
                    description: 'GnG Order',
                    amount: {
                        value: cartTotal
                    }
                }],
                application_context: {
                  shipping_preference: 'NO_SHIPPING'
                }
                
            });
        },
        
        // Finalize the transaction
        onApprove: function(data, actions) {
            return actions.order.capture().then(function(details) {
              /*return actions.order.get().then(function(orderDetails) { */
                    // Show a success message to the buyer
                    $('#transmsg').html('<b>' + 'AUTHORIZED...' + '</b>');
                    $('#transmsg').append('<br>'+'Transaction completed by: ' + details.payer.name.given_name +' '+ details.payer.name.surname + '<br>' + "Order Id: " + details.id + '<br>' + 'Status: PAID & APPROVED'  + '<br>'+ 'Thank You For Your Order'+ '<br>');
                    if (details.status === "COMPLETED") {
                        window.setTimeout(function() {}, 500)
                         $('#transmsg').append('<b>' + 'Sending Order...Please Wait' + 
                        '</b>'+'<br>');
                        $('#transid').val(details.id);
                        $('#orderstat').val('APPROVED');
                        $('#orderform').submit();
                    } 
              });
    

    Hope that helps

    D

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search