Действие ничего не предпринимая при отправке формы - PullRequest
0 голосов
/ 02 мая 2020

Я пытаюсь настроить форму оплаты размещенных полей PinPayments, и я не понимаю, что я делаю неправильно, но кнопка <submit> ничего не делает. Не перезагружает страницу, ничего не делает. Файл оплаты. php работает правильно, так как при ручном вводе этого URL-адреса он работает нормально.

Форма находится в Drupal CMS. Когда я вставляю точно такие же HTML и JS в простой. html файл, кнопка отправки тогда фактически работает. Так что я совершенно в тупике.

Это документация, за которой я следовал:

https://pinpayments.com/developers/integration-guides/hosted-fields

Код:

HTML

<form action="/payment.php" id="payment_form" method="post"><label for="name">Full name</label>
<div id="name"><!-- Hosted Fields will populate this with the 'name' field --></div>

<div class="error_message" id="errors_for_name">&nbsp;</div>
<label for="number">Card number</label>

<div id="number"><!-- Hosted Fields will populate this with the 'number' field --></div>

<div class="error_message" id="errors_for_number">&nbsp;</div>
<label for="cvc">CVC</label>

<div id="cvc"><!-- Hosted Fields will populate this with the 'cvc' field --></div>

<div class="error_message" id="errors_for_cvc">&nbsp;</div>
<label for="expiry">Expiry</label>

<div id="expiry"><!-- Hosted Fields will populate this with the 'expiry' field --></div>

<div class="error_message" id="errors_for_expiry">&nbsp;</div>

<div class="pin-form-field" id="publishable_api_key"><input id="thisField" type="hidden" /></div>
&nbsp;

<div class="pin-form-field" id="address_line1"><input id="thisField" type="text" /></div>
&nbsp;

<div class="pin-form-field" id="address_line2"><input id="thisField" type="text" /></div>
&nbsp;

<div class="pin-form-field" id="address_city"><input id="thisField" type="text" /></div>
&nbsp;

<div class="pin-form-field" id="address_postcode"><input id="thisField" type="text" /></div>
&nbsp;

<div class="pin-form-field" id="address_state"><input id="thisField" type="text" /></div>
&nbsp;

<div class="pin-form-field" id="address_country"><input id="thisField" type="text" /></div>
<br />
<input type="submit" />&nbsp;</form>

Сценарий

<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
    <script src="https://cdn.pinpayments.com/pin.hosted_fields.v1.js"></script>
    <script type="text/javascript">
  $(function() {
    fields = HostedFields.create({
      /* Set this to true when testing. Set it to false in production. */
      sandbox: true,

      /*
        These are the CSS styles for the input elements inside the iframes. Inside each iframe
        is a single input with its id set to name, number, cvc or expiry.

        When the input has a valid value, it will have the 'hosted-fields-valid' class. When
        the input has an invalid value, it will have the 'hosted-fields-invalid' class.
      */
      styles: {
        'input': {
          'font-size': '16px',
          'font-family': 'helvetica, tahoma, calibri, sans-serif',
          'color': '#3a3a3a', 'border':'1px solid #000', 'height':'2em;'
        },

        '.hosted-fields-invalid:not(:focus)': {
          'color': 'red'
        }
      },

      /*
        The fields object defines the fields to be created. All four fields are required
        (name, number, cvc, expiry).

        Each field requires a selector for the element in which to create an iframe. Optionally,
        you can define placeholder text and a label selector (the CSS selector of the label
        element for that particular field).
      */
      fields: {
        name: {
          selector: '#name',
          placeholder: 'Roland Robot'
        },
        number: {
          selector: '#number',
          placeholder: '4111 1111 1111 1111'
        },
        cvc: {
          selector: '#cvc',
          placeholder: '123'
        },
        expiry: {
          selector: '#expiry',
          placeholder: '12/34'
        }

      }
    });
  });

  $(function () {
    /* The submit event for the form. */

    $('#payment_form').on('submit', function(e){
      /*
        If there's no card_token element in the form, then tokenisation hasn't happened yet.
        Ensure the default action is prevented and call a function to tokenise the field.
      */
      if( $('#card_token').length == 0 ) {
        e.preventDefault();
        tokenizeHostedFields();
      }
    });
  });

  /*
    Tokenises the hosted fields. Appends a hidden field for card_token on success, adds
    error messages otherwise.
  */

  function tokenizeHostedFields(){

    /*
      Tokenise the card. This requires address details not included in the hosted fields
      which can be pulled from elsewhere (such as other form elements).
    */
    fields.tokenize(
      {
        publishable_api_key: 'pk_wkHM76EknXUavjrEYZlvNQ',
        address_line1: 'Unit 42',
        address_line2: '123 Example St',
        address_city: 'Perth',
        address_postcode: '6000',
        address_state: 'WA',
        address_country: 'Australia'
      },
      function(err, response){
        if(err) {
          /*
            Example error:

            {
              error: "invalid_resource",
              error_description: "One or more parameters were missing or invalid",
              messages: [
                {
                  code: "number_invalid",
                  message: "A valid card number is required",
                  param: "number"
                }
              ]
            }
          */

          handleErrors(err);
          return;
        }

        /*
          Example successful response:

          {
            address_city: "Perth",
            address_country: "Australia",
            address_line1: "Unit 42",
            address_line2: "123 Example St",
            address_postcode: "6000",
            address_state: "WA",
            customer_token: null,
            display_number: "XXXX-XXXX-XXXX-0000",
            expiry_month: 12,
            expiry_year: 2034,
            name: "Roland Robot",
            primary: null,
            scheme: "visa",
            token: "card_Evv6AG9AzI2Gg0n3FrmQdw"
          }

        */

        /* Append a hidden element to the form with the card_token. */

        $('<input>').attr({
          type: 'hidden',
          id: 'card_token',
          name: 'card_token',
          value: response.token
        }).appendTo('#payment_form');

        /* Resubmit the form with the added card_token input. */
        $('#payment_form').submit();
      }
    );
  }

  /* Handles rendering of the error messages to the form. */

  function handleErrors(err){
    /* Clear any existing error messages. */

    $('.error_message').text('');

    /* Add each error message to their respective divs. */

    err.messages.forEach(function(errMsg){
      $('#errors_for_' + errMsg.param).text(errMsg.message);
    });
  }
</script>

оплата. php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://test-api.pinpayments.com/1/charges');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "amount=400&currency=AUD&description=test charge&email=roland@pinpayments.com&ip_address=203.192.1.172&card[number]=5520000000000000&card[expiry_month]=05&card[expiry_year]=2021&card[cvc]=123&card[name]=Roland Robot&card[address_line1]=42 Sevenoaks St&card[address_line2]=&card[address_city]=Lathlain&card[address_postcode]=6454&card[address_state]=WA&card[address_country]=Australia&metadata[OrderNumber]=123456&metadata[CustomerName]=Roland Robot");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'REMOVED THE SECRET KEY!!!' . ':' . '');

$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...