Why paymentID is null after PayPal transaction? - reactjs

I'm using PayPal in sandbox mode and #paypal/react-paypal-js in my React application and I'm using .NET 5 as my REST API.
Here is my payload when I want to create an order:
{
"totalAmount": 102,
"tax": 0,
"fee": 2,
"paymentMethod": 1,
"items": [
{
"amount": 100,
"reciver": "vala",
"phone": "0912351231",
"email": "vala#gmail.com",
"sender": "ali",
"count": 1
}
]
}
And here is part of my react code that call PayPal API:
<BoxPayment isRtl={isRtl}>
<Text as="h3">{translations.buyPage.paymentMethodTitle}</Text>
<Text as="p">{translations.buyPage.paymentMethodSubTitle}</Text>
<div style={{ 'paddingTop': '.5rem' }}>
<PayPalScriptProvider options={initialOptions}>
<PayPalButtons createOrder={(data, actions) => createOrder(data, actions)}
onApprove={(data, actions: any) => {
console.log('data', data);
console.log('actions', actions);
return actions.order.capture().then((details: any) => {
console.log('details', details);
const name = details.payer.name.given_name;
});
}} />
</PayPalScriptProvider>
</div>
</BoxPayment>
But after successful payment here's what I receive when I console.log data object:
{
"orderID": "48G91901G2470590C",
"payerID": "NBPJH63GK5H5Q",
"paymentID": null,
"billingToken": null,
"facilitatorAccessToken": "A11VAJ-tUcUqKkJgAhnyfVGVYg6Z57SvqHfspQqB8vtUDjDzBMIBlvO6rDvwdIjW7aJwvQQYeMAGyWitChtVZ8LyBzCw"
}
What I am missing?

Within onApprove, the order hasn't been captured when you are printing that data. Capture the order first. When an order is captured, its transaction ID will be in the response's purchase_units[0].payments.captures[0]
If you need to do anything important with that ID, such as store it in a database, used a server-side integration (not actions.order.capture nor actions.order.create, client-side code is not for database operations). See the optional step #5 in the 'Add and modify the code' section of the guide for Integrate Checkout, and be sure to use the client-side error handling code in its linked demo pattern example.

Related

Can't complete a PUT request from a different Modal using fetch with React

I am trying to create a CRUD app using springboot and React.
I have a problem with the PUT request to update a record from MySQL database.
With postman, when I send A PUT request like this:
{
"id": 456,
"name": "CHANGED_NAME",
"surname": "SURNAME",
"gender": "M",
"birthdate": "1995-12-07",
"work_address": "address1",
"home_address": "address2"
},
to http://localhost:8080/users/456
it works fine.
I have the info in a ListUsers.jsx file and I am trying to make the update from another jsx, e.x. UpdateUser.jsx sending as default values the current values when calling the UpdateUser Component.
Inside the UpdateUser.jsx I have a Form and onSubmit I call the handleSumbit method to make the PUT request, but nothing happens.
handleSubmit(event){
event.preventDefault();
fetch('http://localhost:8080/users/'+event.target.userId.value,{
method:'PUT',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
id: event.target.userId.value,
name: event.target.name.value,
surname: event.target.surname.value,
gender: event.target.gender.value,
birthdate: event.target.birthdate.value,
work_address: event.target.work_address.value,
home_address: event.target.home_address.value,
})
})
.then(res=> res.json())
.then((result)=>
{
//alert(result);
this.setState({user_added:true});
},
(error)=>{
//alert('Failed')
this.setState({user_added:true});
}
);
event.target.reset();
}

How to mutate specific object in an array using SWR

I have the following array
[
{
"idChatPublic": 17,
"idChatRoom": 2,
"idSender": "6c25110d-4256-42e1-8205-b75ece274487",
"username": "Hudson Thadeu Teixeira",
"message": "hello",
"avatar": null,
"createdAt": "12:43",
"chatLike": []
},
{
"idChatPublic": 33,
"idChatRoom": 2,
"idSender": "6c25110d-4256-42e1-8205-b75ece274487",
"username": "Hudson Thadeu Teixeira",
"message": "jam",
"avatar": null,
"createdAt": "13:07",
"chatLike": [
{
"idChatLike": 1,
"idChatPublic": 33,
"idUser": "",
"createdAt": "2022-02-14T08:59:34.000Z"
}
]
}
]
How can mutate an specific object of this array and add an object
to the "chatLike" array using SWR?
I have the following function:
async function sendLike() {
const newLike = {
idUser: myUser.userId,
}
mutate(
async (data) => {
console.log(data[messageIndex]) // This log returns specific object in the array
// Handle mutation
},
false
)
socket.emit('send_like', newLike)
}
Please guys I've been trying this for a while would be great If someone gives me a hand :D
You're using SWR with a websocket, which is an anti-pattern. SWR is meant for managing data that's fetched via REST or GraphQL requests, and it can be configured to refetch data on a regular interval. It's not a real time connection. Websocket on the other hand is real time. Consider if SWR is really best for your project - you probably don't need it.
Anyway, I also noticed some issues with how your mutate() is written so here's some feedback.
you must pass an ID into first argument
if you pass a function into mutate's second argument, it must return the new data
an easy way to update a specific item in an array is by using .map() and spread ... syntax
function sendLike() {
const newLike = {
idUser: myUser.userId,
}
// send request to update the source
// this is usually an REST request such as 'POST, UPDATE' etc
socket.emit('send_like', newLike)
// mutate local data
mutate(
'/api/chat', // ID must match ID used in the useSWR hook,
data => data.map(chat => chat.idChatPublic === idChat : {
...chat,
chatLike: [
...chat.chatLike
newLike
]
} : chat),
false
);
}

React-Admin: How do I best use nested "source" props

I am attempting to get react-admin to run on top of the WordPress REST API.
Posts title response is:
{
"title": {
"rendered": "Test"
}
}
And while using react-admin components to edit post title:
<TextInput source="title.rendered" label="Title" validate={required()} />
The challenge happens when submitting the Edit Form:
// the request body becomes this...
{
"title": { "rendered": "Test edited" }
}
// But I need to pass it as follows to work with the REST API...
{
"title": "Test edited"
}
I appreciate any help on solving this problem.
My solution for that issue was trying to Extend WordPress REST API with custom rest fields
Adding a new field name title to modify the existing one.
function ra_get_title_unnest( $post, $field_name, $request ) {
return get_the_title( (int) $post['id'] );
}
function ra_add_title_unnest_to_api() {
register_rest_field( 'post',
'title',
['get_callback' => 'ra_get_title_unnest']
);
}
add_action( 'rest_api_init', 'ra_add_title_unnest_to_api' );
then the response body becomes :
// without a nested form and in a consistent way
{
"title": "Test edited"
}

Splitting the string url in reactjs

I am trying to call the backend api which results in the details of the specific product based on id for example the api is http://localhost:54729/api/product/1 the 1 in the api is the id of the specific product. I am using redux and axios to get the data from the api.
EDIT:
The response from the api from which I am getting is the following
[
{
"id": 0,
"title": "TestProductAzure",
"description": "<p>While working with the EF Core Code-First approach, we create the classes for our domain entities first. Later, we’ll create the database from our code by using migrations. This is the opposite of the Database-First approach where we design our database first and then create the classes which match our database design.In the EF Core Code-First approach, we have full control over the code and the database is just a store without any logic. This approach is helpful in situations where we are starting with the development of a new project and we don’t have a clear picture of how our database should look like yet.We don’t have to worry about creating and updating the database. We can just make the changes in our code and then sync everything easily with the database. The important thing to note is that the manual changes that we make to the database could be lost during migration. So we should make changes to the code only.</p>",
"owner": "Seeded Company",
"link": null,
"url": "http://localhost:54729/api/product/1",
"type": "Internal",
"rank": 5
},
{
"id": 0,
"title": "Support | example.com",
"description": null,
"owner": null,
"link": "/search/product?url=https://www.example.com/support/",
"url": "https://www.exampl.com/support/",
"type": "External",
"rank": 3
},
{
"id": 0,
"title": "TestProductForAzure",
"description": null,
"owner": "Seeded Company",
"link": null,
"url": "http://localhost:54729/api/product/3",
"type": "Internal",
"rank": 0
},
The above response is the response when someone search something with the keyword. Now what I want if the user clicks on the url that has the api like http://localhost:54729/api/product/ I want to check the last number of the api i.e. the id and get the response from that forexample, if the user clicks on http://localhost:54729/api/product/2 . I want to pass the id 2 to the function which will then get pass from action and axios.get give the response.
My Action look like this
export function detailsProduct(id) {
const token = userService.getToken();
console.log(token);
const api = `/product/${id}`;
axios
.get(apiBaseUrl + api, { headers: { Authorization: `Bearer ${token}` } })
.then(res => {
console.log("helloProductDetails", apiBaseUrl + api);
try {
store.dispatch({
type: PRODUCT_DETAILS,
payload: res
});
} catch (err) {
console.log("error", err);
}
});
My Reducer look like this:
case PRODUCT_DETAILS:
console.log(
"action",
action,
"actionPayload",
action.payload,
"state",
state
);
return {
...state,
products: action.payload,
loading: false,
totalRecords: action.payload.length
};
and my .jsx react look like this
function onClickHandler() {
console.log("calling Details Product, HardCodedly");
detailsProduct(1);
}
return (
<div className="row">
<div className="s130">
{/* <div class="col-lg-8 col-xs-8 col-sm-12 col-md-7"> */}
<div className="col-lg">
<div className="container">
{result.type === "Internal" ? (
<Link to={DoctorProductLocation.path} onClick={onClickHandler}>
<h3>{result.title}</h3>
</Link>
) : (
//Try With OnClick Function
<a href={result.url} target="_blank">
<h3>{result.title}</h3>
</a>
)});
As you did notice , I'm sending the id hardcoded for now just to check if I am getting the information, which is working fine. But All I want to do is that when I click on the response it will automatically check the id and send us the response of that.
I thought of splitting the url until the id and pass it to the function action. But I don't know How? Or else if you have any other good idea, I will be thankful to you.

Make Axios Limit the Number of Responses

I am attempting to make an axios GET call to an API to retrieve some JSON data. The data is stored in an array with multiple objects each containing the same keys. There are hundreds of objects in this array but I only want to return the first ten. I am aware I can truncate the data set once it is returned but I am wondering if there is a way to limit the amount of responses to my API call.
Here is an example of the data set:
[
{
"userId": 1,
"id": 1,
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"userId": 1,
"id": 2,
"title": "1984",
"author": "George Orwell"
},
{
"userId": 1,
"id": 3,
"title": "The Count of Monte Cristo",
"author": "Alexandre Dumas"
},
]
and my axios request is simple as well:
router.get('/', (req, res) => {
axios.get(`https://jsonwebsit.info.com/posts`)
.then( response => {
res.send(response.data)
})
.catch(err => {
console.log('Error getting all data from API', err)
})
});
Actually, you can limit the number of responses from a certain API endpoint.
Just add params as an object as a second parameter while making the request.
For example:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/todos',{
params: {
_limit: 10
}
})
.then((res) => {
this.setState({
todos: res.data
});
})
}
Here you are limiting the response to 10 from jsonplaceholder API.
You could also call https://jsonplaceholder.typicode.com/todos/?_limit=10 and would get the same result.
Hope it helps.
On your side there's nothing you can do until pagination is implemented on API side. Depending on the way it's implemented, you will probably make requests to API sending params like offset, page, limit- these are the most common params' names saying how many elements should API return. But if that's 3rd party provider and their docs are not saying anything about such possibility, you're most likely won't be able to do what you want

Resources