简体   繁体   English

How to combine PayPal Smart Payment Button with REST API SDK for PHP V2?

[英]How to combine PayPal Smart Payment Button with REST API SDK for PHP V2?

My problems start after I have included the default code ( https://developer.paypal.com/demo/checkout/#/pattern/server ) and changed it as follows:在我包含默认代码( https://developer.paypal.com/demo/checkout/#/pattern/server )并将其更改如下之后,我的问题就开始了:

<?php

session_start();
require_once '../inc/config.inc.php';

echo '
<!DOCTYPE html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>

<body>

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

<script src="https://www.paypal.com/sdk/js?client-id=' . PAYPAL_CLIENT_ID . '&currency=EUR&disable-funding=credit,card"></script>
';
?>

<script>
    // Render the PayPal button into #paypal-button-container
    paypal.Buttons({
        // Call your server to set up the transaction
        createOrder: function(data, actions) {
            return fetch('01_payPalCheckout.php', {
                mode: "no-cors",
                method: 'post',
                headers: {
                    'content-type': 'application/json'
                }
            }).then(function(res) {
                return res.json();
            }).then(function(orderData) {
                return orderData.id;
            });
        },

        // Call your server to finalize the transaction
        onApprove: function(data, actions) {
            return fetch('01_checkout.php?orderId=' + data.orderID, {
                method: 'post'
            }).then(function(res) {
                return res.json();
            }).then(function(orderData) {
                var errorDetail = Array.isArray(orderData.details) && orderData.details[0];

                if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                    // Recoverable state, see: "Handle Funding Failures"
                    // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
                    return actions.restart();
                }

                if (errorDetail) {
                    var msg = 'Sorry, your transaction could not be processed.';
                    if (errorDetail.description) msg += '\n\n' + errorDetail.description;
                    if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
                    // Show a failure message
                    return alert(msg);
                }

                // Show a success message to the buyer
                alert('Transaction completed by ' + orderData.payer.name.given_name);
            });
        }


    }).render('#paypal-button-container');
</script>

<?php

echo '
</body>
</html>
';

?>

In createOrder I call 01_payPalCheckout.php, which is structured as specified in the PHP SDK:在 createOrder 中,我调用了 01_payPalCheckout.php,其结构如 PHP SDK 中指定的那样:

<?php

use PayPalCheckoutSdk\Orders\OrdersCreateRequest;

session_start();
require_once '../inc/config.inc.php';

# 1: Environment, Client
$environment = new SandboxEnvironment(PAYPAL_CLIENT_ID, PAYPAL_SECRET);
$client = new PayPalHttpClient($environment);


# 2: Request Order
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = [
    "intent" => "CAPTURE",
    "purchase_units" => [[
        "reference_id" => "test_ref_id1",
        "amount" => [
            "value" => "100.00",
            "currency_code" => "USD"
        ]
    ]],
    "application_context" => [
        "cancel_url" => "https://example.com/cancel",
        "return_url" => "https://example.com/return"
    ]
];

try {

    // Call API with your client and get a response for your call
    $response = $client->execute($request);

    // JSON-Encodierung
    $response = json_encode($response);

    // If call returns body in response, you can get the deserialized version from the result attribute of the response
    return $response;

} catch (HttpException $ex) {

    echo $ex->statusCode;
    print_r($ex->getMessage());
    exit();

}

I added json_encode() before returning $response;我在返回 $response; 之前添加了 json_encode() the resulting JSON-code is the following code:生成的 JSON 代码是以下代码:

{
    "statusCode": 201,
    "result": {
        "id": "4H218056YS3363904",
        "intent": "CAPTURE",
        "status": "CREATED",
        "purchase_units": [
            {
                "reference_id": "test_ref_id1",
                "amount": {
                    "currency_code": "USD",
                    "value": "100.00"
                },
                "payee": {
                    "email_address": "info-facilitator@24960324320.de",
                    "merchant_id": "BYWLB3T6SPG54"
                }
            }
        ],
        "create_time": "2020-08-10T08:33:40Z",
        "links": [
            {
                "href": "https:\/\/api.sandbox.paypal.com\/v2\/checkout\/orders\/4H218056YS3363904",
                "rel": "self",
                "method": "GET"
            },
            {
                "href": "https:\/\/www.sandbox.paypal.com\/checkoutnow?token=4H218056YS3363904",
                "rel": "approve",
                "method": "GET"
            },
            {
                "href": "https:\/\/api.sandbox.paypal.com\/v2\/checkout\/orders\/4H218056YS3363904",
                "rel": "update",
                "method": "PATCH"
            },
            {
                "href": "https:\/\/api.sandbox.paypal.com\/v2\/checkout\/orders\/4H218056YS3363904\/capture",
                "rel": "capture",
                "method": "POST"
            }
        ]
    },
    "headers": {
        "": "",
        "Cache-Control": "max-age=0, no-cache, no-store, must-revalidate",
        "Content-Length": "747",
        "Content-Type": "application\/json",
        "Date": "Mon, 10 Aug 2020 08",
        "Paypal-Debug-Id": "1b04a05438898"
    }
}

In onApprove I call "'01_payPalCapture.php?orderId=' + data.orderID" (here I also used the provided standard methods of https://github.com/paypal/Checkout-PHP-SDK :在 onApprove 中,我调用“'01_payPalCapture.php?orderId=' + data.orderID”(这里我还使用了https://github.com/paypal/Checkout-PHP-SDK提供的标准方法:

<?php

// Session starten
session_start();

use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;

// Konfigurations-Datei einbinden
require_once '../inc/config.inc.php';


# 1: Environment, Client
$environment = new SandboxEnvironment(PAYPAL_CLIENT_ID, PAYPAL_SECRET);
$client = new PayPalHttpClient($environment);


# 2 Capture
$request = new OrdersCaptureRequest($_GET['orderId']);
$request->prefer('return=representation');

try {
    $response = $client->execute($request);
    $response = array('id' => $response->result->id);
    $response = json_encode($response);
    return $response;  // value of return: {"id":"2KY036458M157715J"}
}catch (HttpException $ex) {
    echo $ex->statusCode;
    print_r($ex->getMessage());
}

In 01_cart.php the Smart Buttons are rendered as desired, but a click on "PayPal" only results in error messages, eg update_client_config_error etc.在 01_cart.php 中,智能按钮会根据需要呈现,但单击“PayPal”只会导致错误消息,例如 update_client_config_error 等。

I think there is a problem understanding how the two scripts work together from my side.我认为从我这边理解这两个脚本如何协同工作存在问题。

Thanks in advance for hints and help (I've been working on this problem continuously for 4 days now, I've struggled through all the PayPal help and didn't find anything about this particular problem on the internet).提前感谢您的提示和帮助(我已经连续 4 天一直在解决这个问题,我一直在努力通过所有 PayPal 帮助,但在互联网上没有找到任何关于这个特定问题的信息)。

/httpdocs/01_payPalCheckout.php is a bad path /httpdocs/01_payPalCheckout.php是错误的路径

it needs to be one that can load in your web browser它必须是可以在您的 web 浏览器中加载的

Something that would work in an HTML href, like <a href="/01payPalCheckout.php"></a> for example可以在 HTML href 中使用的东西,例如<a href="/01payPalCheckout.php"></a>

Test loading 01payPalCheckout.php in your browser, make sure it is executing and returning the correct JSON, and then fix your client-side code to point to the correct path that will return that JSON when fetched在浏览器中测试加载 01payPalCheckout.php,确保它正在执行并返回正确的 JSON,然后修复客户端代码以指向正确的路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM