繁体   English   中英

Square Connect-自定义表单

[英]Square Connect - Customizing the Form

我正在尝试创建一个付款表格,该表格允许托儿中心接受客户通过输入数字指定的付款。 我已经获得了可以在其Github上找到的基本设置的基本表格,因此我可以正确设置并运行。 我的问题是我是一名前端设计师,无法弄清楚如何获得其他领域的信息。 我拥有运行Square Connect API所需的所有文件。 这是我到目前为止的相关代码...

我的表格(在payment.php中):

  <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: 'MY-APPLICATION-ID',
      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: 'Postal Code'
      },
      // 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.
      //   {
      //     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: {
        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
        }
      }
    });
    function submitButtonClick(event) {
      event.preventDefault();
      sqPaymentForm.requestCardNonce();
    }
</script>
<form class="uk-form billing-form uk-flex uk-flex-wrap" id="form" novalidate action="/payment-portal/process-card.php" method="post">
    <div class="personal-info uk-flex uk-flex-column">
            <div class="billing-form-group uk-flex uk-flex-space-between">
            <input type="text" placeholder="First Name" id="given_name" class="uk-form-large" style="margin-bottom: 1rem;">
            <input type="text" placeholder="Last Name" id="family_name" class="uk-form-large">
        </div>
        <input type="text" placeholder="Billing Address" class="uk-form-large">
        <input type="text" placeholder="City" class="uk-form-large">
        <select class="uk-form-large">
            <option value="AL">Alabama</option>
            <option value="AK">Alaska</option>
            <option value="AZ">Arizona</option>
            <option value="AR">Arkansas</option>
            <option value="CA">California</option>
            <option value="CO">Colorado</option>
            <option value="CT">Connecticut</option>
            <option value="DE">Delaware</option>
            <option value="DC">District Of Columbia</option>
            <option value="FL">Florida</option>
            <option value="GA">Georgia</option>
            <option value="HI">Hawaii</option>
            <option value="ID">Idaho</option>
            <option value="IL">Illinois</option>
            <option value="IN">Indiana</option>
            <option value="IA">Iowa</option>
            <option value="KS">Kansas</option>
            <option value="KY">Kentucky</option>
            <option value="LA">Louisiana</option>
            <option value="ME">Maine</option>
            <option value="MD">Maryland</option>
            <option value="MA">Massachusetts</option>
            <option value="MI">Michigan</option>
            <option value="MN">Minnesota</option>
            <option value="MS">Mississippi</option>
            <option value="MO">Missouri</option>
            <option value="MT">Montana</option>
            <option value="NE">Nebraska</option>
            <option value="NV">Nevada</option>
            <option value="NH">New Hampshire</option>
            <option value="NJ">New Jersey</option>
            <option value="NM">New Mexico</option>
            <option value="NY">New York</option>
            <option value="NC">North Carolina</option>
            <option value="ND">North Dakota</option>
            <option value="OH">Ohio</option>
            <option value="OK">Oklahoma</option>
            <option value="OR">Oregon</option>
            <option value="PA">Pennsylvania</option>
            <option value="RI">Rhode Island</option>
            <option value="SC">South Carolina</option>
            <option value="SD">South Dakota</option>
            <option value="TN">Tennessee</option>
            <option value="TX">Texas</option>
            <option value="UT">Utah</option>
            <option value="VT">Vermont</option>
            <option value="VA">Virginia</option>
            <option value="WA">Washington</option>
            <option value="WV">West Virginia</option>
            <option value="WI">Wisconsin</option>
            <option value="WY">Wyoming</option>
        </select>
        <input type="text" placeholder="Zip Code" id="sq-postal-code" class="uk-form-large">
    </div>
    <div class="card-info uk-flex uk-flex-column">
        <input type="text" placeholder="Phone Number" class="uk-form-large">
        <input type="email" placeholder="Email" class="uk-form-large">
        <div class="billing-form-group uk-flex uk-flex-space-between">
            <input type="text" placeholder="Amount" class="uk-form-large">
            <select class="uk-form-large">
                <option>Visa</option>
                <option>Mastercard</option>
                <option>Discover</option>
                <option>American Express</option>
            </select> 
        </div>
        <input type="text" placeholder="Card Number" id="sq-card-number" class="uk-form-large">
        <div class="exp-cvv-group uk-flex uk-flex-space-between">
            <input type="text" placeholder="MM/YY" id="sq-expiration-date" class="uk-form-large">
            <input type="text" placeholder="CVV" id="sq-cvv" class="uk-form-large uk-form-width-mini">
        </div>
    </div>
    <input type="hidden" id="card-nonce" name="nonce">
    <div class="billing-button-container">
        <input type="submit" onclick="submitButtonClick(event)" id="card-nonce-submit" class="button mid-blue-button billing-button"></div>
    </div>
</form>
<div id="errors"></div>

我的处理器(在process-card.php中):

<?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 ID of the business location to associate processed payments with.
# If you're testing things out, use a sandbox location ID.
#
# See [Retrieve your business's locations](https://docs.connect.squareup.com/articles/getting-started/#retrievemerchantprofile)
# for an easy way to get your business's location IDs. If the php page is not rendering, make sure 
# that error reporting is turned on. If you get an error that says, "Fatal error: Uncaught 
# exception 'SquareConnect\ApiException' with message 'API call to 
# https://connect.squareup.com/v2/locations failed, but for an unknown reason." This is most likely 
# caused by blocked outgoing ports in the web server. Contact host provider for resolution.
$location_id = 'MY-LOCATION-ID';
# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
$access_token = 'MY-ACCESS-TOKEN';
# 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;
}
$transaction_api = new \SquareConnect\Api\TransactionApi();
$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" => "USD"
  ),
  # 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 = $transaction_api->charge($access_token, $location_id, $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>";
}

请注意,我已将对MY的所有引用替换为适用于我的应用程序的正确值。 (正如我说的,我有基本的工作形式。)

我并不是在寻找任何人自己编写所有代码,但是有人可以指出我的入门方向。 我需要获取客户信息以完成付款,并可能附带一条注释以列出孩子。 我知道我将必须添加表单字段以合并注释,但是我什至不知道如何使该名称生效,因此我需要先将其记下来,然后再找出其余的内容。 我的另一件事是我需要知道如何添加父母可以在其想支付的金额中添加的金额字段。 我可以在这里看到process-card.php中的部分:

"amount_money" => array (
  "amount" => 100,
  "currency" => "USD"
),

我不知道这是否只是在说最低收费额,但无论如何每次收费似乎都只有$ 1.00。 我知道它没有连接到表单字段,但是我不确定如何连接它。

我已经在这里这里阅读了文档,但是对我来说,大多数是希腊文。 如果有人可以帮助我使自定义金额生效,我想我可以找出其余的金额。 让我知道是否需要提供其他信息。

几件事

  • 在您的process-card.php ,每次从API中获取您的位置可能会比较容易,而不是对其进行硬编码(如果您仅计划拥有一个位置)

     $location_api = new \\SquareConnect\\Api\\LocationApi(); $location_id = $location_api->listLocations($access_token)->getLocations()[0]->getId(); 
  • 在较高级别上,信用卡现时与表单中的所有其他命名变量一起以表单的形式传递。 我已经编辑了您的代码以传递更多信息,并将其显示在另一侧。

