如何在paypal angular 4

时间:2018-01-09 09:14:03

标签: angular paypal

在下面的代码中我得到Cannot read property 'http' of undefined未定义。 如何在onAuthorize函数中调用外部自定义函数。

这是我接受帮助的链接https://developer.paypal.com/demo/checkout/#/pattern/client 你的任何帮助都会很明显。

ngAfterViewInit(): void {
    const total = this.total_amount;
    const selected_package = this.selected_package.name;
    this.loadExternalScript('https://www.paypalobjects.com/api/checkout.js').then(() => {
        paypal.Button.render({
            env: 'sandbox',
            client: {
                production: '',
                sandbox: 'XXXXXXXXXXXXXXXXXXXXXXX'
            },
            commit: true,
            payment: function (data, actions) {
                return actions.payment.create({
                    payment: {
                        transactions: [
                            {
                                amount: { total: total, currency: 'USD' },
                                description: selected_package,
                            }
                        ]
                    }
                })
            },
            onAuthorize: function (data, actions) {
                return actions.payment.execute().then(function (payment) {
                    const formdata: FormData = new FormData;
                    formdata.append('Payment[trns_id]', payment.id);
                    formdata.append('Payment[paypal]', payment);
                    formdata.append('Payment[amount]', payment.transactions[0].amount);
                    formdata.append('Payment[order_id]', order_id);
                    formdata.append('Payment[state]', payment.state);
                    formdata.append('Payment[auth_token]', auth_token);
                    this.http.post(environment.apiUrl + 'orders/paypal-checkout', formdata).subscribe(
                        (result) => {
                            this.responceData = result.json();
                            if (this.responceData.data.status === true && this.responceData.data.status_message === 'success') {
                                this.router.navigateByUrl('/questionnaire/successfully');
                            }
                        },
                        (err) => {
                            console.log('Error' + err);
                        })
                })
            },
            onError: function (err) {
                console.log(err);
            }
        }, '#paypal-button');
    });
}

1 个答案:

答案 0 :(得分:4)

使用function关键字创建新范围并更改this的值。你需要使用 lambda函数不会改变this的值,如下所示:

您只需将function (data, actions)替换为(data, actions) =>function(payment) (payment) =>而不是其他任何内容

onAuthorize: (data, actions) => {
    return actions.payment.execute().then((payment) => {