AuthnetJson 命名空间 John Conde

AuthnetJson Namespace John Conde

我似乎无法在另一个函数中使用它。所以我有一个名为 user_authnet($user) 的函数,我在其中将数据库中的数组传递给用户对象。在该对象中,我存储了 authorize.net 客户资料 ID。所以我尝试调用 Auth.net API 来获取付款方式和订阅。

如果我包括

namespace JohnConde\Authnet;

在我的脚本顶部,然后我得到

function 'user_authnet' not found or invalid function name

作为一个错误。我猜是因为它不属于您的任何 类。

如果我不放置命名空间声明,我得到

Class 'AuthnetApiFactory' not found

即使 autoload.php 是 运行。

我正在尝试为 Wordpress 制作一个插件。这是我的完整代码:

namespace JohnConde\Authnet;
include get_template_directory() . '/assets/vendor/authnetjson/config.inc.php'; 
include get_template_directory() . '/assets/vendor/authnetjson/src/autoload.php';

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY, AuthnetApiFactory::USE_DEVELOPMENT_SERVER);                

add_action( 'show_user_profile', 'user_authnet' );
add_action( 'edit_user_profile', 'user_authnet' );  


function user_authnet( $user )
{   
    global $request;
    ?>
        <h3>Stored Payment Methods</h3>
        <input type="text" name="authnet_customerProfileId" value="<?php echo esc_attr(get_the_author_meta( 'authnet_customerProfileId', $user->ID )); ?>">
    <?php
        if(get_the_author_meta( 'authnet_customerProfileId', $user->ID )) {

            $response = $request->getCustomerProfileRequest(array(
                "customerProfileId" => get_the_author_meta('authnet_customerProfileId', $user->ID)
            ));

            print_r($response);
        }
}


add_action( 'personal_options_update', 'save_authnet' );
add_action( 'edit_user_profile_update', 'save_authnet' );

function save_authnet( $user_id )
{
    update_user_meta($user_id, 'authnet_customerProfileId', $_POST['authnet_customerProfileId']);
}

通过将该命名空间放置在页面顶部,您实际上是将整个页面放置在该命名空间中。你不想那样做。

相反,只需将命名空间添加到您对 AuthnetApiFactory::getJsonApiHandler() 的调用之前,这样您仍然可以在全局命名空间中工作。

// Remove the line below
//namespace JohnConde\Authnet;
include get_template_directory() . '/assets/vendor/authnetjson/config.inc.php'; 
include get_template_directory() . '/assets/vendor/authnetjson/src/autoload.php';

// Add the namespace to your call to AuthnetApiFactory::getJsonApiHandler()
$request = \JohnConde\Authnet\AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY, \JohnConde\Authnet\AuthnetApiFactory::USE_DEVELOPMENT_SERVER);                

您还可以使用 use 语句稍微缩短此语法:

use JohnConde\Authnet\AuthnetApiFactory;
include get_template_directory() . '/assets/vendor/authnetjson/config.inc.php'; 
include get_template_directory() . '/assets/vendor/authnetjson/src/autoload.php';

$request = \JohnConde\Authnet\AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY, AuthnetApiFactory::USE_DEVELOPMENT_SERVER);