我使用PayPal API,我希望将结果数据保存在我的数据库中

发布于 2025-02-07 18:47:02 字数 7864 浏览 2 评论 0原文

我的问题是,我尝试保存付款时贝宝回报的JSON数据,并将其保存在MySQL数据库中,但插入未完成。

这是按钮的代码,

<div class="prenda">
            <span>
                Tallas
            </span>
            <form class="comprarprenda" action="RegistrarCompra.php" method="post">
                <input class="elegirtalla" type="radio" name="talla" id="XS" value="XS" required>
                <input class="elegirtalla" type="radio" name="talla" id="S" value="S">
                <input class="elegirtalla" type="radio" name="talla" id="M" value="M">
                <input class="elegirtalla" type="radio" name="talla" id="L" value="L">
                <input class="elegirtalla" type="radio" name="talla" id="XL" value="XL">
                <p>
                    <button class="comprar" type="submit" value="comprar" name="botons">
                        Comprar
                    </button>

                    <div id="paypal-button-container"></div>

                    <script>

                        try {
                            var costo = 0;
                            const reqS = new XMLHttpRequest();
    
                            document.addEventListener('DOMContentLoaded', 
                            function Comentarios()
                            {
                                reqS.onload = function ShowComents(){
                                var co =  reqS.responseText;
                                costo = co;
                                alert(costo);
                            }
                                reqS.open("GET", "phpapi.php?");
                                reqS.send();
    
                            }, false);
                            
                        } catch (error) {
                            console.log(error);
                        }

                        try {
                            document.addEventListener('DOMContentLoaded',
    
    
                            paypal.Buttons({
                                style:{
                                    layout: 'horizontal',
                                    color:  'silver',
                                    shape:  'pill',
                                    tagline: 'false',
                                    label:  'paypal'
                                },
                                createOrder: function(data, actions)
                                {
                                    return actions.order.create({
                                        purchase_units: [{
                                            amount: {
                                                value: costo
                                            }
                                        }]
                                    });
                                },
                                onApprove: function(data, actions)
                                {
                                        let url = 'GetDatosCompra.php'
                                    actions.order.capture().then(function(detalles)
                                    {
                                        console.log(detalles);
                                        alert("Pago realizado");
                                        //window.location.href="";
                                        return fetch(url,
                                        {
                                            method: 'post',
                                            headers: 
                                            {
                                                'content-type': 'application/json'
                                            },
                                            body: JSON.stringify(
                                                {
                                                        detalles: detalles
                                                }
                                            )
                                        });
                                    });
                                },

                                onCancel: function(data)
                                {
                                    alert("Pago cancelado");
                                    console.log(data);
                                },
                                onError: function (err) 
                                {
                                    alert("Ha sucedido un error, intente de nuevo");
                                }
                            }).render('#paypal-button-container'), false);
                            
                        } catch (error) {
                            console.log(error);
                        }
                    </script>

                    <button class="alcarrito" type="submit" value="carrito" name="botons">
                        <abbr title="Añadir al carrito de compras">
                            <img src="https://res.cloudinary.com/cadivie/image/upload/v1653571538/carritodecompras_pzica7.png">

                        </abbr>
                    </button>
                    <button class="guardarenlista" type="submit" value="listadeseos" name="botons">
                        <abbr title="Añadir a lista de deseos">
                            <img src="https://res.cloudinary.com/cadivie/image/upload/v1653571538/bookmark_ayho2g.png">

                        </abbr>
            </button>
                </p>            

            </form>
            
        </div>

这是我放置回声的查询的代码

<?php

session_start();
include "database.php";
$id_us = $_SESSION["id_us"];
$id_producto = $_SESSION['id_p'];



$json = file_get_contents('php://input');
$datos = json_decode($json, true);

