通过Square Up金额总计

时间:2017-10-30 15:00:22

标签: php

我一直在研究PayPal的替代品,用于支付在线支付并从github(https://github.com/square/connect-api-examples/tree/master/connect-examples/v2/php_payment)下载Square Ups演示文件。在使用Square创建帐户并安装Composer后,该演示工作正常,但我注意到付款金额在“process-card.php”的演示中是硬编码的。那么如何从表单输入或数据库值传递金额?

3 个答案:

答案 0 :(得分:0)

好的,这是表单页面:

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
  <title>My Payment Form</title>
    <style>
label{display:inline-block;float:left;width:130px}
/* Customize the "Pay with Credit Card" button */
input[type=submit] {
  min-width: 200px;
  min-height: 20px;
  padding: 1.2em;
  margin-top: 5px;
  line-height: 20px;
  box-shadow: 2px 2px 1px rgb(200, 200, 200);
  background: rgb(255, 255, 255);
  border-radius: 5px;
  border: 1px solid rgb(200, 200, 200);
  font-weight: bold;
  font-size:1em;
  float:left;
  cursor:pointer
}
input[type=submit]:hover {background:orange}



    .sq-input {
      border: 1px solid #ccc;
      margin-bottom: 10px;
      padding: 1px;
      font-size:1em;
      width:200px
    }
    .sq-input--focus {
      outline-width: 5px;
      outline-color: #70ACE9;
      outline-offset: -1px;
      outline-style: auto;
    }
    .sq-input--error {
      outline-width: 5px;
      outline-color: #FF9393;
      outline-offset: 0px;
      outline-style: auto;
    }
    .apple-pay-button {
      display: inline-block;
      background-size: 100% 60%;
      background-repeat: no-repeat;
      background-position: 50% 50%;
      border-radius: 5px;
      border-width: 2px;
      padding: 0px;
      box-sizing: border-box;
      min-width: 200px;
      min-height: 32px;
      max-height: 64px;
  }
  .apple-pay-button-white {
      background-image: -webkit-named-image(apple-pay-logo-black);
      background-color: white;
  }
  </style>
  <script src="https://js.squareup.com/v2/paymentform"></script>
  <script>
    var sqPaymentForm = new SqPaymentForm({

      // Replace this value with your application's ID (available from the merchant dashboard).
      // If you're just testing things out, replace this with your _Sandbox_ application ID,
      // which is also available there.
      applicationId: 'sandbox-sq0idp-xxxxxxxxxxxxxxxxx',
      locationId: 'CBASEBbxxxxxxxxxxxxxxx',
      inputClass: 'sq-input',
      cardNumber: {
        elementId: 'sq-card-number',
        placeholder: "0000 0000 0000 0000"
      },
      cvv: {
        elementId: 'sq-cvv',
        placeholder: 'CVV'
      },
      expirationDate: {
        elementId: 'sq-expiration-date',
        placeholder: 'MM/YY'
      },
      postalCode: {
        elementId: 'sq-postal-code',
        placeholder: 'Postcode'
      },




        amount: {
            elementId: 'sq-amount',
            placeholder: 'Amount'
        },



      inputStyles: [

        // Because this object provides no value for mediaMaxWidth or mediaMinWidth,
        // these styles apply for screens of all sizes, unless overridden by another
        // input style below.
        { fontFamily: 'Arial, Helvetica, sans-serif',
          fontSize: '14px',
          padding: '3px'
        },

        // These styles are applied to inputs ONLY when the screen width is 400px
        // or smaller. Note that because it doesn't specify a value for padding,
        // the padding value in the previous object is preserved.
        {
          mediaMaxWidth: '400px',
          fontSize: '18px',
        }
      ],
      callbacks: {
        methodsSupported: function (methods) {
          // Show the Apple Pay button if Apple Pay is supported.
          if (methods.applePay === true) {
            var element = document.getElementById('pay-button-area');
            element.style.display = 'block';
          }
        },
        cardNonceResponseReceived: function(errors, nonce, cardData) {
          if (errors) {
            var errorDiv = document.getElementById('errors');
            errorDiv.innerHTML = "";
            errors.forEach(function(error) {
              var p = document.createElement('p');
              p.innerHTML = error.message;
              errorDiv.appendChild(p);
            });
          } else {
            // This alert is for debugging purposes only.
            alert('Nonce received! ' + nonce + ' ' + JSON.stringify(cardData));

            // Assign the value of the nonce to a hidden form element
            var nonceField = document.getElementById('card-nonce');
            nonceField.value = nonce;

            // Submit the form
            document.getElementById('form').submit();
          }
        },
        unsupportedBrowserDetected: function() {
          // Alert the buyer that their browser is not supported
        },
        createPaymentRequest: function () {
          return {
            requestShippingAddress: false,
            currencyCode: "GBP",
            countryCode: "GB",

            total: {
              label: "Merchant Name",
              amount: "1.01",
              pending: false,
            },

            lineItems: [
              {
                label: "Subtotal",
                amount: "1.00",
                pending: false,
              },
              {
                label: "Tax",
                amount: "0.01",
                pending: false,
              }
            ]
          };
        },
      }
    });
    function submitButtonClick(event) {
      event.preventDefault();
      sqPaymentForm.requestCardNonce();
    }
  </script>
</head>

<body>
    <h1>My Payment Form</h1>
    <p>github example</p>
    <form id="form" novalidate action="process-card.php" method="post">
        <div id="pay-button-area" style="display:none">
            <button id="sq-apple-pay" class="apple-pay-button apple-pay-button-white" />
        </div>
        <label>Amount</label><div id="amount"></div>
            <br style="clear:both">
        <label>Credit Card</label><div id="sq-card-number"></div>
            <br style="clear:both">
        <label>CVV</label><div id="sq-cvv"></div>
            <br style="clear:both">
        <label>Expiration Date</label><div id="sq-expiration-date"></div>
            <br style="clear:both">
        <label>Postcode</label><div id="sq-postal-code"></div>
            <br style="clear:both">
        <input type="hidden" id="card-nonce" name="nonce">
        <label>&nbsp;</label><input type="submit" onclick="submitButtonClick(event)" id="card-nonce-submit">
    </form>
    <div id="errors"></div>
</body>
</html>

答案 1 :(得分:0)

    <?php

require 'vendor/autoload.php';

# Replace these values. You probably want to start with your Sandbox credentials
# to start: https://docs.connect.squareup.com/articles/using-sandbox/

# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
$access_token = 'sandbox-xxxxxxxxxxxxxxxxx';

# Helps ensure this code has been reached via form submission
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  error_log("Received a non-POST request");
  echo "Request not allowed";
  http_response_code(405);
  return;
}

