以Angular 6形式初始化Square iframe的问题

时间:2018-11-20 21:57:37

标签: angular typescript square

我在将Square iframe加载到表单时遇到问题。当我从导航栏导航到付款表单时,iframe不会加载到我的输入字段中。加载它们的唯一方法是点击刷新我的付款表格。这是我的付款:

import { Component, OnInit, Input, EventEmitter, AfterViewInit } from '@angular/core';
import {AppService} from '../app.service';

declare var SqPaymentForm: any;

@Component({
  selector: 'app-payment',
  templateUrl: './payment.component.html',
  styleUrls: ['./payment.component.css']
})
export class PaymentComponent implements OnInit, AfterViewInit  {

  constructor(private appService: AppService) { }
  paymentForm: any ;
  ngOnInit() {
   this.squarePaymentFunction();
  }
  ngAfterViewInit(): void  {}

  squarePaymentFunction() {
    let vm;
    vm = this;
    // this.calculatePayment();
    const applicationId = '********';

    // Set the location ID
    const locationId = '*********';
    this.paymentForm = new SqPaymentForm({

      // Initialize the payment form elements
      applicationId: applicationId,
      locationId: locationId,
      inputClass: 'sq-input',

      // Customize the CSS for SqPaymentForm iframe elements
      inputStyles: [{
        fontSize: '.9em'
      }],

      // Initialize the credit card placeholders
      cardNumber: {
        elementId: 'sq-card-number',
        placeholder: '•••• •••• •••• ••••'
      },
      cvv: {
        elementId: 'sq-cvv',
        placeholder: 'CVV'
      },
      expirationDate: {
        elementId: 'sq-expiration-date',
        placeholder: 'MM/YY'
      },
      postalCode: {
        elementId: 'sq-postal-code'
      },
      // SqPaymentForm callback functions
      callbacks: {

        /*
         * callback function: methodsSupported
         * Triggered when: the page is loaded.
         */
        methodsSupported: function (methods) {
        },

        /*
         * callback function: createPaymentRequest
         * Triggered when: a digital wallet payment button is clicked.
         */
        createPaymentRequest: function () {

          let paymentRequestJson;
          return paymentRequestJson;

        },

        /*
         * callback function: cardNonceResponseReceived
         * Triggered when: SqPaymentForm completes a card nonce request
         */
        cardNonceResponseReceived: function (errors, nonce, cardData)  {
          if (errors) {
            // Log errors from nonce generation to the Javascript console
            console.log('Encountered errors:');
            errors.forEach(function(error) {
              console.log('  ' + error.message);
            });

            return;
          }

          alert('Nonce received: ' + nonce); /* FOR TESTING ONLY */

          // Assign the nonce value to the hidden form field
          // document.getElementById('card-nonce').value = nonce;
          // needs to be extracted from the
          (<HTMLInputElement>document.getElementById('card-nonce')).value = nonce; // casting so .value will work

          let amount = (<HTMLInputElement>document.getElementById('amountToPay')).value;

          // POST the nonce form to the payment processing page
          // (<HTMLFormElement>document.getElementById('nonce-form')).submit();
          vm.sendSqPayment({'nonce': nonce, 'amountToPay': amount});
        },

        /*
         * callback function: unsupportedBrowserDetected
         * Triggered when: the page loads and an unsupported browser is detected
         */
        unsupportedBrowserDetected: function() {
          alert('Your browser seems to be unsupported for card processing. Please try a different browser.');
        },

        /*
         * callback function: inputEventReceived
         * Triggered when: visitors interact with SqPaymentForm iframe elements.
         */
        inputEventReceived: function(inputEvent) {
          switch (inputEvent.eventType) {
            case 'focusClassAdded':
              /* HANDLE AS DESIRED */
              break;
            case 'focusClassRemoved':
              /* HANDLE AS DESIRED */
              break;
            case 'errorClassAdded':
              document.getElementById('error').innerHTML = 'Please fix card information errors before continuing.';
              /* HANDLE AS DESIRED */
              break;
            case 'errorClassRemoved':
              document.getElementById('error').style.display = 'none';
              /* HANDLE AS DESIRED */
              break;
            case 'cardBrandChanged':
              /* HANDLE AS DESIRED */
              break;
            case 'postalCodeChanged':
              /* HANDLE AS DESIRED */
              break;
          }
        },

        /*
         * callback function: paymentFormLoaded
         * Triggered when: SqPaymentForm is fully loaded
         */
        paymentFormLoaded: function() {
          /* HANDLE AS DESIRED */
          console.log('The form loaded!');
        }
      }
    });
  }

  requestCardNonce(event) {


    // Request a nonce from the SqPaymentForm object
    this.paymentForm.requestCardNonce();
  }
  sendSqPayment(data) {
    this.appService.sendPayment(data).subscribe((data) => {
        if (data.success) {
          console.log('Data success');
        }
        // console.log('data', data);
      },
    );
  }
}

我使用Routes和RouterModlue在app.routing.ts中设置了路由

1 个答案:

答案 0 :(得分:0)

首先将autobuild设置为false

squarePaymentFunction() {
    let vm;
    vm = this;

    this.paymentForm = new SqPaymentForm({

      // Initialize the payment form elements
      applicationId: applicationId,
      locationId: locationId,
      inputClass: 'sq-input',
      autoBuild : false,
)};

然后我创建了一个局部变量并将其设置为false

formLoaded: boolean =  false;

接下来,我创建了一个函数来检查是否构建了表单并将其添加到ngOnInit():

loadPaymentForm() {
    if (this.formLoaded === false) {
      this.paymentForm.build();
      this.formLoaded = true;
    }
}

最后一步是将其添加到输入字段中

<input id="property_name" formControlName="property_name"  (focus)="loadPaymentForm()" (input)="checkInputError()" type="text" class="form-control" name="property_name" required/>

这不是最好的方法,但是它正在起作用。