if(is_array($datos))
{
    $id_transaccion = $datos['detalles']['id'];
    $precio = $datos['detalles']['purchase_units'][0]['amount']['value'];
    $estado = $datos['detalles']['status'];
    $fecha = $datos['detalles']['update_time'];
    $fecha_db = date('Y-m-d H:i:s', strtotime($fecha));
    $email = $datos['detalles']['payer']['email_address'];
    $id_cliente = $datos['detalles']['payer']['payer_id'];

    
    echo "<script> alert('$id_us') </script>"; 
    echo "<script> alert('$id_producto') </script>"; 
    echo "<script> alert('$id_transaccion') </script>"; 
    echo "<script> alert('$estado') </script>"; 
    echo "<script> alert('$email') </script>"; 
    echo "<script> alert('$id_cliente') </script>"; 
    echo "<script> alert('$precio') </script>"; 
    echo "<script> alert('$fecha_db') </script>"; 
    echo $id_us; 
    echo $id_producto;
    echo $id_transaccion;
    echo $estado;
    echo $email;
    echo $id_cliente;
    echo $precio;
    echo $fecha_db;

    $ingreso = "INSERT INTO comprado (id_usuario, id_producto, id_transaccion, estado, email, id_cliente, precio, fecha_historial) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    $sql->execute([$id_us, $id_producto, $id_transaccion, $estado, $email, $id_cliente, $precio, $fecha_db]);
    
    $id_historial = $con->lastInsertId();
}


?>

,以便我可以看到变量的值,但是

此代码什么都没发生,我从数据库中获取产品ID

 <?PHP

session_start();

include "database.php";
$id = $_SESSION['id_p'];

    $query = "SELECT * from productos WHERE id_producto = '$id'";     // Esta linea hace la consulta
    $result = mysqli_query($conexion, $query); 

    while ($registro = mysqli_fetch_array($result)){ 
        echo $registro['precio'];
}

?>

,这是我的数据库

My problem is that I try to save the JSON data that PayPal returns when making the payment and save it in a MySQL database but the insert is not done.

Here's the code of the button

<div class="prenda">
            <span>
                Tallas
            </span>
            <form class="comprarprenda" action="RegistrarCompra.php" method="post">
                <input class="elegirtalla" type="radio" name="talla" id="XS" value="XS" required>
                <input class="elegirtalla" type="radio" name="talla" id="S" value="S">
                <input class="elegirtalla" type="radio" name="talla" id="M" value="M">
                <input class="elegirtalla" type="radio" name="talla" id="L" value="L">
                <input class="elegirtalla" type="radio" name="talla" id="XL" value="XL">
                <p>
                    <button class="comprar" type="submit" value="comprar" name="botons">
                        Comprar
                    </button>

                    <div id="paypal-button-container"></div>

                    <script>

                        try {
                            var costo = 0;
                            const reqS = new XMLHttpRequest();
    
                            document.addEventListener('DOMContentLoaded', 
                            function Comentarios()
                            {
                                reqS.onload = function ShowComents(){
                                var co =  reqS.responseText;
                                costo = co;
                                alert(costo);
                            }
                                reqS.open("GET", "phpapi.php?");
                                reqS.send();
    
                            }, false);
                            
                        } catch (error) {
                            console.log(error);
                        }

                        try {
                            document.addEventListener('DOMContentLoaded',
    
    
                            paypal.Buttons({
                                style:{
                                    layout: 'horizontal',
                                    color:  'silver',
                                    shape:  'pill',
                                    tagline: 'false',
                                    label:  'paypal'
                                },
                                createOrder: function(data, actions)
                                {
                                    return actions.order.create({
                                        purchase_units: [{
                                            amount: {
                                                value: costo
                                            }
                                        }]
                                    });
                                },
                                onApprove: function(data, actions)
                                {
                                        let url = 'GetDatosCompra.php'
                                    actions.order.capture().then(function(detalles)
                                    {
                                        console.log(detalles);
                                        alert("Pago realizado");
                                        //window.location.href="";
                                        return fetch(url,
                                        {
                                            method: 'post',
                                            headers: 
                                            {
                                                'content-type': 'application/json'
                                            },
                                            body: JSON.stringify(
                                                {
                                                        detalles: detalles
                                                }
                                            )
                                        });
                                    });
                                },

                                onCancel: function(data)
                                {
                                    alert("Pago cancelado");
                                    console.log(data);
                                },
                                onError: function (err) 
                                {
                                    alert("Ha sucedido un error, intente de nuevo");
                                }
                            }).render('#paypal-button-container'), false);
                            
                        } catch (error) {
                            console.log(error);
                        }
                    </script>

                    <button class="alcarrito" type="submit" value="carrito" name="botons">
                        <abbr title="Añadir al carrito de compras">
                            <img src="https://res.cloudinary.com/cadivie/image/upload/v1653571538/carritodecompras_pzica7.png">

                        </abbr>
                    </button>
                    <button class="guardarenlista" type="submit" value="listadeseos" name="botons">
                        <abbr title="Añadir a lista de deseos">
                            <img src="https://res.cloudinary.com/cadivie/image/upload/v1653571538/bookmark_ayho2g.png">

                        </abbr>
            </button>
                </p>            

            </form>
            
        </div>

here's the code for the query

<?php

session_start();
include "database.php";
$id_us = $_SESSION["id_us"];
$id_producto = $_SESSION['id_p'];



$json = file_get_contents('php://input');
$datos = json_decode($json, true);

if(is_array($datos))
{
    $id_transaccion = $datos['detalles']['id'];
    $precio = $datos['detalles']['purchase_units'][0]['amount']['value'];
    $estado = $datos['detalles']['status'];
    $fecha = $datos['detalles']['update_time'];
    $fecha_db = date('Y-m-d H:i:s', strtotime($fecha));
    $email = $datos['detalles']['payer']['email_address'];
    $id_cliente = $datos['detalles']['payer']['payer_id'];

    
    echo "<script> alert('$id_us') </script>"; 
    echo "<script> alert('$id_producto') </script>"; 
    echo "<script> alert('$id_transaccion') </script>"; 
    echo "<script> alert('$estado') </script>"; 
    echo "<script> alert('$email') </script>"; 
    echo "<script> alert('$id_cliente') </script>"; 
    echo "<script> alert('$precio') </script>"; 
    echo "<script> alert('$fecha_db') </script>"; 
    echo $id_us; 
    echo $id_producto;
    echo $id_transaccion;
    echo $estado;
    echo $email;
    echo $id_cliente;
    echo $precio;
    echo $fecha_db;

    $ingreso = "INSERT INTO comprado (id_usuario, id_producto, id_transaccion, estado, email, id_cliente, precio, fecha_historial) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

    $sql->execute([$id_us, $id_producto, $id_transaccion, $estado, $email, $id_cliente, $precio, $fecha_db]);
    
    $id_historial = $con->lastInsertId();
}


?>

I put echo so I can see the value of the variables but nothing happens

with this code I get the id of the product from the database

 <?PHP

session_start();

include "database.php";
$id = $_SESSION['id_p'];

    $query = "SELECT * from productos WHERE id_producto = '$id'";     // Esta linea hace la consulta
    $result = mysqli_query($conexion, $query); 

    while ($registro = mysqli_fetch_array($result)){ 
        echo $registro['precio'];
}

?>

And this is my database

database fields

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮年慕年 2025-02-14 18:47:02

action.order.capture()

do * do * d dise使用client-side js sdk 如果要将结果写入数据库,则创建并捕获功能。那不是强大的集成模式。这些功能仅适用于非常简单的用例。

相反,请按照 paypal结帐集成 )在您的服务器上,一个用于“创建订单”,另一个用于“捕获顺序”。您可以将Checkout-PHP-SDK用于路由为PayPal的API呼叫,或者您自己的HTTPS实现,首先获得访问令牌然后进行呼叫。这两种路线都应仅返回JSON数据(无HTML或文本)。在第二路线内,当捕获API成功时,您应该验证金额正确,然后可以将其产生的付款详细信息存储在您的数据库中(尤其是paskuy_units [0] .payments.payments.captures.captures [0] .id,这是PayPal事务ID),并在将返回json转发给前端呼叫者之前,请立即执行任何必要的业务逻辑(例如发送确认电子邮件或保留产品)。如果错误向前转发JSON的详细信息,因为前端必须处理此类情况。

将这两条路线与此前端批准流配对: https:https:https:///developer.paypaler.paypal。 com/demo/beckout/#/tatter/server 。 (如果您需要将客户端从客户端发送任何其他数据发送到服务器,例如项目数组或选定的选项,请添加一个body参数,并以JSON字符串或对象的值将其添加到获取的值)

actions.order.capture()

Do *not* use client-side JS SDK create and capture functions if you are going to write the result to a database. That is not a robust integration pattern. These functions are only for very simple use cases.

Instead, follow the PayPal Checkout integration guide and make 2 routes (url paths) on your server, one for 'Create Order' and one for 'Capture Order'. You can use Checkout-PHP-SDK for your routes' API calls to PayPal, or your own HTTPS implementation of first getting an access token and then doing the call. Both of these routes should return only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should verify the amount was correct and can then store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as sending confirmation emails or reserving product) immediately before forwarding your return JSON to the frontend caller. In the event of an error forward the JSON details of it as well, since the frontend must handle such cases.

Pair those 2 routes with this frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server . (If you need to send any additional data from the client to the server, such as an items array or selected options, add a body parameter to the fetch with a value that is a JSON string or object)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文