# Fail if the card form didn't send a value for `nonce` to the server
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
  echo "Invalid card data";
  http_response_code(422);
  return;
}

\SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$locations_api = new \SquareConnect\Api\LocationsApi();

try {
  $locations = $locations_api->listLocations();
  #We look for a location that can process payments
  $location = current(array_filter($locations->getLocations(), function($location) {
    $capabilities = $location->getCapabilities();
    return is_array($capabilities) &&
      in_array('CREDIT_CARD_PROCESSING', $capabilities);
  }));

} catch (\SquareConnect\ApiException $e) {
  echo "Caught exception!<br/>";
  print_r("<strong>Response body:</strong><br/>");
  echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
  echo "<br/><strong>Response headers:</strong><br/>";
  echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
  exit(1);
}

$transactions_api = new \SquareConnect\Api\TransactionsApi();

$request_body = array (

  "card_nonce" => $nonce,

  # Monetary amounts are specified in the smallest unit of the applicable currency.
  # This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
  "amount_money" => array (
    "amount" => 100,
    "currency" => "GBP"
  ),

  # Every payment you process with the SDK must have a unique idempotency key.
  # If you're unsure whether a particular payment succeeded, you can reattempt
  # it with the same idempotency key without worrying about double charging
  # the buyer.
  "idempotency_key" => uniqid()
);

# The SDK throws an exception if a Connect endpoint responds with anything besides
# a 200-level HTTP code. This block catches any exceptions that occur from the request.
try {
  $result = $transactions_api->charge($location->getId(), $request_body);
  echo "<pre>";
  print_r($result);
  echo "</pre>";
} catch (\SquareConnect\ApiException $e) {
  echo "Caught exception!<br/>";
  print_r("<strong>Response body:</strong><br/>");
  echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
  echo "<br/><strong>Response headers:</strong><br/>";
  echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
}
enter code here

答案 2 :(得分:0)

首先,您需要在主要付款表格上显示一个隐藏字段或文本字段...

<input type="text" name="manual-amount">

然后,在process_card页面上,您需要从POST数据中获取传入的表单字段。 (以下是在Python中显示的对不起...),但几乎完全是如何提取NONCE数据的。

nonce = form.getvalue('nonce')
amount = form.getvalue('manual-amount')

下一页后,金额已设置。在该部分中,将硬编码的100替换为您刚刚从上面的POST数据中获得的金额值的整数值...

# Monetary amounts are specified in the smallest unit of the applicable currency.
# This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
amount = {'amount': int(amount), 'currency': 'GBP'}

希望这会给您和其他人一些有关如何使用PHP和其他语言进行操作的想法。