pi-space/notion-api-integration

易于使用且简单的Notion API集成。

v2.4.0 2023-07-23 19:49 UTC

README

关于

Laravel Notion Integration包是Notion.so提供的REST API的包装器。它允许您轻松地与您的Notion工作空间进行交互,节省您的时间和精力。

此包提供了一个简单且流畅的接口,用于操作页面、数据库、用户、块等。

安装

您可以通过composer安装此包

composer require pi-space/notion-api-integration

使用方法

设置Notion工作空间

在您的.env文件中,添加您的Notion令牌

NOTION_TOKEN=secret_{token}

要创建您的第一个集成,请访问:Notion创建集成要获取您的密钥令牌,请访问Notion API

处理Notion数据库

通过ID获取Notion数据库

要通过ID获取Notion数据库,使用NotionDatabase类的find方法。它将返回一个包含标题、描述和所有数据库属性的NotionDatabase对象。

use PISpace\Notion\Core\Models\NotionDatabase;

$database = NotionDatabase::make('632b5fb7e06c4404ae12065c48280e4c')->find();

创建Notion数据库

要创建Notion数据库,使用NotionDatabase类并设置所需的参数,例如父页面ID和属性模式。

use PISpace\Notion\Core\Models\NotionDatabase;

$database = NotionDatabase::make()
    ->setParentPageId('fa4379661ed948d7af52df923177028e')
    ->setTitle('Test Database2')
    ->buildProperties([
            NotionTitle::make('Name'),
            NotionSelect::make('Status')->setOptions([
                ['name' => 'A', 'color' => 'red'],
                ['name' => 'B', 'color' => 'green']
            ]),
            NotionDate::make('Date'),
            NotionCheckbox::make('Checkbox'),
            NotionFormula::make('Formula')->setExpression('prop("Name")'),
            NotionRelation::make('Relation')
                ->setDatabaseId($this->databaseId),
            NotionRollup::make('Rollup')
                ->setRollupPropertyName('Name')
                ->setRelationPropertyName('Relation')
                ->setFunction('count'),
            NotionPeople::make('People'),
            NotionMedia::make('Media'),
            NotionEmail::make('Email'),
            NotionNumber::make('Number'),
            NotionPhoneNumber::make('Phone'),
            NotionUrl::make('Url'),
            NotionCreatedTime::make('CreatedTime'),
            NotionCreatedBy::make('CreatedBy'),
            NotionLastEditedTime::make('LastEditedTime'),
            NotionLastEditedBy::make('LastEditedBy'),
    ])
    ->create();

更新Notion数据库

要更新现有的Notion数据库,使用NotionDatabase类并指定数据库ID和更新后的属性。

$database = NotionDatabase::make('a5f8af6484334c09b69d5dd5f54b378f')
    ->buildProperties([
        // Specify the updated properties
    ])
    ->update();

查询数据库

要查询Notion数据库并获取数据库中包含的页面列表,您可以使用query方法应用过滤器和排序标准。

// Using one filter
$paginated = NotionDatabase::make('632b5fb7e06c4404ae12065c48280e4c')
        ->setFilter(NotionSelect::make('Status')->equals('In Progress'))
        ->query();

// Using multiple filters with AND operator
$pages = $database->setFilters([
    NotionFilter::groupWithAnd([
            NotionSelect::make('Status')->equals('Reading'),
            NotionTitle::make('Name')->equals('MMMM')
        ])
])->query();

// Using multiple filters with OR operator
$pages = $database->setFilters([
    NotionFilter::groupWithOr([
            NotionSelect::make('Status')->equals('Reading'),
            NotionTitle::make('Name')->equals('MMMM')
        ])
])->query();

// Using Notion Compound Filters
$response = $database->setFilters([
    NotionFilter::groupWithOr([
            NotionSelect::make('Status')->equals('Reading'),
            NotionFilter::groupWithAnd([
                NotionTitle::make('Name')->contains('MMMM'),
                NotionTitle::make('Name')->contains('EEEE')
            ])
        ]),
])->query();

// Sorting database results
$pages = $database->sorts(NotionSort::property('Name')->ascending())
    ->query();

// Sort with multiple properties
$pages = $database->setSorts([
            NotionTitle::make('Name')->ascending(),
            NotionDate::make('Date')->descending()
        ])->query();

// Apply sorts and filters together
$pages = $database->setSorts([
            NotionTitle::make('Name')->ascending(),
            NotionDate::make('Date')->descending()
        ])->setFilters([
    NotionFilter::groupWithOr([
            NotionSelect::make('Status')->equals('Reading'),
            NotionTitle::make('Name')->equals('MMMM')
        ])
])->query();

处理Notion页面

通过ID获取页面(不包含页面内容)

$page = NotionPage::make('b4f8e429038744ca9c8d5afa93ea2edd')->find();

通过ID获取页面(包含页面内容)

$page = NotionPage::make('b4f8e429038744ca9c8d5afa93ea2edd')->findWithContent();

创建新的Notion页面/Notion数据库项

要创建新的Notion页面或新的Notion数据库项,您可以使用NotionPage类并设置所需的属性及其值。

