zamblas/invoicexpress-api

Laravel 与 InvoiceXpress API 交互的包

v1.4 2023-08-11 11:09 UTC

This package is auto-updated.

Last update: 2024-09-11 13:52:43 UTC


README

license GitHub release Packagist release

Laravel InvoiceXpress API

Laravel 包用于与 InvoiceXpress API 交互

测试了 Laravel 5.5。*

目录

1 - 安装

通过 Composer

$ composer require rpsimao/invoicexpress-api

在 config/app.php 中注册 Providers 和 Facade(对于 Laravel 5.5 及以上版本不是必需的)

'providers' => [
....

rpsimao\InvoiceXpressAPI\InvoiceXpressAPIServiceProvider::class,

.....

'aliases' => [

.....

'InvoiceXpressClients' =>  rpsimao\InvoiceXpressAPI\InvoiceXpressAPIFacade::class,

.....

1.1 - 发布配置

$ php artisan vendor:publish --tag=ivxapi-config

在配置文件中,所有 API 端点都是可访问的,例如,您需要生成发票 PDF

config(invoicexpress.enpoints.invoice.generate_pdf);

所有端点都是通用的,如:'api/pdf/{invoice-id}.xml',因此有一个辅助函数用于将通用端点替换为实际值

endpoint_replace(['the-real-value'], config(invoicexpress.enpoints.invoice.generate_pdf));

第一个参数必须是数组,并且需要替换的端点中的项的数量必须与要替换的项匹配。如果不匹配,将引发异常并抛出致命错误。

1.2 - 迁移

$ php artisan vendor:publish --tag=ivxapi-migrations
$ php artisan migrate

2 - 配置

将您的 API 密钥和账户名称添加到 .env 文件中


INVOICEXPRESS_API_KEY=
INVOICEXPRESS_ACCOUNT_NAME=


这些将被配置文件读取

....

'api_key'      => env('INVOICEXPRESS_API_KEY'),
'account_name' => env('INVOICEXPRESS_ACCOUNT_NAME'),

....

如果您不想将 API 密钥放在 .env 文件中,或者更喜欢在每次请求时获取它,您可以调用 getAPIKey() 方法。这样,您可以频繁更改账户中的 API 密钥,而无需更新应用程序。

在配置文件 invoicexpress 中,有两个空字段 ['username', 'password'],因此您可以将其放在那里,如果需要的话。

$client = new InvoiceXpressAPI();
$api_key = $client->getAPIKey('my-username', 'my-password');
....
//later in the query
....
$client->setQuery(['api_key' => $api_key]);
....

3 - 使用

请查看操作的参数说明。

见: https://invoicexpress.com/api/overview

有 2 个类用于处理 API

3.1 - Eloquent 模型

它有一个自定义函数,用于检索所有客户并将它们放入数据库中。

您可以为定期检索它们创建一个 cron 作业。

//Accepts a flag (true or false[default])
InvoiceXpressClients::getAllClientsFromAPI(true);

如果传递 true 标志,则函数将客户插入到数据库中。 False 或无,返回包含所有客户的数组。

如果客户已存在,则更新值。

3.1.1 - 与 Laravel::Auth() 的一对一关系

如果您希望 InvoiceXpress 与您的应用程序用户之间建立关系,请执行以下操作

$ php artisan vendor:publish --tag=ivxapi-migrateauth
$ php artisan migrate

在您的用户模型中添加以下方法

class User extends Model
{
.......

//Get the InvoiceXpress Client record associated with the user.

public function invoicexpress()
{
	return $this->hasOne('InvoiceXpressClients');
}

现在您有一对一关系。现在您只需将 user_id 插入到 InvoiceXpress 表中。

3.2 - 与 API 交互

use rpsimao\InvoiceXpressAPI\Service\InvoiceXpressAPI;

//Making a GET REQUEST

$client = new InvoiceXpressAPI();
$client->setMethod('GET');
$client->setUrl(config('invoicexpress.my_url'));
$client->setEndpoint(config('invoicexpress.endpoints.clients.list_all'));
$client->setQuery(['api_key' => config('invoicexpress.api_key')]);

$response = $client->talkToAPI();

.....



// Another GET Request to generate a PDF for an invoice

$client = new InvoiceXpressAPI();
$client->setMethod('get');
$client->setUrl(config('invoicexpress.my_url'));
$client->setEndpoint(
    endpoint_replace(['12759480'], config('invoicexpress.endpoints.invoices.generate_pdf'))
);
$client->setQuery([
        'api_key' => config('invoicexpress.api_key'),
        'invoice-id' => '12759480',
        'second_copy' => true
    ]);
$response = $client->talkToAPI();



//Making a POST REQUEST
// Creating a new Client

client = new InvoiceXpressAPI();
$client->setMethod('post');
$client->setUrl(config('invoicexpress.my_url'));
$client->setEndpoint( config('invoicexpress.endpoints.clients.create'));
$client->setQuery([
        'api_key' => config('invoicexpress.api_key'),
        'client' => [
        	'name' => 'My name',
        	'code' => 'My Client Code',
        	'email' => 'client@email.com'
        	//.... insert more values ....
        ]
    ]);
$response = $client->talkToAPI();


//Do whatever you need with the response

//Making a PUT REQUEST

$client = new InvoiceXpressAPI();
$client->setMethod('put');
$client->setUrl(config('invoicexpress.my_url'));
$client->setEndpoint(endpoint_replace(['123456789'], config('invoicexpress.endpoints.clients.update')));
$client->setQuery([
	'api_key' => config('invoicexpress.api_key'),
	'client-id' => '123456789',
	'client' => [
		'name' => 'My awesome Client',
		'code' => '123',
		'phone' =>  999888777
		//.... insert more values ....
		]
	]);
$response = $client->talkToAPI();


//Do whatever you need with the response

4 - 测试

目前有 4 个测试可用。

  1. GET 请求以检索所有客户
  2. PUT 请求以更新客户信息
  3. GET 请求以检索您的 API 密钥
  4. GET 请求以生成发票 PDF

为了使它们工作,您必须填写自己的凭据/数据

class GetTest extends TestCase {

// Use your own credentials|data to run the tests

	protected $url          = '';
	protected $api_key      = '';
	protected $username     = '';
	protected $password     = '';
	protected $client_id    = '';
	protected $client_name  = '';
	protected $client_code  = '';
	protected $client_phone = '';
	protected $invoice      = '';

.......

然后您可以运行测试

$ cd your-laravel-project-folder
$ vendor/bin/phpunit vendor/rpsimao/invoicexpress-api

如果一切顺利,您应该会收到

OK (4 tests, 4 assertions)

5 - 消息

默认情况下,所有错误/成功消息都返回 XML 格式。如果您希望更改为 JSON,只需添加 setMsgFormat() 方法并传递 JSON 标志

.....
$client = new InvoiceXpressAPI();
$client->setMsgFormat('json');
......

5.1 - 错误消息

api_codeapi_msg 是 InvoiceXpress API 返回的实际消息,其他只是用于调试。

调试标签仅在 .env 文件中设置为 APP_DEBUG=true 时出现

这是错误消息的返回方式

XML

<?xml version="1.0"?>
<response>
	<api_code>500</api_code>
	<api_msg>Server error: `GET https://mycompany.app.invoicexpress.com/api/pdf/1234567.xml?api_key=11111abc2222def33333&amp;invoice-id=1234567` resulted in a `500 Internal Server Error` response: An error occured on the server. We have been notified.</api_msg>
	<file>/Code/testapi/vendor/rpsimao/invoicexpress-api/src/Service/InvoiceXpressAPI.php</file>
	<line>408</line>
	<message>simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '&amp;lt;' not found</message>
</response>

JSON

{
"api_code":"500",
"api_msg":"Server error: `GET https:\/\/mycompany.app.invoicexpress.com\/api\/pdf\/1234567.xml?api_key=11111abc2222def33333&invoice-id=1234567` resulted in a `500 Internal Server Error` response:\nAn error occured on the server. We have been notified.\n\n",
"file":"\/Code\/testapi\/vendor\/rpsimao\/invoicexpress-api\/src\/Service\/InvoiceXpressAPI.php",
"line":385,
"message":"simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '&lt;' not found"
} 

5.2 - 成功消息

这是成功消息的返回方式

XML

<?xml version="1.0"?>
<response>
	<api_code>200</api_code>
	<api_msg>OK</api_msg>
	<api_values><pdfUrl>https://invoicexpress-downloads.s3.amazonaws.com/store_00000_Factura-0000-a.pdf?AWSAccessKeyId=AAKKAAKKK&amp;Expires=1501762080&amp;Signature=vmePXICWhUBRLygwVO6y2Lx6x4M%3D&amp;response-content-disposition=attachment%3B%20filename%3DFactura-0000-a.pdf&amp;response-content-type=application%2Fpdf</pdfUrl></api_values>
</response>

JSON

{
  "response": {
    "api_code": "200",
    "api_msg": "OK",
    "api_values": { "pdfUrl": "https://invoicexpress-downloads.s3.amazonaws.com/store_00000_Factura-0000-a.pdf?AWSAccessKeyId= AAKKAAKKK&Expires=1501762080&Signature=vmePXICWhUBRLygwVO6y2Lx6x4M%3D&response-content-disposition=attachment%3B%20filename%3DFactura-0000-a.pdf&response-content-type=application%2Fpdf" }
  }
}