Angular 6 PayPal VALIDATION_ERROR

Это мой ответ. Некоторые из вас могут легко понять.

package package02;

public class C11PostfixAndPrefix {

    public static void main(String[] args) {
        // In this program, we will use the value of x for understanding prefix 
        // and the value of y for understaning postfix. 
        // Let's see how it works. 

        int x = 5; 
        int y = 5; 

        Line 13:   System.out.println(++x);  // 6   This is prefixing. 1 is added before x is used. 
        Line 14:   System.out.println(y++);  // 5   This is postfixing. y is used first and 1 is added. 

        System.out.println("---------- just for differentiating");

        System.out.println(x);  // 6   In prefixing, the value is same as before {See line 13}
        System.out.println(y);  // 6   In postfixing, the value increases by 1  {See line 14} 

        // Conclusion: In prefixing (++x), the value of x gets increased first and the used 
        // in an operation. While, in postfixing (y++), the value is used first and changed by
        // adding the number. 
    }
}
0
задан kronus 15 January 2019 в 18:32
поделиться

2 ответа

Я не знаю, является ли это правильным способом сделать это, но я больше не получаю первоначальную ошибку.

Во-первых, я создал несколько скрытых полей для соответствующих элементов, которые я хотел опубликовать, наряду с присвоением каждому входу идентификатора - следующие скрытые поля:

    <input
      type="text"
      [(ngModel)]="model.total"
      style="padding-bottom: 10px;"
      name="total"
      id="total"
      #total="ngModel"
      value="{{ model.total | currency }}"
    />
    <input
      type="hidden"
      name="user_id"
      id="user_id"
      value="{{ this.user_id }}"
    />
    <input
      type="hidden"
      name="orders_id"
      id="orders_id"
      value="{{ this.orders_id }}"
    />
    <input
      type="hidden"
      name="product"
      id="product"
      value="{{ this.product }}"
    />
    <input
      type="hidden"
      name="subTotal"
      id="subTotal"
      value="{{ this.payPalSrvc.getSubTotal() }}"
    />

Во-вторых, я создал отдельный PayPalService, чтобы разделить функциональность, а также, я хотел, чтобы эти сообщения проходили через мой перехватчик, чтобы поместить jwt в заголовки:

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import { ShoppingCartService } from "./shopping-cart.service";
import { ProductService } from "./product.service";
import { LoginService } from "./login.service";

@Injectable({
  providedIn: "root"
})
export class PaypalService {
  constructor(
    private http: HttpClient,
    private loginSrvc: LoginService,
    private prdSrvc: ProductService,
    private cartSrvc: ShoppingCartService
  ) {}

  addScript = false;
  paypalLoad = true;
  finalAmount;
  subTotal;

  paypalConfig = {
    env: "sandbox",
    client: {
      sandbox:
        "<my-sandbox-id>",
      production: "<your-production-key here>"
    },
    commit: true,
    payment: function(data, actions) {
      return actions.payment.create({
        transactions: [
          {
            amount: {
              total: document.getElementById("total").value,
              currency: "USD",
              details: {
                subtotal: document.getElementById("subTotal").value,
                tax: (document.getElementById("total").value * 0.07).toFixed(2),
                shipping: (document.getElementById("total").value * 0.03).toFixed(2),
                handling_fee: "1.00",
                shipping_discount: "0.00",
                insurance: (document.getElementById("total").value * 0.01).toFixed(2)
              }
            },
            description: "The payment from for-her application.",
            /* custom: "90048630024435", */
            invoice_number: document.getElementById("orders_id").value, // Insert a unique invoice number
            payment_options: {
              allowed_payment_method: "INSTANT_FUNDING_SOURCE"
            },
            soft_descriptor: document.getElementById("user_id").value,
            item_list: {
              items: [document.getElementById("product").value],
              shipping_address: {
                recipient_name: (document.getElementById("firstName").value + " " + document.getElementById("lastName").value),
                line1: document.getElementById("address").value,
                line2: document.getElementById("address2").value,
                city: document.getElementById("city").value,
                country_code: document.getElementById("country").value,
                postal_code: document.getElementById("zip").value
                phone: document.getElementById("phone").value,
                state: document.getElementById("state").value,
                email: document.getElementById("email").value
              }
            }
          }
        ],
        note_to_payer: "Contact us for any questions on your order."
      });
    },
    onAuthorize: (data, actions) => {
      return actions.payment.execute().then(payment => {
        // Do something when payment is successful.
        // window.alert("Thank you for your purchase! You order will be processed and shipped as soon as possible");
        document.getElementById("myModal").style.display = "block";
        document.getElementById("ModalBackdrop").style.display = "block";
        this.cartSrvc.postCart();
      });
    }
  };