$page = NotionPage::make()
     ->setDatabaseId('a5f8af6484334c09b69d5dd5f54b378f')
        ->buildProperties([
            NotionTitle::make('Name')
                ->setTitle('Test'),
            NotionSelect::make('Status')
                ->setSelected('A'),
            NotionDate::make('Date')
                ->setStart('2021-01-01'),
            NotionCheckbox::make('Checkbox')
                ->setChecked(true),
            NotionRelation::make('Relation')
                ->setPageIds(['633fc9822c794e3682186491c50210e6']),
            NotionText::make('Password')
                ->setText('Text'),
            NotionPeople::make('People')
                ->setPeople([
                    NotionUser::make('2c4d6a4a-12fe-4ce8-a7e4-e3019cc4765f'),
                ]),
            NotionMedia::make('Media')
                ->setFiles([
                    NotionFile::make()
                        ->setFileType('file')
                        ->setRelativeType('external')
                        ->setFileUrl('https://www.google.com'),
                ]),
            NotionEmail::make('Email')
                ->setEmail('eyadhamza0@gmail.com'),
            NotionNumber::make('Number')
                ->setNumber(10),
            NotionPhoneNumber::make('Phone')
                ->setPhoneNumber('+201010101010'),
            NotionUrl::make('Url')
                ->setUrl('https://www.google.com'),
        ])
    ->create();

创建带有内容的新的Notion页面/Notion数据库项

 $page = NotionPage::make()
        ->setDatabaseId($this->databaseId)
        ->buildProperties([
            NotionTitle::make('Name', 'Test'),
            NotionSelect::make('Status')
                ->setSelected('A'),
        ])->setBlockBuilder(
        NotionBlockBuilder::make()
            ->headingOne(NotionRichText::text('Eyad Hamza')
                ->isToggleable()
                ->setBlockBuilder(
                    NotionBlockBuilder::make()
                        ->headingOne(NotionRichText::text('Eyad Hamza')
                            ->bold()
                            ->italic()
                            ->strikethrough()
                            ->underline()
                            ->code()
                            ->color('red')
                        )
                )
                ->bold()
                ->italic()
                ->strikethrough()
                ->underline()
                ->code()
                ->color('red')
            )
            ->headingTwo('Heading 2')
            ->headingThree('Heading 3')
            ->numberedList([
                'Numbered List',
                'asdasd Numbered List'
            ])
            ->bulletedList(['Bullet List'])
            ->paragraph('Paragraph')
            ->toDo(['To Do List'])
            ->toggle('Toggle')
            ->quote('Quote')
            ->divider()
            ->callout('Callout')
            ->image(NotionFile::make()
                ->setFileType('image')
                ->setFileUrl('https://my.alfred.edu/zoom/_images/foster-lake.jpg')
                ->setRelativeType('external')
            )
            ->file(NotionFile::make()
                ->setFileType('file')
                ->setFileUrl('https://www.google.com')
                ->setRelativeType('external')
            )
            ->embed('https://www.google.com')
            ->bookmark('https://www.google.com')
            ->code(NotionRichText::text('echo "Hello World"')->setCodeLanguage('php'))
            ->equation('x^2 + y^2 = z^2')
            ->pdf(NotionFile::make()
                ->setFileType('pdf')
                ->setFileUrl('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')
                ->setRelativeType('external')
            )
            ->video(NotionFile::make()
                ->setFileType('video')
                ->setFileUrl('https://www.youtube.com/watch?v=xTQ7vhtp23w')
                ->setRelativeType('external')
            )
    )->create();

更新页面属性

要更新现有页面的属性,创建一个包含页面ID的NotionPage对象,设置更新的属性,并调用update()方法。

$page = NotionPage::make('b4f8e429038744ca9c8d5afa93ea2edd')
    ->buildProperties([
    // Specify the updated properties
])->update();

删除页面

要删除页面,创建一个包含页面ID的NotionPage对象并调用delete()方法。

$page = NotionPage::make('b4f8e429038744ca9c8d5afa93ea2edd')->delete();

处理Notion块

通过ID获取块

要通过ID获取Notion块,使用NotionBlock类的find方法。

$block = NotionBlock::make('b4f8e429038744ca9c8d5afa93ea2edd')->find();

获取块子项

要获取Notion块的子块,使用fetchChildren方法。

$blockChildren = NotionBlock::make('b4f8e429038744ca9c8d5afa93ea2edd')
        ->fetchChildren();

更新块

要更新Notion块,创建一个新的NotionBlock实例,设置更新的内容,并调用update()方法。

$block = NotionBlock::make('62ec21df1f9241ba9954828e0958da69')
        ->setType(NotionBlockTypeEnum::HEADING_1)
        ->setBlockContent(NotionRichText::text('Eyad Hamza'))
        ->update();

添加块子项

要向Notion块添加子块,使用createChildren方法。

$block = NotionBlock::make('62ec21df1f9241ba9954828e0958da69')
     ->setBlockBuilder(
        NotionBlockBuilder::make()
            ->headingTwo(NotionRichText::text('Eyad Hamza')
                ->bold()
                ->setLink('https://www.google.com')
                ->color('red'))
            ->headingThree('Heading 3')
            ->numberedList(['Numbered List'])
            ->bulletedList(['Bullet List'])
    )->createChildren();

删除块

要删除Notion块,使用delete方法。

$block = NotionBlock::make('62ec21df1f9241ba9954828e0958da69')->delete();

搜索

您可以使用NotionSearch类在Notion页面或数据库中执行搜索。

在页面中搜索

要在 Notion 页面中搜索特定查询,请使用 NotionSearch 类的 inPages 方法。您可以使用 sorts 方法应用排序标准。

$response = NotionSearch::inPages('Eyad')
    ->sorts([
            NotionLastEditedTime::make()->ascending(),
    ])
    ->apply(50);

数据库搜索

要在 Notion 数据库中搜索特定查询,请使用 NotionSearch 类的 inDatabases 方法。

$response = NotionSearch::inDatabases('Eyad')->apply(50);

用户

检索所有用户

要检索所有 Notion 用户,请使用 NotionUser 类的 index 方法。

$users = NotionUser::make()->index();

通过 ID 检索用户

要按 ID 检索特定的 Notion 用户,请使用 NotionUser 类的 find 方法。

$user = NotionUser::make('2c4d6a4a-12fe-4ce8-a7e4-e3019cc4765f')->find();

检索当前机器人信息

要检索当前 Notion 机器人的信息,请使用 NotionUser 类的 getBot 方法。

$bot = NotionUser::make()->getBot();

评论

通过页面 ID / 讨论ID检索所有评论

要检索与页面或讨论相关联的所有评论,请使用 NotionComment 类的 index 方法。

$comments = NotionComment::make('0b036890391f417cbac775e8b0bba680')->index();

创建新评论

要在页面或讨论中创建新评论,请使用 NotionComment 类并设置父 ID 和内容。

// You can pass a rich text object if you want to format the comment
NotionComment::make()
        ->setDiscussionId('ac803deb7b064cca83067c67914b02b4')
        ->setContent(NotionRichText::make('This is a comment')
            ->color('red')
            ->bold()
            ->italic()
        )
        ->create();

// Or you can pass a string
NotionComment::make()
        ->setParentId('a270ab4fa945449f9284b180234b00c3')
        ->setContent('This is a comment')
        ->create();

分页

Notion API 为某些端点提供分页响应。NotionPaginator 类为您处理分页。

带有搜索结果的示例

$response = NotionSearch::inPages('Eyad')->apply(50);
$pages = $response->getResults(); // Get the first 50 results
$response->hasMore(); // Check if there are more results
$response->next() // Get the next 50 results (if hasMore is true)
$response->getObjectType(); // Get the type of the object (always "list")
$response->getResultsType() // Get the type of the results (Block/Database/Page)

将 Eloquent 模型映射到 Notion 数据库项

要将您的 Laravel Eloquent 模型映射到 Notion 数据库项,您可以使用 Notionable 特性并在您的模型中实现 mapToNotion 方法。

class User extends Model
{
    use Notionable;

    protected string $notionDatabaseId = '74dc9419bec24f10bb2e65c1259fc65a';

    protected $guarded = [];

    public function mapToNotion(): array
    {
        return [
            'name' => NotionTitle::make('Name'),
            'email' => NotionEmail::make('Email'),
            'password' => NotionText::make('Password'),
        ];
    }
}

$user = User::create([
    'name' => 'John Doe',
    'email' => 'johndoe@gmail.com',
    'password' => 'password'
]);

$user->saveToNotion();

在 Notion 和 Eloquent 模型之间同步数据

您可以使用 sync:to-notion Artisan 命令在 Notion 和 Eloquent 模型之间同步数据。

php artisan sync:to-notion User

监视 Notion 数据库

目前,Notion API 不支持 webhooks。但是,您可以使用 'notion:watch' Artisan 命令来监视 Notion 数据库的更改。该命令将按指定的间隔运行并检查 Notion 数据库中的更改。如果有任何更改,它将向您的路由发送 POST 请求,以便您可以相应地处理它。您可以在配置文件中更改间隔和路由。

这是运行命令的方式

php artisan notion:watch '02758e48d12244f99552dd4f766a0077'

当然,您可以将该命令用于 cron 作业,以按指定的间隔运行它。

// in app/Console/Kernel.php

protected function schedule(Schedule $schedule): void
{
    $schedule->command(NotionDatabaseWatcher::class, ['02758e48d12244f99552dd4f766a0077'])->everyMinute();
}

处理错误

在出现错误的情况下,将抛出一个包含错误信息的异常。您可以检查异常文件夹或 NotionException 类以获取有关异常的更多信息。请参阅 Notion API 文档以获取有关错误的详细信息。

测试

要运行包测试,请使用以下命令

composer test

更改日志

请参阅 更改日志 了解最近更改的信息。

贡献

参阅 CONTRIBUTING 了解详细信息。

安全漏洞

请查看 我们的安全策略 了解如何报告安全漏洞。

致谢

许可

MIT 许可证 (MIT)。请参阅 许可文件 了解更多信息。