Query
I am facing an issue while trying to integrate PayPal with Angular. I am encountering difficulties when attempting to call an injected service inside a function of the promise returned. Any assistance in resolving this would be greatly appreciated.
Here are the steps I am following:
- Click on the load PayPal button.
- Load the dynamically injected Braintree and PayPal sdk.
- Authorize into PayPal and get the nonce token.
- Pass the generated nonce token to the injected service within the component.
Code snippet below
app.component.html
<button (click)="initializePayPal()">load paypal</button>
<div id="pay-pal-btn"></div>
app.component.ts
export class AppComponent {
constructor(private backEndService: BackEndService) {}
initializePayPal() {
get("https://js.braintreegateway.com/web/3.71.1/js/client.min.js", () => {
get(
"https://js.braintreegateway.com/web/3.71.1/js/paypal-checkout.min.js",
() => {
console.log("loaded");
this.loadPayPalSDK();
}
);
});
}
private loadPayPalSDK(): void {
braintree.client
.create({
authorization: "sandbox_5rnr7xqg_kx8tzdyvfcrnxq5y"
})
.then(clientInstance => {
// Create a PayPal Checkout component.
return braintree.paypalCheckout.create({
client: clientInstance
});
})
.then(paypalCheckoutInstance => {
return paypalCheckoutInstance.loadPayPalSDK({
vault: true
});
})
.then(paypalCheckoutInstance => {
return paypal
.Buttons({
locale: "en_US",
fundingSource: paypal.FUNDING.PAYPAL,
style: {
height: 40
},
createBillingAgreement() {
return paypalCheckoutInstance.createPayment({
flow: "vault"
});
},
onApprove(data, actions) {
return paypalCheckoutInstance
.tokenizePayment(data)
.then(payload => {
console.log(payload.nonce);
this.backEndService.addToken(payload);
});
},
onCancel(data) {},
onError(err) {
//
}
})
.render("#pay-pal-btn");
});
}
}
Back End Service backend.service.ts
import { Injectable } from "@angular/core";
@Injectable({ providedIn: "root" })
export class BackEndService {
addToken(token: string) {
// here is am going to use the token generated and pass this value to backend service using http request.
console.log("token" + token);
}
}
Expected Solution
I need help implementing a solution where the injected service is called upon invoking the tokenizePayment method.
Thank you in advance for your help.