从独立脚本传输可运行的 PHP cURL 脚本,并刷新 Wordpress 代码

问题描述 投票:0回答:1

我想得到一些输入来解决我的问题,我正在尝试解决将我的独立 php 函数和 js 脚本转换为工作 Wordpress 格式的问题。我必须将其转换为我的 Wordpress 页面的工作格式,并且需要一些输入。

我已经创建了一个脚本,用于在 php 中对 2 个不同端点进行链式 API 调用。

对端点 a) 的调用 1 正在向 API 发送 3 个静态主体参数(API 密钥、用户 ID、密码等)和 1 个动态值(用户 IP 地址)。作为响应,API POST 一个 orderREF 字符串和一个应该显示在屏幕上的 QR 代码的 url。除此之外,二维码每 5 秒刷新一次。

用户成功扫描 QR 码后,呼叫 2 至端点 b) 将返回客户姓名和社会安全号码以及与 ATM 不太相关的其他一些值。对于用户来说,身份验证过程已经完成,我想将获得的数据传输到我的客户数据库中。

正如您将在我的脚本中看到的那样,我在独立脚本中创建了此功能的工作原型,但需要帮助将其传输到工作 Wordpress(插件或短代码)中,以便我可以在页面的特定部分使用此功能。我希望用户在注册我们的网站之前完成此过程,以便充分验证用户的身份。

我成功创建的代码执行了 2 个链式 API 调用并通过 javascript 刷新了 QR 码。为了简单起见,我硬编码了用于测试的凭据,这些将存储在 .env 文件中

<?php
// Handle AJAX requests for the second API call
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['checkStatus'])) {
    $orderRef = $_POST['orderRef'];

    $apiUser = 'aaa';
    $password = ' xxx ';
    $companyApiGuid = 'yyy ';
    $url = 'https://url/endpoint/2';

    $requestData = array(
        'apiUser' => $apiUser,
        'password' => $password,
        'companyApiGuid' => $companyApiGuid,
        'orderRef' => $orderRef
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($requestData));
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;
    exit;
}

// Initial QR code generation if not a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $apiUser = 'aaa';
    $password = 'xxx';
    $companyApiGuid = 'yyy';
    $url = 'https://url/endpoint1';

    $data = array(
        'apiUser' => $apiUser,
        'password' => $password,
        'companyApiGuid' => $companyApiGuid,
        'endUserIp' => $_SERVER['REMOTE_ADDR'],
        'getQr' => true
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json'
    ));

    $response = curl_exec($curl);
    if (!$response) {
        die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
    }
    curl_close($curl);
    $responseData = json_decode($response, true);

    $apiResponse = $responseData['apiCallResponse']['Response'] ?? [];
    $qrImageUrl = $apiResponse['QrImage'] ?? 'No QR code URL available.';
    $orderRef = $apiResponse['OrderRef'] ?? 'No order reference available.';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QR Code and Status Check</title>
<script>
var refreshInterval; // Interval for refreshing the QR code

function refreshQRCode(qrImageUrl) {
    var qrImage = document.getElementById('qrImage');
    if (qrImage) {
        qrImage.src = qrImageUrl + '?' + new Date().getTime(); // Appending timestamp to avoid cache issues
    }
}

function checkStatus(orderRef) {
    fetch('index.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'checkStatus=true&orderRef=' + orderRef
    })
    .then(response => response.json())
    .then(data => {
        console.log(data); // For debugging purposes, log the data received from the server

        // Update the logs with detailed status from the second API call
        document.getElementById('detailedLogs').innerHTML = `
            <p>Auth Success: ${data.authResponse && data.authResponse.Success}</p>
            <p>Auth Error Message: ${data.authResponse && data.authResponse.ErrorMessage}</p>
            <p>API Call Success: ${data.apiCallResponse && data.apiCallResponse.Success}</p>
            <p>Status Message: ${data.apiCallResponse && data.apiCallResponse.StatusMessage}</p>
            <p>Order Reference: ${data.apiCallResponse && data.apiCallResponse.Response && data.apiCallResponse.Response.OrderRef}</p>
            <p>Completion Status: ${data.apiCallResponse && data.apiCallResponse.Response && data.apiCallResponse.Response.Status}</p>
            <p>Hint Code: ${data.apiCallResponse && data.apiCallResponse.Response && data.apiCallResponse.Response.HintCode}</p>
        `;

        if (data.apiCallResponse.Response.Status === "complete") {
            clearInterval(refreshInterval); // Stop refreshing the QR code
            var user = data.apiCallResponse.Response.CompletionData.user;
            document.getElementById('qrImageContainer').innerHTML = `
                <p>SUCCESS</p>
                <p>Personal Number: ${user.personalNumber}</p>
                <p>Name: ${user.name}</p>
                <p>Given Name: ${user.givenName}</p>
                <p>Surname: ${user.surname}</p>
            `;
        } else {
            // If conditions are not met, keep polling every 5 seconds
            setTimeout(function() { checkStatus(orderRef); }, 5000);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        setTimeout(function() { checkStatus(orderRef); }, 5000);
    });
}

