Значение параметра для платежной системы - Paypal payment.php - Как связать? - PullRequest
0 голосов
/ 19 октября 2019

Я настраиваю автоматическую систему оплаты для друга. Скрипт работает нормально, и исправленная сумма 5 € = 40.000 LP вставлена ​​в базу данных.

Но если я хочу дать клиенту возможность выбрать сумму, которую он хочет заплатить, обработайте скрипт 5 € для API PayPal.

Вот код, который я использую: https://github.com/EvolutedNewMedia/paypal-example

Я внес некоторые изменения в скрипт и попросил Google помочь. Я не знаю, как искать ответ.

Моя попытка была дать api сумму и цену, как вы видите.

То есть donate.tpl




<!-- START BLOCK : donatepage -->

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Donate</title>
</head>
<body>
<center>
<br><font size="5"><strong>Donate with</strong></font><br/>
<br/><img src="paypal_PNG22.png" width="100" height="100">
<br/>
<br/>
<br/>
<form>
 <p>Select Payment</p>
  <label>

    <select name="Payment" size="9" >>
      <option value="5">5€ = 40.000LP</option>
      <option value="10">10€ = 84.000 LP (Bonus 5%)</option>
      <option value="15">15€ = 132.000 LP (Bonus 10%)</option>
      <option value="20">20€ = 184.000 LP (Bonus 15%)</option>
      <option value="25">25€ = 240.000 LP (Bonus 20%)</option>
      <option value="30">30€ = 300.000 LP (Bonus 25%)</option>
      <option value="35">35€ = 364.000 LP (Bonus 30%)</option>
      <option value="40">40€ = 432.000 LP (Bonus 35%)</option>
    </select>
  </label>
</form>
<br/>    
<br/>   
<br/>   
<br/>   
        <form class="paypal" action="payments.php" method="post" id="paypal_form">
        <input type="hidden" name="cmd" value="_xclick" />
        <input type="hidden" name="no_note" value="1" />
        <input type="hidden" name="lc" value="DE" />
        <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
        <input type="hidden" name="first_name" value="Customer's First Name" />
        <input type="hidden" name="last_name" value="Customer's Last Name" />
        <input type="hidden" name="payer_email" value="customer@example.com" />
        <input type="hidden" name="item_number" value={uid} / >
        <input type="hidden" name="item_amount" value="Payment" / >
        <input type="submit" name="submit" value="Submit Payment"/>
    </form>
</center>
</body>
</html>



<!-- END BLOCK : donatepage -->





<!-- START BLOCK : error -->

<div class="areaopac color3" style="background-color:#FFD4D4;">

    <div id="padding">

        <div id="error">{title}</div>

        <div id="content_page">{msg}</div>

    </div>

</div>

<!-- END BLOCK : error -->



<!-- START BLOCK : success -->

<div class="areaopac color3" style="background-color:#D4FFD4;">

    <div id="padding">

        <div id="success">{title}</div>

        <div id="content_page">{msg}</div>

    </div>

</div>

<!-- END BLOCK : success -->

, то есть payment.php




// Product being purchased.


switch($_POST['Payment']){
case '5':
    $itemName = '40000';

    $itemAmount = 5.00;
break;
case '10':
    $itemName = '84000';

    $itemAmount = 10.00;
break;
case '15':
    $itemName = '132000';

    $itemAmount = 15.00;
break;
case '20':
    $itemName = '184000';

    $itemAmount = 20.00;
break;
case '25':
    $itemName = '240000';

    $itemAmount = 25.00;
break;
case '30':
    $itemName = '300000';

    $itemAmount = 30.00;
break;
case '35':
    $itemName = '364000';

    $itemAmount = 35.00;
break;
case '40':
    $itemName = '432000';

    $itemAmount = 40.00;
break;
default:
    $itemName = '40000';

    $itemAmount = 5.00;
}

$itemPrice = 40000;



// Include Functions

require 'functions.php';



// Check if paypal request or response

if (!isset($_POST["txnid"]) && !isset($_POST["txn_type"])) {



    // Grab the post data so that we can set up the query string for PayPal.

    // Ideally we'd use a whitelist here to check nothing is being injected into

    // our post data.

    $data = [];

    foreach ($_POST as $key => $value) {

        $data[$key] = stripslashes($value);

    }



    // Set the PayPal account.

    $data['business'] = $paypalConfig['email'];



    // Set the PayPal return addresses.

    $data['return'] = stripslashes($paypalConfig['return_url']);

    $data['cancel_return'] = stripslashes($paypalConfig['cancel_url']);

    $data['notify_url'] = stripslashes($paypalConfig['notify_url']);



    // Set the details about the product being purchased, including the amount

    // and currency so that these aren't overridden by the form data.

    $data['item_name'] = $itemName;

    $data['amount'] = $itemAmount;

    $data['currency_code'] = 'EUR';

    $data['item_price'] = $itemPrice;



    // Add any custom fields for the query string.

    //$data['custom'] = USERID;



    // Build the query string from the data.

    $queryString = http_build_query($data);



    // Redirect to paypal IPN

    header('location:' . $paypalUrl . '?' . $queryString);

    exit();



} else {

    // Handle the PayPal response.



    // Create a connection to the database.

    $db = new mysqli($dbConfig['host'], $dbConfig['username'], $dbConfig['password'], $dbConfig['name']);

    // Assign posted variables to local data array.

    $data = [

        'item_name' => $_POST['item_name'],

        'item_number' => $_POST['item_number'],

        'payment_status' => $_POST['payment_status'],

        'payment_amount' => $_POST['mc_gross'],

        'payment_currency' => $_POST['mc_currency'],

        'txnid' => $_POST['txnid'],

        'receiver_email' => $_POST['receiver_email'],

        'payer_email' => $_POST['payer_email'],

        'custom' => $_POST['custom'],

    ];



    // We need to verify the transaction comes from PayPal and check we've not

    // already processed the transaction before adding the payment to our

    // database.

    if (verifyTransaction($_POST) && checkTxnid($data['txnid'])) {

        if (addPayment($data) !== false) {

            // Payment successfully added.

        }

    }

}

и functions.php


/**
 * Verify transaction is authentic
 *
 * @param array $data Post data from Paypal
 * @return bool True if the transaction is verified by PayPal
 * @throws Exception
 */
function verifyTransaction($data) {
    global $paypalUrl;

    $req = 'cmd=_notify-validate';
    foreach ($data as $key => $value) {
        $value = urlencode(stripslashes($value));
        $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i', '${1}%0D%0A${3}', $value); // IPN fix
        $req .= "&$key=$value";
    }

    $ch = curl_init($paypalUrl);
    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_SSLVERSION, 6);
    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_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
    $res = curl_exec($ch);

    if (!$res) {
        $errno = curl_errno($ch);
        $errstr = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL error: [$errno] $errstr");
    }

    $info = curl_getinfo($ch);

    // Check the http response
    $httpCode = $info['http_code'];
    if ($httpCode != 200) {
        throw new Exception("PayPal responded with http code $httpCode");
    }

    curl_close($ch);

    return $res === 'VERIFIED';
}

/**
 * Check we've not already processed a transaction
 *
 * @param string $txnid Transaction ID
 * @return bool True if the transaction ID has not been seen before, false if already processed
 */
function checkTxnid($txnid) {
    global $db;

    $txnid = $db->real_escape_string($txnid);
    $results = $db->query('SELECT * FROM `TBL_LaghaimPointUser` WHERE txnid = \'' . $txnid . '\'');

    return ! $results->num_rows;
}

/**
 * Add payment to database
 *
 * @param array $data Payment data
 * @return int|bool ID of new payment or false if failed
**/ 


function addPayment($data) 
    {
    global $db;
    if (is_array($data)) 
        {

        $stmt = $db->prepare('UPDATE `TBL_LaghaimPointUser` SET txnid=?, lpu_user_lag_point= lpu_user_lag_point + ? WHERE lpu_user_idx =?');
        $stmt->bind_param
        (
            'sds',
            $data['txnid'],
            $data['item_name'],
            $data['item_number']
        );

        $stmt->execute();
        $stmt->close();

        return $db->insert_id;
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...