Paypal javascript sdk onClick not prevent popup showing - paypal

I follow this documentation to integrate paypal javascript sdk. I want validate user input after paypal button click and prevent paypal window display if validation fail.
paypal.Buttons({
onClick: function(data, actions) {
console.log('click >>>>>')
return actions.reject();
// return false;
},
createOrder: function(data, actions) {
return fetch('/checkout/submit/paypal/create_order', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(_this.getSubmitData())
}).then(function(res) {
return res.json();
}).then(function(detial) {
return detial.orderId
});
},
onApprove: function(data, actions) {
// data > { billingToken, facilitatorAccessToken, orderID, payerID, paymentID }
return fetch('/checkout/submit/paypal/capture_order?orderId=' + data.orderID, {
method: 'post',
headers: {
'content-type': 'application/json'
},
}).then(function(res) {
return res.json();
}).then(function(details) {
console.log(details);
})
}
}).render('#paypal-button-container');
When i click the paypal button, console show my message click >>>>> and a new window display and disappear immeditely.
I don't think it should show a new window.

I don't think it should show a new window.
Nonetheless, that's how it works if you reject from onClick.
To prevent the popup from opening, you need to disable the buttons in onInit and add a listener for re-enabling them when appropriate, as documented in the link in your question.

Related

Paypal Order API capture payment in Angular and NestJS

My stack is NestJS and Angular12, I am using the OrderAPI v2.
I succesfully implemented the order flow using an SDK button, but, since I have several payment systems that are activated by a single button "Pay now", I need to avoid SDK in my front end. Follows the methods I use to create and capture payments, and they works with the SDK button.
async createOrder(value: number): Promise<any> {
const accessToken = await this.generateAccessToken();
const url = this.baseUrl+`/v2/checkout/orders`;
const body = {
intent: "CAPTURE",
return_url: process.env.CLIENT+"/success",
purchase_units: [
{
amount: {
currency_code: "EUR",
value: value.toFixed(2)
}
}
]
}
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`
}
const obs = this.httpService.post(url, JSON.stringify(body),{headers: headers});
const response = await firstValueFrom(obs);
return response.data;
}
async capturePayment(order: CreateOrderDto, orderId: string): Promise<any> {
const accessToken = await this.generateAccessToken();
const url = this.baseUrl+`/v2/checkout/orders/${orderId}/capture`;
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`
}
const obs = this.httpService.post(
url,
{},
{
headers: headers
}
)
const response = await firstValueFrom(obs);
if (response.data.success) await this.orderService.createOrder(order)
return response.data;
}
When calling the createOrder() function I return the url of the approvation, and in my Front-end I do the redirect to the approve page of Paypal. The problem is that when approving the transaction on the approve url the user is shown a infinite loading page.
Is there something I am missing?

Update a wordpress rest api using javascript fetch method

This is the index.php of my plugin where I am registering a custom POST endpoint.
function __construct()
{
add_action('rest_api_init', array($this, 'add_custom_api'));
}
function add_custom_api()
{
register_rest_route('wyr/v1', 'putAns', array(
'methods' => 'POST',
'callback' => array($this, 'putAns')
));
}
But, I want to insert the data inside this endpoint using a fetch post method from javascript.
function putAns($data)
{
return (); // INSERT SOMETHING FROM JAVASCRIPT
}
This is the javascript code that I'm failing with:
async clickHandler(e) {
const response = await fetch("http://localhost/plugdev/wp-json/wyr/v1/putAns", {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'A blog post by DAVID',
body: 'Brilliant post on fetch API',
userId: 1,
})
});
var data1 = await response.json();
console.log(data1)
}
There are a lot of other details missing but this is the general gist of the issue: Onclick of a button, I want to change the value of a a property inside this object. Then, I'll have to catch this request from php and insert it into the database.

Axios `PUT` 500 Error when trying to add contract to sendgrid

I am trying to take user emails and put them into sendgrid as a contract list. It seems like some information is being lost when trying to add new emails to the list but am unsure exactly what is causing the problem.
First I have a hero component that contains the area of email collection:
const Hero = () => {
const [mail, setMail] = useState(null);
const [loading, setLoading] = useState(false);
//Called onClick()
const subscribe = () => {
setLoading(true);
axios.put("api/sendgrid/mailingList", mail)
.then((result) => {
if (result.status === 200) {
toast.success(result.response.data);
setLoading(false);
}
})
.catch((error) => {
console.log(error.response.data);
setLoading(false);
});
};
The axios put from the previous section goes to my api/sendgrid/mailingList:
import axios from "axios";
export default async function handler(req, res) {
if (req.method === "PUT") {
await axios.put("https://api.sendgrid.com/v3/marketing/contacts", {
contacts: [{ email: req.body.mail }],
list_ids: [process.env.SENDGRID_MAILING_ID],
},
{
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.NEXT_PUBLIC_SENDGRID}`,
},
}
)
.then((res) => {
res.status(200).send({
message:
"Your email has been succesfully added to the mailing list. Welcome 👋",
});
})
.catch((error) => {
res.status(500).send({
message:
"There was a problem with your subscription, please try again or contact us",
});
});
}
}
I am able to access my API script but am met with the following error:
PUT http://localhost:3000/api/sendgrid/mailingList 500 (Internal
Server Error)
The network tab on the console tools:

wait for complete page load does not work as expected in Protractor

I am writing a test for login into non-angular application.
describe('login Test for App', function () {
beforeEach(function () {
browser.ignoreSynchronization=true;
browser.get(loginPageURL,2000);
});
it('It should Login a User', function () {
element(by.id('username')).sendKeys(constants.userName);
element(by.id('password')).sendKeys(constants.password);
element(by.id('Login')).click().then(function () {
// Waiting to open modal
browser.wait(function () {
return browser.getCurrentUrl().then(function (url) {
return url==dashboardUrl;
});
});
});
});
});
After login, I want to check currentUrl. But After login button click, It waits till dashboard url appeared.
But when after loginbutton click, It go to diffrent url, Then it also wait for dashboard url infinite.
I want to check current url after login event, if it is not dashboard url, then it should fail, and do not run next test suite cases, because login Test is failed.
Like-
When clickOn login button.
Wait for complete page load.
2.Then check current url, If it is not dashboard url, then test should failed, and not proceed for any test cases.
It is not best practice to wait for the pages url to load in order to know if the page is loaded, because there could be redirects or other things.
It is best practice to wait for a specific element on the next page(after log-in). Here is your code refactored to use a custom wait() function that will wait for an element to appear before continuing to retrieve the current url:
describe('login Test for App', function () {
browser.ignoreSynchronization = true;
it('should load the log-in page', function(done) {
browser.driver.get(loginPageURL).then(function() {
browser.driver.sleep(2000);
wait('#username', 10000);
done();
});
});
it('It should Login a User', function (done) {
element(by.id('username')).sendKeys(constants.userName);
element(by.id('password')).sendKeys(constants.password);
element(by.id('Login')).click().then(function () {
// Waiting to open modal
wait('#element_on_the_next_page', 10000);
browser.getCurrentUrl().then(function (url) {
// do anything with the url
done();
});
});
});
function wait(selector, timeout) {
browser.driver.wait(function() {
return browser.driver.isElementPresent(by.css(selector)).then(function(present) {
return present;
});
}, timeout);
browser.driver.wait(function() {
return browser.driver.findElement(by.css(selector)).isDisplayed().then(function(displayed) {
return displayed;
});
}, timeout).then(function() {
return;
});
}
});
Hope this helps!

how to track paypal transaction in google analytics

I want to track my conversions coming from Paypal checkout option.
I want to differentiate between conversions from normal checkout process & conversions from Paypal.
on the newest Paypal javascript API, this is how to log:
paypal.Button.render({
...
payment: function(data, actions) {
return new paypal.Promise(function (resolve, reject) {
// LOG BUTTON CLICKED
resolve();
}).then(function () {
return actions.payment.create({
..
});
});
},
onAuthorize: function(data, actions) {
return actions.payment.get().then(function(paymentDetails) {
...
return actions.payment.execute().then(function() {
// LOG FINISHED TRANSACTION
}})
},
// same for onerror, oncancel