I am attempting to integrate worldpay with out React web app.
Incorporating the credit card functionality via Worldpay.useTemplateForm() is working fine but the next step is causing a problem.
To use 3DS we have to redirect away from our site to a bank controlled site and supply them with a URL to be redirected back to afterwards.
This is annoying in itself because we have a lot of saved state in our app and on returning all of this would be lost, however its not the biggest issue.
After the 3DS they POST the form data back to us and React cannot accept post requests and the webpage simply displays 'CANNOT POST /'
Has anyone successfully implemented Worldpay 3DS into a React app??
You can send request with cart data dirrectly to payment system:
const formData = {
reusable: true,
paymentMethod: {
name: 'name',
expiryMonth: 10,
expiryYear: 2021,
issueNumber: 1,
startMonth: 2,
startYear: 2013,
cardNumber: '5454 5454 5454 5454',
type: 'Card',
cvc: '123'
},
clientKey: 'your key'
}
fetch('https://api.worldpay.com/v1/tokens', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(formData)
})
.then(data => {
if (data.ok) {
data.json().then(result => {
// if data is valid you will get token
console.log('result', result) // <-
})
}
})
.catch(err => console.log('err', err))
If cart data is correct you will get 'token' inside 'result' variable. Then you should send this token to your backend, then backend should make request with this token as mentioned in official documentation - 3D secure backend integration
Other steps described in this link.
Related
I come to you in a time of great need. I've spent like a week on this and still can't figure it out. Please help.
Here is what I want to do:
I've got a WordPress website (http://test/test.wp/) on which you can do the following API call right in the browser when you are logged in:
$.ajax({
url: 'http://test/test.wp/wp-json/wp/v2/users/me',
method: 'GET',
beforeSend: function(xhr){
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
}).done(function(response){
console.log(response);
}).fail(function(response){
console.log( response.responseJSON.message );
});
And it works just fine. You get a Json about the current user (I just need the ID)
Now, I got another website (subdomain) written in React (http://app.test) and I am trying to pretty much do the same GET request to WordPress to grab the ID of the currently logged in User.
The sites are interconnected and I am sort of trying to imitate a SSO between WordPress and React by simply grabbing the ID of the currently logged in user in WordPress and using it in the react subdomain
To achieve this I've taken care of the CORS so I can make GET request from React to WordPress with no problems.
I also shared my WordPress wordpress_logged_in_cffb670352ad40cd796ad890d27ee701 cookie with the React subdomain so I've got access to that (which, from what I understand is the only cookie needed to keep you authenticated)
So, with all of that said why is my request from React failing?
Axios({
method: 'get',
url: 'http://test/test.wp/wp-json/wp/v2/users/me',
headers: {
'X-WP-Nonce': '659cbfeec0', // <= It's needed to use the WP Api and it's correct. I mannually grabed it from WP with wpApiSettings.nonce
withCredentials: true, // <= From what I understand is the only thing needed to send the `wordpress_logged_in_cffb670352ad40cd796ad890d27ee701` cookie ???
},
})
.then(response => console.log(response))
.catch(err => console.log(err));
So why then the answer that I get is a 403 (Forbidden)?:
code: "rest_cookie_invalid_nonce"
data: {status: 403}
statusText: 'Forbidden'
message: "Cookie verification failed"
You can say that the answer is in the response that I get, but I really have no idea why that's the case.
Please help.
Desperate Coder.
I was passing the 'with-Credentials' in the Headers and was not sending the cookies in the request because of that.
The correct way of doing it is:
Axios.get(
'http://test/test.wp/wp-json/wp/v2/users/me',
{
withCredentials: true,
headers: { 'X-WP-NONCE': 'Your_Nonce' },
}
)
I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests. An API token is necessary, in order to access data via the Jira API. I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.
This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:
curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool
This is the React state hook for setting the data to the fetched data:
const [jiraTicket, setJiraTicket] = useState([]);
This is the fetch function for the API request (${} will be filled with user input):
function getJiraTicket() {
axios.get(`${username}:${apiToken}#Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
.then((res) => {
const data = res.data;
setJiraTicket(data);
})
}
The button inside the react component return should invoke the fetch function:
return(
<Container>
<Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
</Container>
);
This is the error I'm currently getting, because the authorization is not working the way I did it
(I replaced the provided username, API token etc. for this example):
GET http://localhost:3000/username:apitoken#https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found)
Edit:
My current approach:
function getJiraTicket() {
axios.get(`${userName}:${apiToken}#https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
auth: {
username: userName,
password: apiToken,
},
withCredentials: true
})
.then((res) => {
const data = res.data;
console.log(data);
setJiraTicket(data);
})
.catch(err => {
// This error means: The request was made and the server responded with a status code
if(err.res) {
console.log(err.res.data);
console.log(err.res.status);
console.log(err.res.headers);
console.log("request was made and server responded with status");
// The request was made but no response was received
} else if (err.request) {
console.log(err.request);
console.log("request was made, but no response was received");
// Something happened in setting up the request that triggered an error
} else {
console.log("Error", err.message);
console.log("request is note set up correctly");
}
console.log(err.config);
})
Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"
Endpoint that works well in Postman (Basic auth is provided in Postman):
https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid
Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly. This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication. However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:
https://auth.atlassian.com/authorize? audience=api.atlassian.com&
client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent
Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues
Axios uses a headers config for get/post so you should not include them in your URL. Here is a general example of how you should construct the URL and apply headers:
let axiosUrl = `https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
baseURL: axiosUrl,
method: 'get',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin", "*"
},
//timeout: 2000,
auth: {
username: userName,
password: apiToken,
}
})
.then((res) => {
setJiraTicket(res.data);
})
.catch(function (error) {
console.log(error);
});
I am trying to get some of the examples located in the with-ireon-sessions github account to work with my own back-end: https://github.com/vercel/next.js/tree/canary/examples/with-iron-session
I can sign in using const { user, mutateUser } = useUser(); with useUser() being from the example: https://github.com/vercel/next.js/blob/canary/examples/with-iron-session/lib/useUser.js
My sign-in method looks like this;
const signIn = async ({ email, password, remember_me }) => {
try {
await mutateUser(
fetchJson(`${API.baseURL}/${API.signIn}`, {
method: "POST",
headers: {
"Accept": 'application/json',
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password
})
})
);
} catch (error) {
console.error("An unexpected error happened:", error);
setErrorMessage((<p className="error">{error.data.message}</p>));
}
};
I can see my user change, but I still have the following issues:
I don't see any cookies get created. Does with-iron-sessions require the site to be deployed to the vercel cloud in order for cookies to get added, or am I right in thinking I can use my own server and API endpoints?
What's the pattern for using the /api/user endpoint in useUser.js; does the endpoint look for the cookies (that are not getting created for me) and do it's own validation, or is there validation I need to do in my version of that endpoint? Is there an example of what that endpoint looks like server-side you might be able to point me to?
Is there a way to refresh the cookie (once I get them to appear) so they are X days since last using the site instead of X days from first login so it's a sliding cookie lifespan, or does that happen automatically?
When I sign out my sign_out endpoint returns a 204 status code but the UI doesn't change like it does when I sign in. Any tips for me there?
Thank you!
So far I've been able to configure a method in C# that is able to hardcode a new repository in Azure DevOps, but my real goal is to create a user interface that allows the user to specify the request body which consists of the following:
name: 'nameOfRepository',
project: {
id: 'projectId'
}
The user will fill out the first input field with the desired name of the new repository. The second input field should use a GET Request that displays all available projects in your organization in a dropdown list.
I'm also using .NET Core 3.0 and believe this probably has to be done with an API controller as well, but I am not certain.
I have little to no experience with React and have no idea how and where I'm going to specify the request body and personal access token to create the repository. I would appreciate an explanation of how this works and would also appreciate a solution that could guide me in the right direction.
Azure DevOps Rest API Documentation will give you access to the platform. If you are decided to develop totally in React js. I would like to suggest to take a starter kit, mostly will cover all your basic setup to React.
Follow the below steps to get an idea of how you can achieve with react js
Need to set up OAuth in azure deops. The below link will give an idea. In the callback page, you need to store access token store
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops. If you have personal auth token this is not required
Get all list of repositories using fetch or Axios API
Example with Axios:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'bearer token' or 'basic personalaccesstoken'
}
axios.get('https://dev.azure.com/{organization}/{project}/_apis/git/repositories', {
headers: headers,
params: {
'api-version':'5.1'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Use react form to capture the input value and on submit of form, validate against the repositories, if it is new call the Axios or fetch post method to create a new repository
Example with Axios
const headers = {
'Content-Type': 'application/json',
'Authorization': 'bearer token'
}
const data = {
name: ''
parentRepository: {id: '', ....}
project: {id: '', ...}
}
axios.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories', JSON.stringify(data),
{
headers: headers,
params: {
'api-version':'5.1'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Similarly, you can access all the API's mentioned REST API documentation of Microsoft. link
I am trying to create a stripe payment app using reactJS and expressJS, I am getting this error:
Proxy error: Could not proxy request /payment from localhost:3000 to https://localhost:5000/
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (EPROTO)
In package.json file I have set proxy as -
"proxy": "https://localhost:5000"
In my react component I have -
const onToken = token => {
axios({
url: "payment",
method: "post",
data: {
amount: priceForStripe,
token: token
}
})
.then(response => {
alert("succesful payment");
})
.catch(error => {
console.log("Payment Error: ", error);
alert(
"There was an issue with your payment! Please make sure you use the provided credit card."
);
});
};
In my server.js I have -
const stripe = require("stripe")("sk_test_...");
app.post("/payment", (req, res) => {
const body = {
source: req.body.token.id,
amount: req.body.amount,
currency: "usd"
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
} else {
res.status(200).send({ success: stripeRes });
}
});
});
whenever I submit any payment I hit error -
I tried all method linked here but can't solve that issue. I heartily thank if anyone explain any solution of that problem.
Since your backend works fine without stripe, the 500 error indicates that stripe is the problem.
This is related to the information you are sending in the body of the stripe charges.create request. I think you are missing the customer.id.
This post arjunphp.com/node-stripe-express-js shows the charges.create request as
{ amount,
description: "Sample Charge",
currency: "usd",
customer: customer.id
}
As #CherryDT mentioned, first I set proxy to "proxy": "http://localhost:5000". Then I change my backend code as #Greg M suggested -
app.post("/payment", (req, res) => {
stripe.customers
.create({
email: req.body.email, // customer email, which user need to enter while making payment
source: req.body.token.id // token for the given card
})
.then(customer =>
stripe.charges.create({
// charge the customer
amount: req.body.amount,
description: "Sample Charge",
currency: "usd",
customer: customer.id
})
)
.then(charge => res.status(200).send({ success: "success" }));
});
That's it. My payment method works perfectly.
I think the proxy error is a red herring. The real issue is the parsing on your server, causing the 500.
It looks like by default Axios encodes the json for you (but you should double check the request). To access JSON encoded request body data in Express, you need to use the body-parser middleware.
See this answer for an example: How do I consume the JSON POST data in an Express application
I'm taking the exact react course from Andre. My solution was to start the backend server.
So whoever gets into this issue from the same course either try the answer above or:
npm start
or
yarn start