You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PHP代码使Authorize.net支付页显示客户最近4个支付档案

如何让Authorize.net Accept Hosted页面显示客户最近的4个支付档案

我用PHP开发,代码文件为AcceptSuite/get-an-accept-payment-page.php。根据Authorize.net官方文档,使用Customer Profiles功能时,在getHostedPaymentPageRequest请求的customerProfileId元素中传入客户档案ID后,浏览器显示的表单应展示该客户最近的4个支付档案,客户可选择这些支付方式、输入新支付信息并保存为后续可用的支付档案。但当前页面并未显示这4个最近的支付档案,请问该如何修改代码实现此功能?

当前代码

<?php
  require 'vendor/autoload.php';
  require_once 'includes/classes/SampleCodeConstants.php';
  use net\authorize\api\contract\v1 as AnetAPI;
  use net\authorize\api\controller as AnetController;

  define("AUTHORIZENET_LOG_FILE", "phplog");
    $customerProfileId = "your custome id";


function getAnAcceptPaymentPage($customerProfileId)
{
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName(\SampleCodeConstants::MERCHANT_LOGIN_ID);
    $merchantAuthentication->setTransactionKey(\SampleCodeConstants::MERCHANT_TRANSACTION_KEY);

    $setting = new AnetAPI\SettingType();
    $setting->setSettingName("hostedPaymentButtonOptions");
    $setting->setSettingValue("{\"text\": \"Pay\"}");

    $setting1 = new AnetAPI\SettingType();
    $setting1->setSettingName("hostedPaymentOrderOptions");
    $setting1->setSettingValue("{\"show\": false}");

    $setting5 = new AnetAPI\SettingType();
    $setting5->setSettingName("hostedPaymentBillingAddressOptions");
    $setting5->setSettingValue('{"show": false, "required": false}');

    $customerProfile = new AnetAPI\CustomerProfilePaymentType();
    $customerProfile->setCustomerProfileId($customerProfileId);

    $customerOptions = new AnetAPI\SettingType();
    $customerOptions->setSettingName("hostedPaymentCustomerOptions");
    $customerOptions->setSettingValue("{\"showEmail\": false, \"requiredEmail\":false, \"addPaymentProfile\": true}");

    $transactionRequestType = new AnetAPI\TransactionRequestType();
    //$transactionRequestType->setTransactionType("authCaptureTransaction");
    $transactionRequestType->setTransactionType("authOnlyTransaction");
    $transactionRequestType->setAmount(100.00);
    $transactionRequestType->setProfile($customerProfile);

    $hostedPaymentOptions = new AnetAPI\SettingType();
    $hostedPaymentOptions->setSettingName("hostedPaymentPaymentOptions");
    $hostedPaymentOptions->setSettingValue("{\"cardCodeRequired\": true, \"showCreditCard\": true, \"showBankAccount\": false}");

    $request = new AnetAPI\GetHostedPaymentPageRequest();
    $request->setMerchantAuthentication($merchantAuthentication);
    $request->setTransactionRequest($transactionRequestType);
    $request->addToHostedPaymentSettings($setting);
    $request->addToHostedPaymentSettings($setting1);
    $request->addToHostedPaymentSettings($setting5);
    $request->addToHostedPaymentSettings($customerOptions);
    $request->addToHostedPaymentSettings($hostedPaymentOptions);

    $controller = new AnetController\GetHostedPaymentPageController($request);
    $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

    if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
        //echo "Hosted payment page token: " . $response->getToken() . "\n";
        return $response->getToken();

    } else {
        echo "ERROR :  Failed to get hosted payment page\n";
    }
}

$token = getAnAcceptPaymentPage($customerProfileId);
?>

<?php
include("include the file with the code");


?>

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<head>
    <title>HostedPayment Test Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script type="text/javascript">

        $(function () {

            //$("#btnOpenAuthorizeNetIFrame").click(function () {
                $("#add_payment").show();
                $("#send_token").attr({ "action": "https://test.authorize.net/payment/payment", "target": "add_payment" }).submit();
                //$("#send_token").attr({ "action": "https://accept.authorize.net/payment/payment", "target": "add_payment" }).submit();
                $(window).scrollTop($('#add_payment').offset().top - 50);
            //});

        });


</script>
</head>
<body>
<!--     
    <div>
        Open Authorize.net in an iframe to complete transaction
        <button id="btnOpenAuthorizeNetIFrame" onclick="">Show Payment Form</button>
    </div>
