plai2010/php-msgraph

PHP 的 Microsoft Graph 工具。

v1.2.2 2024-04-24 20:16 UTC

This package is not auto-updated.

Last update: 2024-09-25 22:13:33 UTC


README

这是一个用于在 PHP 应用程序中使用 Microsoft Graph API 的实用程序包。在这个版本中,它只支持向 sendMail 端点发送电子邮件消息。

这个包的使用场景是在 Laravel (10.x) 应用程序中进行电子邮件通知。它包含一个 Laravel 服务提供者。

这个包是为与 [plai2010/php-oauth2][plai2010-oauth2] 一起使用而设计的,用于 OAuth2 令牌管理。

安装

可以从 Packagist 安装此包

$ composer require plai2010/php-msgraph

也可以从 Github 克隆源仓库

$ git clone https://github.com/plai2010/php-msgraph.git
$ cd php-msgraph
$ composer install

示例:发送电子邮件

此包最好作为 Laravel 扩展使用。虽然也可以将其作为仅提供实用程序库使用,但如本示例所示,可能会有些不便。

use PL2010\MsGraph\MsGraphClient;
use PL2010\OAuth2\Contracts\TokenRepository;

// Some PL2010\OAuth2\Contracts\TokenRepository.
// Here we have a single hard coded access token
// wrapped as a token repository.
$tkrepo = new class implements TokenRepository {
	public function getOAuth2Token(string $key, int $valid=0): array {
		return [
			// One single hard coded token regardless of $key.
			'access_token' => '....',
		];
	}
	public function putOAuth2Token(string $key, array $token): static {
		return $this;
	}
};

$msgraph = new MsGraphClient('sendmail', [
	// OAuth2 access token will be retrieved from the
	// token repository using this key.
	'token_key' => 'does-not-matter',
], [
	// Provide token repository.
	'token_repo' => $tkrepo,
]);

$msg = (new \Symfony\Component\Mime\Email())
	->from('no-reply@example.com')
	->to('john.doe@example.com')
	->subject('hello')
	->html('<h3>Greetings!</h3>')
	->attach(file_get_contents('wave.png'), 'wave.png', 'image/png')
;
$msgraph->sendEmail($msg);

客户端管理器

应用程序通常作为单个 MS Graph API 客户端。使用 MsGraphManager 可以配置多个客户端,以应对更复杂的场景。例如,可能有一个作为应用程序的客户端,另一个作为代表个别用户的代理。

// Create manager.
$manager = new PL2010\MsGraph\MsGraphManager;

// Configure a application/service level client.
$manager->configure('service', [
	'token_key' => 'msgraph:app',
]);

// Configure an agent client. Here we assume that
// the token repository recognizes the '@user' tag
// in the token key and looks up user specific
// access token.
$manager->configure('agent', [
	'token_key' => 'msgraph:agent@user',
]);

Laravel 集成

此包包含一个 Laravel 服务提供者,可以通过两种方式提供单例 MsGraphManager

* Abstract 'msgraph' in the application container, i.e. `app('msgraph')`.
* Facade alias 'MsGraph', i.e. `MsGraph::`.

配置文件是 config/msgraph.php。它返回一个按名称组织的客户端配置的关联数组,如下所示

<?php
return [
	'msgraph_site' => [
		'token_key' => 'msgraph:app',
	],
	'msgraph_ua' => [
		'token_key' => 'msgraph:agent@user',
	],
	...
];

还注册了一个 'msgraph' 邮件传输。因此,可以在 config/mailer.php 中定义一个邮件发送器,如下所示

	'outlook' => [
		'transport' => 'msgraph',

		// Points to entry in config/msgraph.php.
		'msgraph' => 'msgraph_site',
	]

然后可以像这样发送消息

	use Illuminate\Mail\Mailable;
	$msg = (new Mailable())
		->to('john.doe@example.com')
		->subject('hello')
		->html('<h3>Greetings!</h3>')
		->send(Mail::mailer('outlook'));