`

<script type="text/javascript" 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: 'XXXXX',
      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: 'Postal Code'
      },
      // 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.
      //   {
      //     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: {
        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
      }
  }
});
    function submitButtonClick(event) {
        event.preventDefault();
        sqPaymentForm.requestCardNonce();
    }
</script>
<form class="uk-form billing-form uk-flex uk-flex-wrap" id="form" novalidate action="/payment-portal/process-card.php" method="post">
    <div class="personal-info uk-flex uk-flex-column">
        <div class="billing-form-group uk-flex uk-flex-space-between">
            <input type="text" placeholder="First Name" id="given_name" class="uk-form-large" style="margin-bottom: 1rem;">
            <input type="text" placeholder="Last Name" id="family_name" class="uk-form-large">
        </div>
        <input type="text" placeholder="Billing Address" class="uk-form-large">
        <input type="text" placeholder="City" class="uk-form-large">
        <select class="uk-form-large">
            <option value="AL">Alabama</option>
            <option value="AK">Alaska</option>
            <option value="AZ">Arizona</option>
            <option value="AR">Arkansas</option>
            <option value="CA">California</option>
            <option value="CO">Colorado</option>
            <option value="CT">Connecticut</option>
            <option value="DE">Delaware</option>
            <option value="DC">District Of Columbia</option>
            <option value="FL">Florida</option>
            <option value="GA">Georgia</option>
            <option value="HI">Hawaii</option>
            <option value="ID">Idaho</option>
            <option value="IL">Illinois</option>
            <option value="IN">Indiana</option>
            <option value="IA">Iowa</option>
            <option value="KS">Kansas</option>
            <option value="KY">Kentucky</option>
            <option value="LA">Louisiana</option>
            <option value="ME">Maine</option>
            <option value="MD">Maryland</option>
            <option value="MA">Massachusetts</option>
            <option value="MI">Michigan</option>
            <option value="MN">Minnesota</option>
            <option value="MS">Mississippi</option>
            <option value="MO">Missouri</option>
            <option value="MT">Montana</option>
            <option value="NE">Nebraska</option>
            <option value="NV">Nevada</option>
            <option value="NH">New Hampshire</option>
            <option value="NJ">New Jersey</option>
            <option value="NM">New Mexico</option>
            <option value="NY">New York</option>
            <option value="NC">North Carolina</option>
            <option value="ND">North Dakota</option>
            <option value="OH">Ohio</option>
            <option value="OK">Oklahoma</option>
            <option value="OR">Oregon</option>
            <option value="PA">Pennsylvania</option>
            <option value="RI">Rhode Island</option>
            <option value="SC">South Carolina</option>
            <option value="SD">South Dakota</option>
            <option value="TN">Tennessee</option>
            <option value="TX">Texas</option>
            <option value="UT">Utah</option>
            <option value="VT">Vermont</option>
            <option value="VA">Virginia</option>
            <option value="WA">Washington</option>
            <option value="WV">West Virginia</option>
            <option value="WI">Wisconsin</option>
            <option value="WY">Wyoming</option>
        </select>
        <input type="text" placeholder="Zip Code" id="sq-postal-code" class="uk-form-large">
    </div>
    <div class="card-info uk-flex uk-flex-column">
    <input name="phone" type="text" placeholder="Phone Number" class="uk-form-large">
        <input name="email" type="email" placeholder="Email" class="uk-form-large">
        <div class="billing-form-group uk-flex uk-flex-space-between">
            <input name="amount" type="text" placeholder="Amount" class="uk-form-large">
            <select class="uk-form-large">
                <option>Visa</option>
                <option>Mastercard</option>
                <option>Discover</option>
                <option>American Express</option>
            </select> 
        </div>
        <input type="text" placeholder="Card Number" id="sq-card-number" value="4111111111111111" class="uk-form-large">
        <div class="exp-cvv-group uk-flex uk-flex-space-between">
            <input type="text" placeholder="MM/YY" value="0121" id="sq-expiration-date" class="uk-form-large">
            <input type="text" placeholder="CVV" id="sq-cvv" class="uk-form-large uk-form-width-mini">
        </div>
    </div>
    <input type="hidden" id="card-nonce" name="nonce">
    <div class="billing-button-container">
        <input type="submit" onclick="submitButtonClick(event)" id="card-nonce-submit" class="button mid-blue-button billing-button">
    </div>
</div>
</form>
<div id="errors"></div>

<?php
include 'vendor/autoload.php';

$access_token = 'XXXXXX';

echo'<pre>';
var_dump($_POST);
echo '</pre>';

$location_api = new \SquareConnect\Api\LocationApi();

$location_id = $location_api->listLocations($access_token)->getLocations()[0]->getId();
# 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;
}

$transaction_api = new \SquareConnect\Api\TransactionApi();
$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" => $_POST['amount']*100,
    "currency" => "USD"
  ),
  # 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 = $transaction_api->charge($access_token, $location_id, $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>";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM