我已经使用google-api-php-client
创建了一个PHP应用程序。我从谷歌控制台创建了一个谷歌帐户电子邮件id,从那里生成了P12文件,并将其放入本地服务器。这可以很好地与"自定义"PHP配合使用。
现在,我想将google-api-php-client
库与我的Symfony项目集成到一个自定义捆绑包中。我在/app/Resources
中创建了一个文件夹"LIB",并将google-api-php-client
的所有文件都放在那里。
然后,我将下面的行放在主控制器中,以包括autoload.php
文件并访问Google_Client
类:
//require_once($this->container->getParameter( 'kernel.root_dir' ). '/../src/ABC/Bundle/TTBundle/Lib/src/Google/autoload.php');
$service_account_email = 'xxxxx-yyyyyy@developer.gserviceaccount.com';
$key_file_location = 'API-Project.p12';
// Create and configure a new client object.
$client = new Google_Client();
但它向我显示了以下错误:
致命错误异常:错误:类在中找不到"ABC\Bundle\TTBundle\Controller\Google_Client"D: \wamp\www\TTPR\current\src\ABC\Bundle\TTBundle\Controller\WebAnalyticsController.php133线
我通过以下步骤解决了问题:
1-在我的控制器中创建一个函数:
2-在getService函数中,我调用了我自己创建的函数,以包含autoload.php文件:
需要知道的重要一点是在创建类的对象时放一个"反斜杠"(/),我错过了这个"反斜线",浪费了我的时间,希望这能帮助一些人并节省时间:)
protected function includeSsrsSdk()
{
require_once($this->container->getParameter( 'kernel.root_dir' ). '/../src/MWAN/Bundle/BIBundle/Lib/src/Google/autoload.php');
}
public function getService()
{
$this->includeSsrsSdk();
$service_account_email = 'xxyyzz@developer.gserviceaccount.com';
$key_file_location = $this->container->getParameter( 'kernel.root_dir' ). '/../src/MWAN/Bundle/BIBundle/Lib/API-Project-xxxx.p12';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new Google_Service_Analytics($client);
// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_email,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
return $analytics;
}