【问题标题】:How to integrate PayPal express checkout into angular2 typescript project如何将 PayPal 快速结账集成到 angular2 typescript 项目中
【发布时间】:2017-10-04 00:26:23
【问题描述】:

Paypal 提供了easy way to integrate its express checkout solution,但在使用 typescript 编写的 angular2 项目中使用此解决方案的最佳解决方案是什么?

【问题讨论】:

  • 所有 JavaScript 都是 TypeScript,所以从那里开始。 Angular 2 集成可能会受益于创建可注入服务来包装全局。

标签: angular typescript paypal


【解决方案1】:

我使用过这样的解决方案:

加载外部脚本的方法

  private loadExternalScript(scriptUrl: string) {
    return new Promise((resolve, reject) => {
      const scriptElement = document.createElement('script')
      scriptElement.src = scriptUrl
      scriptElement.onload = resolve
      document.body.appendChild(scriptElement)
  })

组件代码

  ngAfterViewInit(): void {
    this.loadExternalScript("https://www.paypalobjects.com/api/checkout.js").then(() => {
      paypal.Button.render({
        env: 'sandbox',
        client: {
          production: '',
          sandbox: ''
        },
        commit: true,
        payment: function (data, actions) {
          return actions.payment.create({
            payment: {
              transactions: [
                {
                  amount: { total: '1.00', currency: 'USD' }
                }
              ]
            }
          })
        },
        onAuthorize: function(data, actions) {
          return actions.payment.execute().then(function(payment) {
            // TODO
          })
        }
      }, '#paypal-button');
    });
  }

信用

Andrei Odri 的回答在这里:script tag in angular2 template / hook when template dom is loaded

【讨论】:

  • 如何更改(动态设置)amount.total 的值?执行 onAuthorize 的回调时,如何调用控制器中的函数?
  • 我在 ngOninit 上加载了脚本,但通过手动调用函数来渲染按钮。将金额和货币传递给函数并分配给它们的变量,如下所示:{ total: cost, currency: selectedCurreny }
  • 是否需要通过loadExternalScript()函数添加“paypalobjects.com/api/checkout.js”?或者我们可以在网站的索引页面中添加这个js。我也在做同样的事情,但是当我在更新购物车上创建贝宝按钮时,我收到一个错误“页面上已加载具有相同版本 (4.0.235) 的 PayPal 结帐集成脚本”。请建议我更好的方法来处理这个@Remotec
  • 如何将PayPal导入项目? paypal.Button.render({ 来自哪里?
【解决方案2】:

您可以像这样使用 Angular 4 实现贝宝结帐:

import { Component, OnInit } from '@angular/core';

declare let paypal: any;

@Component({
    selector: 'app-page-offers',
    templateUrl: './page-offers.component.html',
    styleUrls: ['./page-offers.component.sass']
})

export class PageOffersComponent implements OnInit {

    constructor() {}

    ngOnInit() {
        $.getScript( 'https://www.paypalobjects.com/api/checkout.js', function() {
            paypal.Button.render({
             [...]
            })
    [...]

享受:)

【讨论】:

    【解决方案3】:

    通过使用 Remotec 的答案,我可以进行快速结帐。它虽然给出了一些违规警告。用户选择货币后,我已经在我的函数中呈现。我已经从角度模板传递了“这个”。我用过 Angular 6 和 Angular 材料 2

    <div class="container">
      <div *ngFor="let currency of currencies">
      </div>
    
      <div class="row">
        <form >
          <mat-form-field appearance="standard" class="col-sm-12 col-md-6">
            <mat-label>Cost</mat-label>
            <input matInput placeholder="Amount" [(ngModel)]="cost" required disabled="true" name="amount" id="amount">
          </mat-form-field>
    
          <mat-form-field appearance="standard" class="col-sm-12 col-md-6">
            <mat-select placeholder="Select Currency" [(ngModel)]="selectedCurrency" name="curr" id="curr" (selectionChange)="CurrencyChange(cost,selectedCurrency,this)" >
              <mat-option *ngFor="let c of currencies" [value]="c.value" >
                {{c.viewValue}}
              </mat-option>
            </mat-select>
    
          </mat-form-field>
        </form>
    
      </div>
      <div id="paypal-button" class="align-content-between align-content-center"></div>
    </div>
    

    在 CurrencyChange 函数中,我已经传递了这个,在 paypal 函数中,我再次调用了我的 angular 函数来完成付款。我不知道这是否是一个好习惯。但这行得通。

        export class PaymentComponent implements OnInit {
    
      cost = '1';
      currency = 'INR';
      selectedCurrency = "0";
      currencies: Currency[] = [
        {
          value: "0",
          viewValue: "Select Currency"
        },
        {
          "value": "INR",
          "viewValue": "Indian Ruppe"
        }, {
          "value": "USD",
          "viewValue": "US Dollar"
        },
        {
          "value": "EUR",
          "viewValue": "EURO"
        }]
    
      private loadExternalScript(scriptUrl: string) {
        return new Promise((resolve, reject) => {
          const scriptElement = document.createElement('script')
          scriptElement.src = scriptUrl
          scriptElement.onload = resolve
          document.body.appendChild(scriptElement)
        })
      }
    
      ngOnInit() {
        this.loadExternalScript("https://www.paypalobjects.com/api/checkout.js");
      }
    
    
      constructor() { }
    
      paymentSuccess(payment) {
        //alert('Payment Success');
      }
      CurrencyChange(cost, selectedCurreny,self): void {
    
        document.getElementById("paypal-button").innerHTML = "";
        if (selectedCurreny == 0) {
          alert('Please select the Country');
          return;
        }
        //reset earlier inserted paypal button
        paypal.Button.render({
          env: 'sandbox',
          client: {
            production: 'AQ9IbOayBJxHmad9DMGoysS4UhzE-usUqfSQ-CLzSn3M96qvZny5vZZ2VkNzn6EBTnE2UU4L8PDkqJJE',
            sandbox: 'AQ9IbOayBJxHmad9DMGoysS4UhzE-usUqfSQ-CLzSn3M96qvZny5vZZ2VkNzn6EBTnE2UU4L8PDkqJJE'
          },
          commit: true,
          payment: function (data, actions) {
            return actions.payment.create({
              payment: {
                transactions: [
                  {
                    amount: { total: cost, currency: selectedCurreny }
                  }
                ]
              }
            })
          },
          onAuthorize: function (data, actions) {
            return actions.payment.execute().then(function (payment) {
    
              alert('Payment Successful')
              self.paymentSuccess(payment);
                console.log(payment)
            })
          }
        }, '#paypal-button');
      }
    }
    

    【讨论】:

      【解决方案4】:

      我最近回答了类似的问题 (how to write the below code in angular 2 component using typescript),并编写了封装 paypal 按钮的简单组件。

      我已经扩展了我的示例,使其具有输入成本属性,因此您可以将成本传递给按钮的组件。如果需要,您可以轻松扩展它并传递更多数据。

      正如 Aluan Haddad 在评论中所说,您可以将 PayPal 全局包装在服务中。我编写了一个简单的服务,用一些类型定义包装了 Button 属性:

      export class PaypalService {
          constructor() {  }
      
          // You can bind do paypal's button with type definitions in the following way:
          public Button: {
              render: ({ payment, onAuthorize }: {
                  payment?: (data: any, actions: any) => void,
                  onAuthorize?: (data: any, actions: any) => void
              }, divId: string) => void
          } = (window as any).paypal.Button;
      }
      

      工作示例位于:https://plnkr.co/edit/9AlbWnZDzek9kDdigdED

      我不确定 PayPal 按钮的内部工作原理,但这应该可以让您抢先一步,希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2014-10-07
        • 2013-03-15
        • 2018-04-15
        • 2014-04-15
        • 2013-05-17
        • 1970-01-01
        • 2018-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多