window.onload = function() {
    var orderRef = '<?php echo $orderRef; ?>';
    var qrImageUrl = '<?php echo $qrImageUrl; ?>';
    refreshQRCode(qrImageUrl);
    refreshInterval = setInterval(function() { refreshQRCode(qrImageUrl); }, 5000); // Set up the interval to refresh QR code every 5 seconds
    checkStatus(orderRef);
}
</script>
</head>
<body>
    <h1>QR Code</h1>
    <div id="qrImageContainer">
        <?php if (isset($qrImageUrl) && $qrImageUrl !== 'No QR code URL available.') { ?>
            <img id="qrImage" src="<?php echo $qrImageUrl; ?>" alt="QR Code"><br>
        <?php } else { ?>
            <p>QR Code URL not available.</p>
        <?php } ?>
    </div>
    <div id="logs"></div>
    <h2>Log Call Endpoint 1</h2>
    <p>Auth Success: <?php echo $responseData['authResponse']['Success'] ?? 'No data'; ?></p>
    <p>Auth Error Message: <?php echo $responseData['authResponse']['ErrorMessage'] ?? 'No error message'; ?></p>
    <p>API Call Success: <?php echo $responseData['apiCallResponse']['Success'] ?? 'No data'; ?></p>
    <p>Status Message: <?php echo $responseData['apiCallResponse']['StatusMessage'] ?? 'No status message'; ?></p>
    <p>Order Reference: <?php echo $orderRef; ?></p>
    <div id="messageContainer"></div>
    <h2>Log Call Endpoint 2</h2>
    <div id="detailedLogs"></div>
</body>
</html>

为了将此功能引入 WordPress,我考虑创建一个简单的插件并填充脚本,以便 Wordpress 可以处理它(也涉及 JS 和 AJAX 功能)

我创建了一个简单的插件结构

  • 主要插件-index.php
  • api-handler.php 用于实际调用。
  • template.php 用于输出 和 /js 文件夹,我在其中找到用于刷新二维码的 js 脚本文件。 我在实际页面上使用短代码函数以及页面上所需的部分来调用所有这些。

plugin-index.php 文件

<?php
/*
Plugin Name: Plugin Name 
Description: Integrates QR code generation and status check verification.
Version: 1.0
Author: me.
*/

function ba_bank_enqueue_scripts() {
    wp_enqueue_script('ba_bank-ajax', plugin_dir_url(__FILE__) . 'js/bankid-ajax.js', array('jquery'), null, true);
    wp_localize_script('bba_bank-ajax', 'bankidAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'ba_bank_enqueue_scripts');

include_once plugin_dir_path(__FILE__) . 'api-handler.php';

function byggauktion_bankid_shortcode() {
    $response = get_initial_qr_code_data();
    $responseData = json_decode($response, true);
    $qrImageUrl = $responseData['apiCallResponse']['Response']['QrImage'] ?? 'No QR code URL available.';
    $orderRef = $responseData['OrderRef'] ?? 'No order reference available.';

    ob_start();
    ?>
    <div id="qrImageContainer">
        <?php if ($qrImageUrl !== 'No QR code URL available.'): ?>
            <img id="qrImage" src="<?php echo esc_url($qrImageUrl); ?>" alt="QR Code"><br>
        <?php else: ?>
            <p>QR code URL not available.</p>
        <?php endif; ?>
        <div id="updateArea">
            <p>Scan the QR code above. Updates will appear here once available.</p>
        </div>
    </div>
    <input type="hidden" id="orderRef" value="<?php echo esc_attr($orderRef); ?>">
    <?php
    echo ob_get_clean();
}
add_shortcode('ba_bank', 'ba_bank_shortcode');

function ba_bank_handle_ajax() {
    check_status_update();
    wp_die();
}
add_action('wp_ajax_ba_check_status', 'ba_bank_handle_ajax');
add_action('wp_ajax_nopriv_ba_check_status', 'ba_bank__handle_ajax');

api-handler.php

<?php
function get_initial_qr_code_data() {
    $data = [
        'apiUser' => 'aaa',
        'password' => 'xxx',
        'companyApiGuid' => 'zzz',
        'endUserIp' => $_SERVER['REMOTE_ADDR'],
        'getQr' => true
    ];
    return make_bank_api_call('https://url/endpoint1', $data);
}

function check_status_update() {
    $orderRef = isset($_POST['orderRef']) ? sanitize_text_field($_POST['orderRef']) : '';
    $data = [
        'apiUser' => 'aaa',
        'password' => 'xxx',
        'companyApiGuid' => 'zzz',
        'orderRef' => $orderRef
    ];
    $response = make_bank_api_call('https://url/endpoint2', $data);
    echo $response;
}

function make_bank_api_call($url, $data) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response ? $response : json_encode(['error' => 'No response from API']);
}

用于 html 输出的 template.php 文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QR Code and Status Check</title>
</head>
<body>
    <h1>QR Code</h1>
    <div id="qrImageContainer">
        <?php if (isset($qrImageUrl) && $qrImageUrl !== 'No QR code URL available.') : ?>
            <img id="qrImage" src="<?php echo $qrImageUrl; ?>" alt="QR Code">
        <?php else : ?>
            <p>QR Code URL not available.</p>
        <?php endif; ?>
    </div>
    <div id="logs"></div>
    <h2>Log Call Endpoint 1</h2>
    <p>Order Reference: <?php echo isset($orderRef) ? $orderRef : 'No order reference available.'; ?></p>

    <p>Auth Success: <?php echo $responseData['authResponse']['Success'] ?? 'No data'; ?></p>
    <p>Auth Error Message: <?php echo $responseData['authResponse']['ErrorMessage'] ?? 'No error message'; ?></p>
    <p>API Call Success: <?php echo $responseData['apiCallResponse']['Success'] ?? 'No data'; ?></p>
    <p>Status Message: <?php echo $responseData['apiCallResponse']['StatusMessage'] ?? 'No status message'; ?></p>
    <p>Order Reference: <?php echo $orderRef; ?></p>
    <div id="messageContainer"></div>
    <h2>Log Call Endpoint 2</h2>
    <div id="detailedLogs"></div>
    <script src="<?php echo plugin_dir_url(__FILE__) . 'js/bankid-ajax.js'; ?>"></script>
</body>
</html>

最后是bankid-ajax,js

document.addEventListener('DOMContentLoaded', function() {
    var qrImage = document.getElementById('qrImage');
    var orderRef = document.getElementById('orderRef').value;
    var updateArea = document.getElementById('updateArea');

    function checkStatus(orderRef) {
        fetch(bankidAjax.ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=byggauktion_check_status&orderRef=' + encodeURIComponent(orderRef)
        })
        .then(response => response.json())
        .then(data => {
            // Dynamically update content
            if (data.status === 'complete') {
                updateArea.innerHTML = '<p>Verification completed successfully for user ' + data.user.name + '</p>';
            } else {
                updateArea.innerHTML = '<p>Status: ' + data.status + '</p>';
            }
            if (data.newQrImage) {
                qrImage.src = data.newQrImage + '?refresh=' + new Date().getTime();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            updateArea.innerHTML = '<p>Error checking status. Please try again.</p>';
        });
    }

    setInterval(() => checkStatus(orderRef), 5000);
});

我无法通过这种方式连接到API,并且无法显示二维码。我已经尝试将其进一步简化。可以尝试给我建议如何针对我的 WordPress 用例进一步简化我的脚本吗?

谢谢你

php wordpress
1个回答
0
投票

为了扩展我的评论,您在代码中遗漏了一些关键内容。

首先,让我们生成一个随机数并将其传递给您的 JS。

function ba_bank_enqueue_scripts() {
    wp_enqueue_script('ba_bank-ajax', plugin_dir_url(__FILE__) . 'js/bankid-ajax.js', array('jquery'), null, true);
    $bankcheck_nonce   = wp_create_nonce( 'bankcheck_nonce' );
    wp_localize_script( 'bba_bank-ajax', 'bankidAjax',
        array(
            'ajaxurl'           => admin_url( 'admin-ajax.php' ),
            'bankcheck_nonce'   => $bankcheck_nonce
        )
    );
}
add_action( 'wp_enqueue_scripts', 'ba_bank_enqueue_scripts' );

现在,在 JS 文件中,您需要将其与

ajaxurl
...

一起调用
//add the nonce value to a variable & add it to your action string
var security = bankidAjax.bankcheck_nonce;
function checkStatus( orderRef ) {
    fetch( bankidAjax.ajaxurl {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=byggauktion_check_status&security='+security+'&orderRef=' + encodeURIComponent(orderRef)
    } )

现在我们必须确保您的回调函数与您在 JS 中使用的操作名称相匹配,并检查您的 AJAX 引用:

function check_status_update() {
    //this checks the ajax referer to make sure it's permitted
    check_ajax_referer( 'bankcheck_nonce', 'security' );
    $orderRef = isset($_POST['orderRef']) ? sanitize_text_field($_POST['orderRef']) : '';
    $data = [
        'apiUser' => 'aaa',
        'password' => 'xxx',
        'companyApiGuid' => 'zzz',
        'orderRef' => $orderRef
    ];
    $response = make_bank_api_call( 'https://url/endpoint2', $data );
    echo $response;
    //stops AJAX from returning a 0 as a response, basically ends the process for you
    wp_die();
}
//this next bit is key, you have to add an action and use the action name from your JS
//in your JS you used byggauktion_check_status
//for logged in users
add_action( 'wp_ajax_byggauktion_check_status',  'check_status_update' );
//for logged out users, if this needs to function on the front end
add_action( 'wp_ajax_nopriv_byggauktion_check_status',  'check_status_update' );

显然这是未经测试的,但是通过这些添加的元素,您应该能够自己调试其余的元素。 :-) 祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.