-->
    <div    id="iframe_holder" class="center-block" style="width:90%;max-width: 1000px">
        <iframe id="add_payment" class="embed-responsive-item panel" name="add_payment" width="100%"  height="600" border="1" frameborder="0" scrolling="no" hidden="true">
        </iframe>
    </div>
    <form id="send_token" action="" method="post" target="add_payment" >
        <input type="hidden" name="token" value="<?php echo $token; ?>" />
    </form>

    <script type="text/javascript">

        (function () {
            if (!window.AuthorizeNetIFrame) window.AuthorizeNetIFrame = {};
                AuthorizeNetIFrame.onReceiveCommunication = function (querystr) {
                    var params = parseQueryString(querystr);
                        switch (params["action"]) {
                            case "successfulSave":
                                break;
                            case "cancel":
                                break;
                            case "resizeWindow":
                                var w = parseInt(params["width"]);
                                var h = parseInt(params["height"]);
                                var ifrm = document.getElementById("add_payment");
                                ifrm.style.width = w.toString() + "px";
                                ifrm.style.height = h.toString() + "px";
                                break;
                            case "transactResponse":
                                var ifrm = document.getElementById("add_payment");
                                ifrm.style.display = 'none';
                            }
                    };

                function parseQueryString(str) {
                    var vars = [];
                    var arr = str.split('&');
                    var pair;
                    for (var i = 0; i < arr.length; i++) {
                        pair = arr[i].split('=');
                        vars.push(pair[0]);
                        vars[pair[0]] = unescape(pair[1]);
                        }
                    return vars;
                    }
        }());
    </script>
</body>
</html>

修复方案

1. 添加客户档案返回选项设置

需要新增hostedPaymentReturnCustomerProfileOptions配置,明确开启显示客户档案支付方式的功能:

$returnProfileOptions = new AnetAPI\SettingType();
$returnProfileOptions->setSettingName("hostedPaymentReturnCustomerProfileOptions");
$returnProfileOptions->setSettingValue('{"show": true, "allowAddPayment": true}');

将该配置添加到请求的hostedPaymentSettings列表中:

$request->addToHostedPaymentSettings($returnProfileOptions);

2. 更新支付选项配置

在hostedPaymentPaymentOptions中添加allowStoredPaymentMethods参数,明确允许显示已存储的支付方式:

$hostedPaymentOptions->setSettingValue("{\"cardCodeRequired\": true, \"showCreditCard\": true, \"showBankAccount\": false, \"allowStoredPaymentMethods\": true}");

3. 验证客户档案存在支付记录

确保传入的$customerProfileId对应的客户档案下已创建至少一个支付档案,否则页面不会显示历史支付方式。

4. 完整修改后的核心函数代码

整合上述修改后的getAnAcceptPaymentPage函数如下:

function getAnAcceptPaymentPage($customerProfileId)
{
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName(\SampleCodeConstants::MERCHANT_LOGIN_ID);
    $merchantAuthentication->setTransactionKey(\SampleCodeConstants::MERCHANT_TRANSACTION_KEY);

    $setting = new AnetAPI\SettingType();
    $setting->setSettingName("hostedPaymentButtonOptions");
    $setting->setSettingValue("{\"text\": \"Pay\"}");

    $setting1 = new AnetAPI\SettingType();
    $setting1->setSettingName("hostedPaymentOrderOptions");
    $setting1->setSettingValue("{\"show\": false}");

    $setting5 = new AnetAPI\SettingType();
    $setting5->setSettingName("hostedPaymentBillingAddressOptions");
    $setting5->setSettingValue('{"show": false, "required": false}');

    $customerProfile = new AnetAPI\CustomerProfilePaymentType();
    $customerProfile->setCustomerProfileId($customerProfileId);

    $customerOptions = new AnetAPI\SettingType();
    $customerOptions->setSettingName("hostedPaymentCustomerOptions");
    $customerOptions->setSettingValue("{\"showEmail\": false, \"requiredEmail\":false, \"addPaymentProfile\": true}");

    // 新增客户档案返回选项配置
    $returnProfileOptions = new AnetAPI\SettingType();
    $returnProfileOptions->setSettingName("hostedPaymentReturnCustomerProfileOptions");
    $returnProfileOptions->setSettingValue('{"show": true, "allowAddPayment": true}');

    $transactionRequestType = new AnetAPI\TransactionRequestType();
    $transactionRequestType->setTransactionType("authOnlyTransaction");
    $transactionRequestType->setAmount(100.00);
    $transactionRequestType->setProfile($customerProfile);

    $hostedPaymentOptions = new AnetAPI\SettingType();
    $hostedPaymentOptions->setSettingName("hostedPaymentPaymentOptions");
    // 更新支付选项,允许显示存储的支付方式
    $hostedPaymentOptions->setSettingValue("{\"cardCodeRequired\": true, \"showCreditCard\": true, \"showBankAccount\": false, \"allowStoredPaymentMethods\": true}");

    $request = new AnetAPI\GetHostedPaymentPageRequest();
    $request->setMerchantAuthentication($merchantAuthentication);
    $request->setTransactionRequest($transactionRequestType);
    $request->addToHostedPaymentSettings($setting);
    $request->addToHostedPaymentSettings($setting1);
    $request->addToHostedPaymentSettings($setting5);
    $request->addToHostedPaymentSettings($customerOptions);
    $request->addToHostedPaymentSettings($hostedPaymentOptions);
    // 添加新配置到请求
    $request->addToHostedPaymentSettings($returnProfileOptions);

    $controller = new AnetController\GetHostedPaymentPageController($request);
    $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);

    if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
        return $response->getToken();
    } else {
        echo "ERROR :  Failed to get hosted payment page\n";
    }
}

5. 测试验证

修改代码后,使用存在支付档案的客户ID重新生成支付页面,此时iframe内的表单应显示该客户最近的4个支付档案选项,客户可选择已有方式或添加新支付信息。

内容的提问来源于stack exchange,提问作者SnappyDesign

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:34:51