  addPaypalScript() {
    this.addScript = true;
    return new Promise((resolve, reject) => {
      const scripttagElement = document.createElement("script");
      scripttagElement.src = "https://www.paypalobjects.com/api/checkout.js";
      scripttagElement.onload = resolve;
      document.body.appendChild(scripttagElement);
    });
  }

  public getSubTotal() {
    this.subTotal = (document.getElementById("total").value) -
    ((document.getElementById("total").value * 0.07) +
    (document.getElementById("total").value * 0.03) +
    (document.getElementById("total").value * 0.01) +
    1.00);
    return this.subTotal.toFixed(2);
  }

  public getToken(): string {
    return localStorage.getItem("jwt");
  }
}

Конечно, теперь у меня есть другая ошибка искаженного запроса, который помещен внутри jsonlint и, как вы можете видеть, он вернулся как действительный:

From jsonlint.com

Но главное, чтобы параметры / свойства работали:

along with subtotal calculations working

Если кто-нибудь может сказать мне, о чем новая ошибка, то я бы будь благодарен.

Error: Request to post https://www.sandbox.paypal.com/v1/payments/payment failed with 400 error. Correlation id: f31569c675597, f31569c675597

{
    "name": "MALFORMED_REQUEST",
    "message": "Incoming JSON request does not map to API request",
    "information_link": "https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST",
    "debug_id": "f31569c675597"
}

request/</<@https://www.paypalobjects.com/api/checkout.js:14216:39

Еще раз спасибо @ paulsm4 за предложение заглянуть под вкладку «Сеть», чтобы увидеть, действительно ли значение было опубликовано.

0
ответ дан kronus 15 January 2019 в 18:32
поделиться

У меня точно такая же проблема. Транзакция работает, когда я передаю жестко закодированное значение, и я также использую Angular 6. У меня есть только ввод номера типа и кнопка Paypal. Я использую этот проект для использования Paypal https://github.com/Enngage/ngx-paypal Вот мой код:

component.html [114 ]

<ngx-paypal [config]="payPalConfig"></ngx-paypal>
<input type="number" class="form-control" placeholder="Enter amount" [(ngModel)]="amount"/>

component.ts

import { Component, OnInit, Input } from '@angular/core';
import { PayPalConfig, PayPalEnvironment, PayPalIntegrationType } from 'ngx-paypal';

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

  amount: number;
  public payPalConfig?: PayPalConfig;

  ngOnInit(): void {
    this.initConfig();
  }

  private initConfig(): void {
    this.payPalConfig = new PayPalConfig(PayPalIntegrationType.ClientSideREST, PayPalEnvironment.Sandbox, {
      commit: true,
      client: {
        sandbox: '...',
      },
      button: {
        label: 'paypal',
        layout: 'vertical'
      },
      onAuthorize: (data, actions) => {
        console.log('Authorize');
        return undefined;
      },
      onPaymentComplete: (data, actions) => {
        console.log('OnPaymentComplete');
        console.log(data);
      },
      onCancel: (data, actions) => {
        console.log('OnCancel');
      },
      onError: err => {
          if (typeof this.amount === 'number') {
          console.log('NUMBER !!!!!!!!!!');
        } else if (typeof this.amount === 'string') {
          console.log('STRING !!!!!!!!!!');
        }
        console.log('Amount : ' + this.amount);
        console.log('OnError : ' + err);
      },
      onClick: () => {
        console.log('onClick');
      },
      validate: (actions) => {
        console.log(actions);
      },
      experience: {
        noShipping: true,
        brandName: '...'
      },
      transactions: [{
        amount: {
          currency: 'EUR',
          total: this.amount
        }
      }]
    });
  }
}

Спасибо за любую помощь!

0
ответ дан Daniel 15 January 2019 в 18:32
поделиться
Другие вопросы по тегам:

Похожие вопросы: