Cannot do payment with paypal
-
Hi team, I implemented a react-native app with WordPress as backend. I installed this plugin for paypal checkout in app. But, it is not processing paymant in Android. But, it is working in web version of react native. Can you check the code for payment and order placement?
Below is the code.
//payment gateway integration code...............
import { WOOCOMMERCE_URL, CONSUMER_KEY, CONSUMER_SECRET } from './woocommerceConfig';
useEffect(() => {
const checkCart = async () => {
const cart = await AsyncStorage.getItem('cart');
if (!cart || JSON.parse(cart).length === 0) {
setCartEmpty(true);
} else {
calculateTotalAmount(); // Calculate total amount when cart is not empty
}
};
checkCart();
}, []);
const calculateTotalAmount = async () => {
const cart = await AsyncStorage.getItem('cart');
if (cart) {
const cartItems = JSON.parse(cart);
const total = cartItems.reduce((total, item) => {
return total + (item.price * item.quantity);
}, 0).toFixed(2);
setTotalAmount(total); // Set calculated total amount
}
};
useEffect(() => {
const getClientToken = async () => {
try {
const response = await axios.get(${WOOCOMMERCE_URL}/wp-json/braintree/v1/get-braintree-client-token
);
setClientToken(response.data.clientToken);
} catch (error) {
console.error('Error fetching client token:', error);
Alert.alert('Error', 'Could not connect to the payment gateway.');
}
};
// getClientToken();
}, []);
const createPayPalPayment = async () => {
const PAYPAL_CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const PAYPAL_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const dataDetail = {
intent: 'sale',
payer: {
payment_method: 'paypal',
},
transactions: [
{
amount: {
total: totalAmount, // Use calculated order total
currency: 'USD',
},
},
],
redirect_urls: {
return_url: 'https://mysite.com',
cancel_url: 'https://mysite.com',
},
};
try {
const tokenResponse = await fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:Basic ${btoa(
${PAYPAL_CLIENT_ID}:${PAYPAL_SECRET})}
,
},
body: 'grant_type=client_credentials',
});
const tokenData = await tokenResponse.json();
if (!tokenData.access_token) {
throw new Error('Failed to obtain access token');
}
setAccessToken(tokenData.access_token);
const paymentResponse = await fetch('https://api.sandbox.paypal.com/v1/payments/payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization:Bearer ${tokenData.access_token}
,
},
body: JSON.stringify(dataDetail),
});
if (!paymentResponse.ok) {
throw new Error('Payment creation failed: ' + paymentResponse.statusText);
}
const paymentData = await paymentResponse.json();
const approvalUrl = paymentData.links.find(link => link.rel === 'approval_url');
if (!approvalUrl) {
throw new Error('Approval URL not found');
}else {
Alert.alert('Approval URL found');
}
Alert.alert(paymentData.id);
setPaymentId(paymentData.id);
setApprovalUrl(approvalUrl.href);
} catch (error) {
console.error('Error:', error);
Alert.alert('Error', error.message);
}
};
const onNavigationStateChange = async (webViewState) => {
if (webViewState.url.includes('https://mysite.com')) {
const urlParams = new URLSearchParams(webViewState.url);
setApprovalUrl(null);
const PayerID = urlParams.get('PayerID');
try {
const executeResponse = await fetch(https://api.sandbox.paypal.com/v1/payments/payment/${paymentId}/execute
, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization:Bearer ${accessToken}
,
},
body: JSON.stringify({ payer_id: PayerID }),
});
if (!executeResponse.ok) {
const errorData = await executeResponse.json();
Alert.alert('Payment execution failed: ', errorData.message || 'Unknown error');
return;
}
else{
Alert.alert('Payment execution success: ');
}
const executeData = await executeResponse.json();
// Alert.alert(executeData);
if (executeData.state !== 'approved') {
Alert.alert('Payment failed');
return;
}else{
Alert.alert('Payment was approved ');
}
// Now, create the order in WooCommerce
await placeOrder(executeData);
} catch (error) {
console.error('Error during payment execution:', error);
Alert.alert('Error', 'An error occurred during the payment process. Please try again.');
}
}
};
const placeOrder = async (paymentData) => {
setLoading(true);
try {
const cart = await AsyncStorage.getItem('cart');
if (!cart) {
Alert.alert('Error', 'Your cart is empty.');
setLoading(false);
return;
}
const cartItems = JSON.parse(cart);
const lineItems = cartItems.map(item => ({
product_id: item.productId,
quantity: item.quantity,
}));
const billingInfo = {
first_name: name,
email: email,
phone: phone,
address_1: address,
city: city,
postcode: postalCode,
country: country,
state: state,
};
const formData = {
payment_method: 'paypal',
billing: billingInfo,
line_items: lineItems,
};
const authHeader =Basic ${Buffer.from(
${CONSUMER_KEY}:${CONSUMER_SECRET}).toString('base64')}
;
const response = await axios.post(
${WOOCOMMERCE_URL}/wp-json/wc/v3/orders
,
formData,
{
headers: {
Authorization: authHeader,
'Content-Type': 'application/json',
},
}
);
if (response.status === 201) {
Alert.alert('Order Placed', 'Your order has been placed successfully!');
await AsyncStorage.removeItem('cart');
navigation.navigate('OrderReceivedScreen', { order: response.data });
} else {
Alert.alert('Error', 'Failed to place order. Please try again.');
}
} catch (error) {
console.error('Order placement error:', error.response ? error.response.data : error.message);
Alert.alert('Error', 'An error occurred while placing your order.');
} finally {
setLoading(false);
}
};
const handlePlaceOrder = () => {
if (!name || !email || !phone || !address || !city || !postalCode || !country || !state) {
Alert.alert('Error', 'Please fill in all fields.');
return;
}
if (paymentMethod === 'paypal') {
createPayPalPayment();
}
};
//PLACE ORDER BUTTON
<TouchableOpacity style={styles.placeOrderButton} onPress={handlePlaceOrder}>
<Text style={styles.placeOrderButtonText}>Place Order</Text>
</TouchableOpacity>
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- You must be logged in to reply to this topic.