• Resolved albyse

    (@albyse)


    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>
    • This topic was modified 1 month, 1 week ago by albyse.
Viewing 1 replies (of 1 total)
  • Plugin Support Reynier C. (woo-hc)

    (@reynierc)

    Hi @albyse ,

    It sounds like it’s a bit of a challenge with the PayPal checkout on Android. Since this involves code that looks custom-made, our support mainly covers the WooCommerce core and official extensions.

    If it’s a custom integration, the best route would be to reach out to a developer who can dive deep into the specifics of the React Native environment and its interaction with the WooCommerce REST API. Based on the feedback we get from our customers we highly recommend contacting one of the services on our Customization page.

    Meanwhile, ensuring that your WordPress and WooCommerce versions are up to date, as well as the PayPal plugin, can sometimes solve a few unexpected issues.

    Hope this helps.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.