Commit 233d8414 authored by hangjun83's avatar hangjun83

财务开票模块更新

parent 8ce2673e
<?php
namespace App\Console\Commands;
use App\Finance\Repositories\Contracts\InvoiceRecordRepository;
use App\Finance\Repositories\Eloquent\InvoiceRecordRepositoryEloquent;
use App\Finance\Services\InvoiceService;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
class InvoiceJobCommand extends Command
{
use ConfirmableTrait;
/**
* 命令行的名称及用法。
*
* @var string
*/
protected $signature = 'invoice:job
{--action_type= : 任务操作类型}
{--params= : 任务参数}';
/**
* 命令行的概述。
*
* @var string
*/
protected $description = '财务开票任务命令行';
/**
* 创建新的命令实例。
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 运行命令。
* @throws \Exception
*/
public function handle()
{
if (! $this->confirmToProceed()) {
return 1;
}
if($this->hasArgument('help')){
$this->help();
}else{
$action_type = $this->option('action_type');
$params = $this->option('params');
if(empty($action_type)){
$this->error('缺少命令参数,请输入具体的参数命令.如需帮助请输入 --help');
exit;
}
//$service = app(InvoiceService::class);
$service = (new InvoiceService(app(InvoiceRecordRepositoryEloquent::class)));
switch($action_type){
case 'registerPlatform' :
$service->registerPlatform();
break;
case 'getQiyeInvoiceInfo' :
$service->getQiyeInvoiceInfo();
break;
case 'applyInvoice' :
$service->applyInvoice([
'invoice_platform' => 'rhawn',
'invoice_type' => 'blue',
'invoice_category' => '1',
'invoice_platform_id' => '1',
'invoice_creater_by' => '测试',
'invoice_items' => [
[
'item_id' => '1',
'item_price' => '100',
'item_nums' => '1'
]
],
'invoice_money' => '100.8',
'invoice_customer' => [
'cust_name' => '测试名称',
'cust_code' => '13213113',
'cust_address' => '测试地址',
'cust_phone' => '021-12345678',
'cust_bankname' => '测试银行名称',
'cust_bankaccount' => '测试银行账号',
'cust_mobile' => '1388888888'
]
]);
break;
default:
}
}
}
public function help()
{
$helpStr = "参数帮助说明";
$this->comment($this->setHelp($helpStr)->getProcessedHelp());
$this->line("action_type: 具体动作参数\n\n initProductToExcel => 初始化批量商品 \n batchUpdateProduct => 批量更新商品\n\nparams : 操作需要传入的参数.非必填项");
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface InvoiceRecordRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface RhawnInvoiceItemsRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface RhawnInvoiceRepository extends RepositoryInterface
{
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Repositories\Eloquent;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Eloquent\BaseRepository as BaseRepositoryEloquent;
abstract class BaseRepository extends BaseRepositoryEloquent
{
protected function getConnectionName()
{
return app($this->model())->getConnectionName();
}
protected function getTableName()
{
return app($this->model())->getTable();
}
public function getConnection()
{
return DB::connection($this->getConnectionName());
}
}
<?php
namespace App\Finance\Repositories\Eloquent;
use App\Finance\Repositories\Contracts\InvoiceRecordRepository;
use App\Finance\Repositories\Models\InvoiceRecord;
class InvoiceRecordRepositoryEloquent extends BaseRepository implements InvoiceRecordRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return InvoiceRecord::class;
}
public function saveInvoice($saveParams)
{
$result = $this->updateOrCreate(['invoice_number' => $saveParams['invoice_number']],$saveParams);
return $result->toArray();
}
public function getInvoiceRecordByNumber($invoiceNumber)
{
$result = $this->getList(['invoice_number' => $invoiceNumber]);
return $result;
}
public function getList($where = [], $offset = 0, $limit = 100)
{
$query = $this;
if(!empty($where)){
foreach($where as $whereKey => $whereValue){
$query = $query->where($whereKey,$whereValue);
}
}
$result = $query->offset($offset)->limit($limit)->get()->toArray();
return $result;
}
}
<?php
namespace App\Finance\Repositories\Eloquent;
use App\Finance\Repositories\Contracts\RhawnInvoiceItemsRepository;
use App\Finance\Repositories\Models\RhawnInvoiceItems;
/**
* Class UserRepositoryEloquent.
*/
class RhawnInvoiceItemsRepositoryEloquent extends BaseRepository implements RhawnInvoiceItemsRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnInvoiceItems::class;
}
public function getInvoiceItemsByIdAndItemId($id, $itemId)
{
$invoiceItemInfo = null;
$invoiceItemInfo = $this->join('dpdetail', 'dpdetail.dpd_id', 'soidetail.dpd_id')
->join('soitems', 'soitems.si_id', 'dpdetail.si_id')
->join('products', 'products.p_id', 'soitems.p_id')
->whereIn('soidetail.soid_id', $itemId)
->where('soidetail.soi_id', $id)
->select(
'soidetail.soi_id','soidetail.soid_id', 'soidetail.soid_amount', 'dpdetail.dpd_num',
'products.p_code', 'products.p_cn_name', 'products.p_pack', 'products.p_pack_unit'
)->get()->toArray();
return $invoiceItemInfo;
}
}
<?php
namespace App\Finance\Repositories\Eloquent;
use App\Finance\Repositories\Contracts\RhawnInvoiceRepository;
use App\Finance\Repositories\Models\RhawnInvoice;
/**
* Class UserRepositoryEloquent.
*/
class RhawnInvoiceRepositoryEloquent extends BaseRepository implements RhawnInvoiceRepository
{
protected $fieldSearchable = [
];
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return RhawnInvoice::class;
}
public function getInvoiceById($id)
{
$invoice = $this->where('soi_id',$id)->get()->toArray();
if($invoice){
return $invoice;
}
return null;
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Repositories\Models;
use App\Repositories\Models\Model;
class InvoiceRecord extends Model
{
// 销售订单
protected $table = 'finance_invoice_record';
protected $connection = 'mysql';
protected $primaryKey = 'id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'invoice_number', 'invoice_real_number', 'invoice_type', 'invoice_status', 'invoice_money', 'invoice_platform', 'platform_invoice_id',
'invoice_creater_by', 'invoice_category', 'invoice_items', 'invoice_customer', 'invoice_real_date', 'invoice_pdf_url', 'created_at', 'updated_at'
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
}
\ No newline at end of file
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Repositories\Models;
use App\Repositories\Models\Model;
class RhawnInvoice extends Model
{
// 销售订单
protected $table = 'soinvoice';
protected $connection = 'rhawn_mysql';
protected $primaryKey = 'soi_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
/**
* update时不做自动更新时间操作
* @return null
*/
public function getUpdatedAtColumn()
{
return null;
}
public function getCreatedAtColumn()
{
return null;
}
}
\ No newline at end of file
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Repositories\Models;
use App\Repositories\Models\Model;
class RhawnInvoiceItems extends Model
{
// 销售订单
protected $table = 'soidetail';
protected $connection = 'rhawn_mysql';
protected $primaryKey = 'soid_id';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
/**
* update时不做自动更新时间操作
* @return null
*/
public function getUpdatedAtColumn()
{
return null;
}
public function getCreatedAtColumn()
{
return null;
}
}
\ No newline at end of file
<?php
namespace App\Finance\Services\Api;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\ThirdPlatform\PlatformAbstractService;
use App\Support\Facades\SimpleLogs;
use App\Support\Traits\HttpClientHelpers;
class BaiwangApiService extends PlatformAbstractService
{
use HttpClientHelpers;
public function __construct(ThirdApiPlatformRepository $thirdApiPlatformRepository)
{
parent::__construct($thirdApiPlatformRepository);
$this->setPlatformName('baiwang_invoice');
$this->getPlatformInfo();
}
/**
* 查询企业唯一标识
*/
public function queryQiyeUniqueSign($platform)
{
try{
if($this->checkPlatformStatus()){
$qiyeParams = [
'nsrmc' => $this->platformInfo['platform_params'][$platform]['nsrmc'],
'nsrsbh' => $this->platformInfo['platform_params'][$platform]['nsrsbh']
];
$response = $this->sendPost($this->getPlatformApiUrl().'/cloud/queryUniqueSign',$qiyeParams);
return $this->response($response);
}
}catch(\Exception $exception){
return $this->exception($exception);
}
}
public function queryOrder($params = [])
{
try{
if($this->checkPlatformStatus()){
$queryParams = [
'qyId' => '23020214385104316',
'ddlsh' => '15382750'
];
$response = $this->sendPost($this->getPlatformApiUrl().'/cloud/queryOrder',$queryParams);
return $this->response($response);
}
}catch(\Exception $exception){
return $this->exception($exception);
}
}
/**
* 开票申请(蓝字&红字)
* @param $params
* @return mixed|void
*/
public function applyElecInvoice($params)
{
try{
if($this->checkPlatformStatus()){
$requestParams = $params;
$response = $this->sendPost($this->getPlatformApiUrl().'/cloud/applyElecInvoice',$requestParams);
$token = $this->response($response);
return $token['data'];
}
}catch(\Throwable $exception){
return $this->exception($exception);
}
}
/**
* 蓝字发票作废(发票开具后开票日期在当月才能作废,跨月需要红冲。)
* @param $params
* @return mixed|void
*/
public function cancelElecInvoice($params)
{
try{
if($this->checkPlatformStatus()){
$tokenParams = [
'accessId' => $this->platformInfo['platform_params']['prod_accessId'],
'accessSecret' => $this->platformInfo['platform_params']['prod_accessSecret']
];
$response = $this->getPostClient($this->getPlatformApiUrl().'/openApi/v1/token',$tokenParams);
$token = $this->apiResponse($response);
return $token['data'];
}
}catch(\Exception $exception){
return $this->exception($exception);
}
}
/**
* 红字发票撤销
* @param $params
* @return mixed|void
*/
public function cancelElecRedInvoice($params)
{
try{
if($this->checkPlatformStatus()){
$tokenParams = [
'accessId' => $this->platformInfo['platform_params']['prod_accessId'],
'accessSecret' => $this->platformInfo['platform_params']['prod_accessSecret']
];
$response = $this->getPostClient($this->getPlatformApiUrl().'/openApi/v1/token',$tokenParams);
$token = $this->apiResponse($response);
return $token['data'];
}
}catch(\Exception $exception){
return $this->exception($exception);
}
}
/**
* 红字发票确认单状态查询
* @param $params
* @return mixed|void
*/
public function queryRedInvoiceConfirmState($params)
{
try{
if($this->checkPlatformStatus()){
$tokenParams = [
'accessId' => $this->platformInfo['platform_params']['prod_accessId'],
'accessSecret' => $this->platformInfo['platform_params']['prod_accessSecret']
];
$response = $this->getPostClient($this->getPlatformApiUrl().'/openApi/v1/token',$tokenParams);
$token = $this->apiResponse($response);
return $token['data'];
}
}catch(\Exception $exception){
return $this->exception($exception);
}
}
/**
* 发票下载(支持单张发票pdf地址查询。)
* @param $params
* @return mixed|void
*/
public function invoiceDownload($params)
{
try{
if($this->checkPlatformStatus()){
$tokenParams = [
'accessId' => $this->platformInfo['platform_params']['prod_accessId'],
'accessSecret' => $this->platformInfo['platform_params']['prod_accessSecret']
];
$response = $this->getPostClient($this->getPlatformApiUrl().'/openApi/v1/token',$tokenParams);
$token = $this->apiResponse($response);
return $token['data'];
}
}catch(\Exception $exception){
return $this->exception($exception);
}
}
private function exception($exception)
{
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':'.__FUNCTION__.' exception => ');
return false;
}
private function getPlatformApiUrl()
{
/*if(env('API_DEBUG')){
return $this->platformInfo['platform_params']['test_url'];
}*/
return $this->platformInfo['platform_url'];
}
public function response($response)
{
$response = json_decode($response,true);
if($response && $response['code'] == 0){
return $response['data'];
}
return false;
}
public function sendPost($uri, $paramsBody, $header = [])
{
$options = [];
$options['headers'] = [
'Accept' => 'application/json;charset=UTF-8',
'Content-Type'=> 'application/json;charset=UTF-8',
];
$options['body'] = $this->requestParamsEncode($paramsBody);
list($url,$method) = explode($this->platformInfo['platform_url'],$uri);
// auth签名
$header = array_merge($header,$this->authHeaders($method));
if(!is_null($header)){
$options['headers'] = array_merge($options['headers'],$header);
}
SimpleLogs::writeLog($paramsBody, __CLASS__.':'.$method.' 接口请求参数报文 => ');
return $this->clientRequest('post', $uri, $options);
}
/**
* 权限auth签名
* @param $path
* @return string[]
*/
private function authHeaders($path)
{
$key = $this->platformInfo['platform_params']['key'];
$sercret = $this->platformInfo['platform_params']['secret'];
$serverName = "/bwdpzx/agentinvoiceservice-cloud/agentiscloud";
$date = gmdate("D, d M Y H:i:s")." GMT";
$host = "api.baiwangjs.com";
$nonce = $this->uuid();
$ua = "PHP ".PHP_VERSION." 64 bit, sdk-ver=1.0.0";
$sign_str = "POST ".$serverName.$path." HTTP/1.1\n".
"date: ".$date."\n".
"host: ".$host."\n".
"x-htjs-nonce: ".$nonce."\n".
"x-htjs-ua: ".$ua;
$signature = base64_encode(hash_hmac('sha256', $sign_str, $sercret, true));
return [
'date' => $date,
'host' => $host,
'x-htjs-nonce' => $nonce,
'x-htjs-ua' => $ua,
'Authorization' => 'hmac username="'.$key.'", algorithm="hmac-sha256", headers="request-line date host x-htjs-nonce x-htjs-ua", signature="'.$signature.'"'
];
}
private function uuid()
{
$chars = md5(uniqid(mt_rand(), true));
$uuid = substr ( $chars, 0, 8 ) . '-'
. substr ( $chars, 8, 4 ) . '-'
. substr ( $chars, 12, 4 ) . '-'
. substr ( $chars, 16, 4 ) . '-'
. substr ( $chars, 20, 12 );
return $uuid ;
}
/**
* 对参数进行base64加密
* @param $params
* @return string
*/
public function requestParamsEncode($params)
{
$encodeParams = $params;
if(is_array($encodeParams)){
/*foreach($encodeParams as $key => $params){
$encodeParams[$key] = base64_encode($params);
}*/
$encodeParams = base64_encode(json_encode($encodeParams));
return $encodeParams;
}
return base64_encode($encodeParams);
}
}
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Finance\Services;
use App\Finance\Repositories\Contracts\InvoiceRecordRepository;
use App\Finance\Repositories\Eloquent\RhawnInvoiceItemsRepositoryEloquent;
use App\Finance\Repositories\Eloquent\RhawnInvoiceRepositoryEloquent;
use App\Finance\Services\Api\BaiwangApiService;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Services\ThirdPlatform\PlatformBaseService;
use App\Support\Facades\SimpleLogs;
class InvoiceService
{
public function __construct(InvoiceRecordRepository $invoiceRecordRepository)
{
$this->apiService = (new BaiwangApiService(app(ThirdApiPlatformRepository::class)));
$this->rhawnInvoiceRepository = app(RhawnInvoiceRepositoryEloquent::class);
$this->rhawnInvoiceItemsRepository = app(RhawnInvoiceItemsRepositoryEloquent::class);
$this->invoiceRecordRepository = $invoiceRecordRepository;
}
/**
* 注册平台信息
* @param string $platformName
*/
public function registerPlatform($platformName = 'baiwang')
{
if('baiwang' == $platformName){
$registerInfo = [
'platform_name' => 'baiwang_invoice',
'platform_title' => '百旺开票',
'platform_url' => 'http://api.baiwangjs.com/bwdpzx/agentinvoiceservice-cloud/agentiscloud',
'platform_desc' => '百旺开票对接',
'platform_params' => [
'test_url' => 'http://dlkp.kjgc.htjs.net/agentiscloud',
'rhawn' => [
'qyid' => '23020214385104316',
'nsrsbh' => '91310120MA1HMP790Y',
'nsrmc' => '上海易恩化学技术有限公司',
'nsrdz' => '上海市奉贤区银工路28号E幢',
'nsrdh' => '021-57461626',
'nsryh' => '交行上海南桥支行',
'nsrzh' => '310069309018800003232',
'key' => 'zsIY3Bzsm5esWKoU63VSOj6a',
'secret' => 'gNWFyeJslmrt7ce2O8eOs8NVzfoWIg',
'tax_rate' => '13'
],
'bhua' => [
'qyid' => '',
'nsrsbh' => '91310115312498004F',
'nsrmc' => '上海百舜生物科技有限公司',
'nsrdz' => '上海市奉贤区联合北路215号第3幢1242室 ',
'nsrdh' => '021-37581181',
'nsryh' => '交行上海大场支行',
'nsrzh' => '310065060018010017377',
'key' => '',
'secret' => '',
'tax_rate' => '13'
]
],
'platform_type' => 'third',
];
}
app(PlatformBaseService::class)->registerPlatform($registerInfo);
}
/**
* 申请开票(包括蓝字和红字)
* @param $invoiceParams
*/
public function applyInvoice($invoiceParams)
{
if(!isset($invoiceParams['invoice_platform']) || empty($invoiceParams['invoice_platform'])){
throw new \Exception('开票平台不存在',502);
}
if(!in_array($invoiceParams['invoice_platform'],['rhawn','bhua'])){
throw new \Exception('开票平台不在允许范围内',502);
}
if(!isset($invoiceParams['invoice_type']) || empty($invoiceParams['invoice_type'])){
throw new \Exception('开票类型不存在',502);
}
if(!in_array($invoiceParams['invoice_type'],['blue','red'])){
throw new \Exception('开票类型错误',502);
}
if(!isset($invoiceParams['invoice_category'])){
throw new \Exception('开票种类不存在',502);
}
if(!in_array($invoiceParams['invoice_category'],['1','2'])){
throw new \Exception('开票种类错误',502);
}
if(!isset($invoiceParams['invoice_customer']) || empty($invoiceParams['invoice_customer'])){
throw new \Exception('购买方发票信息不存在',502);
}
//查询是否存在发票记录
$invoiceInfo = null;
switch($invoiceParams['invoice_platform']){
case 'rhawn' : $invoiceInfo = $this->rhawnInvoiceRepository->getInvoiceById($invoiceParams['invoice_platform_id']);
break;
}
if(!$invoiceInfo){
$errorMessage = $invoiceParams['invoice_platform'].' invoice_platform_id :'.$invoiceParams['invoice_platform_id'].' 没有找到相应的开票信息';
SimpleLogs::writeLog($errorMessage, __CLASS__.':'.__FUNCTION__, 'error');
throw new \Exception('没有找到相应的开票信息',502);
}
//对发票项进行检查
if(!empty($invoiceParams['invoice_items'])){
$itemIds = [];
$invoiceItemsParams = [];
foreach($invoiceParams['invoice_items'] as $item){
$invoiceItemsParams[$item['item_id']] = $item;
array_push($itemIds,$item['item_id']);
}
//查询产品是否存在
$invoiceItem = $this->rhawnInvoiceItemsRepository->getInvoiceItemsByIdAndItemId($invoiceParams['invoice_platform_id'],$itemIds);
if($invoiceItem){
foreach($invoiceItem as $item){
if(isset($invoiceItemsParams[$item['soid_id']])){
if($invoiceItemsParams[$item['soid_id']]['item_nums'] > $item['dpd_num']){
SimpleLogs::writeLog('item_id : '.$item['soid_id'].' 开票数量超出已发货数量', __CLASS__.':'.__FUNCTION__, 'error');
throw new \Exception('开票数量超出已发货数量',502);
}
}
}
}
}
$invoiceNumber = 'I';
$invoiceNumber .= $invoiceParams['invoice_platform'] == 'rhawn' ? 'R' : 'B';
$invoiceNumber .= $invoiceParams['invoice_type'] == 'blue' ? 'B' : 'R';
$invoiceNumber .= $invoiceParams['invoice_category'] . date('Ymd',time());
$platformInfo = $this->apiService->getPlatformInfo()['platform_params'][$invoiceParams['invoice_platform']];
//组装请求参数
$applyInvoiceParams = [];
$applyInvoiceParams['qyId'] = $platformInfo['qyid'];
$applyInvoiceParams['sksbh'] = $platformInfo['nsrsbh'];
$applyInvoiceParams['bmbBbh'] = '';
$applyInvoiceParams['ddlsh'] = $invoiceNumber;
$applyInvoiceParams['fplxdm'] = '0'.$invoiceParams['invoice_category'];
$applyInvoiceParams['kplx'] = $invoiceParams['invoice_type'] == 'blue' ? 0 : 1;
$applyInvoiceParams['tspz'] = '';
$applyInvoiceParams['zsfs'] = 0;
$applyInvoiceParams['qdbz'] = count($invoiceParams['invoice_items']) > 8 ? 1 : 0;
$applyInvoiceParams['xsfMc'] = $platformInfo['nsrmc']; // 销售方名称
$applyInvoiceParams['xsfNsrsbh'] = $platformInfo['nsrsbh']; //销售方纳税人识别号
$applyInvoiceParams['xsfDz'] = $platformInfo['nsrdz']; // 销售方地址
$applyInvoiceParams['xsfDh'] = $platformInfo['nsrdh']; // 销售方电话
$applyInvoiceParams['xsfYh'] = $platformInfo['nsryh']; // 销售方银行名称
$applyInvoiceParams['xsfZh'] = $platformInfo['nsrzh']; // 销售方银行账户
$applyInvoiceParams['gmfMc'] = $invoiceParams['invoice_customer']['cust_name']; // 购买方名称
$applyInvoiceParams['gmfNsrsbh'] = $invoiceParams['invoice_customer']['cust_code']; // 购买方纳税人识别号
$applyInvoiceParams['gmfDz'] = $invoiceParams['invoice_customer']['cust_address']; // 购买方地址
$applyInvoiceParams['gmfDh'] = $invoiceParams['invoice_customer']['cust_phone']; // 购买方电话
$applyInvoiceParams['gmfYh'] = $invoiceParams['invoice_customer']['cust_bankname']; // 购买方银行名称
$applyInvoiceParams['gmfZh'] = $invoiceParams['invoice_customer']['cust_bankaccount']; // 购买方银行账户
$applyInvoiceParams['gmfMobile'] = $invoiceParams['invoice_customer']['cust_mobile']; // 购买方银行账户
$applyInvoiceParams['gmfEmail'] = ''; // 购买方邮箱
$applyInvoiceParams['sqr'] = $invoiceParams['invoice_creater_by'];
$applyInvoiceParams['dlzh'] = $platformInfo['qyid'];
$applyInvoiceParams['sfwzzfp'] = 'N';
$applyInvoiceParams['zpFppzdm'] = $invoiceParams['invoice_category'] == 2 ? '1130' : '04';
//初始化非必填项
$applyInvoiceParams['jshj'] = '';
$applyInvoiceParams['hjje'] = '';
$applyInvoiceParams['hjse'] = '';
$applyInvoiceParams['bz'] = '';
$applyInvoiceParams['kce'] = '';
$applyInvoiceParams['sslkjly'] = '';
$applyInvoiceParams['detailParam'] = [];
//开票明细列
foreach($invoiceItem as $item){
$applyInvoiceItems = [];
$applyInvoiceItems['fphxz'] = 0;
$applyInvoiceItems['hsbz'] = 1; //默认含税
$applyInvoiceItems['spmc'] = $item['p_cn_name'];
$applyInvoiceItems['spbm'] = $item['p_code'];
$applyInvoiceItems['ggxh'] = $item['p_code'];
$applyInvoiceItems['dw'] = '';
$applyInvoiceItems['dj'] = '';
$applyInvoiceItems['sl'] = $invoiceItemsParams[$item['soid_id']]['item_nums'];
$applyInvoiceItems['je'] = bcmul($invoiceItemsParams[$item['soid_id']]['item_price'],1,2);
$applyInvoiceItems['se'] = '';
$applyInvoiceItems['slv'] = bcdiv($platformInfo['tax_rate'],100,3);
$applyInvoiceItems['lslbs'] = 0;
$applyInvoiceItems['yhzcbs'] = 0;
$applyInvoiceItems['zxbm'] = '';
$applyInvoiceItems['zzstsgl'] = '';
array_push($applyInvoiceParams['detailParam'],$applyInvoiceItems);
}
//请求接口之前记录开票信息
$invoiceParams = array_merge($invoiceParams,['invoice_number' => $invoiceNumber]);
$result = $this->saveInvoiceRecord($invoiceParams);
if($result){
//记录请求参数
$this->apiService->storePlatformDataEntries('invoice_apply_'.$result['invoice_number'],$applyInvoiceParams);
$response = $this->apiService->applyElecInvoice($applyInvoiceParams);
if($response){
$this->invoiceRecordRepository->saveInvoice([
'invoice_number' => $result['invoice_number'],
'invoice_status' => 0
]);
return true;
}else{
throw new \Exception('申请发票失败',502);
}
}
}
public function cancelBlueInvoice()
{
}
public function confirmRedInvoice()
{
}
public function cancelRedInvoice()
{
}
public function downloadInvioce($invoiceNumber)
{
}
public function getQiyeInvoiceInfo()
{
$info = $this->apiService->queryQiyeUniqueSign();
var_dump($info);
}
/**
* 保存开票记录
* @param $params
*/
public function saveInvoiceRecord($invoiceParams)
{
$saveParams = [];
try{
$invoiceInfo = $this->invoiceRecordRepository->getInvoiceRecordByNumber($invoiceParams['invoice_number']);
if(!$invoiceInfo){
$saveParams['invoice_number'] = $invoiceParams['invoice_number'];
$saveParams['invoice_type'] = $invoiceParams['invoice_type'] == 'blue' ? 1 : 2;
$saveParams['invoice_status'] = -1;
$saveParams['invoice_money'] = $invoiceParams['invoice_money'];
$saveParams['invoice_platform'] = $invoiceParams['invoice_platform'];
$saveParams['platform_invoice_id'] = $invoiceParams['invoice_platform_id'];
$saveParams['invoice_creater_by'] = $invoiceParams['invoice_creater_by'];
$saveParams['invoice_category'] = $invoiceParams['invoice_category'];
$saveParams['invoice_items'] = json_encode($invoiceParams['invoice_creater_by'],JSON_UNESCAPED_UNICODE);
$saveParams['invoice_customer'] = json_encode($invoiceParams['invoice_customer'],JSON_UNESCAPED_UNICODE);
}
$result = $this->invoiceRecordRepository->saveInvoice($saveParams);
if($result){
return $result;
}
}catch(\Throwable $exception){
SimpleLogs::writeLog($exception->getMessage(), __CLASS__.':'.__FUNCTION__, 'error');
return false;
}
}
}
<?php
namespace App\Http\Controllers\V1\Finance;
use App\Finance\Services\InvoiceService;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;
use App\Http\Controllers\V1\Controller;
use App\Support\Traits\Helpers;
class InvoiceController extends Controller
{
use Helpers;
public function __construct(InvoiceService $invoiceService)
{
$this->invoiceService = $invoiceService;
}
public function applyInvoice(Request $request)
{
$requestParams = $this->formatKeysfromArray($request->all(),'toUnderScore');
try{
$result = $this->invoiceService->applyInvoice($requestParams);
return Response::success($result,'发票申请成功');
}catch(\Throwable $exception){
return $this->returnErrorExecptionResponse($exception,$exception->getMessage());
}
}
public function baiwangInvoiceCallBack(Request $request)
{
}
}
......@@ -77,7 +77,8 @@ class AppServiceProvider extends ServiceProvider
\App\Console\Commands\ThirdPlatformJobCommand::class,
\App\Console\Commands\KafkaConsumerCommand::class,
\App\Console\Commands\TestJobCommand::class,
\App\Console\Commands\RhawnToolsJobCommand::class
\App\Console\Commands\RhawnToolsJobCommand::class,
\App\Console\Commands\InvoiceJobCommand::class
]);
}
......
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Contracts;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface UserRepository.
*/
interface ApiPermissionsRepository extends RepositoryInterface
{
}
<?php
namespace App\Repositories\Eloquent;
use App\Repositories\Contracts\ApiPermissionsRepository;
use App\Repositories\Criteria\RequestCriteria;
use App\Repositories\Models\ApiPermissions;
use Illuminate\Support\Facades\DB;
/**
* Class UserRepositoryEloquent.
*/
class ApiPermissionsRepositoryEloquent extends BaseRepository implements ApiPermissionsRepository
{
public function model()
{
return ApiPermissions::class;
}
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
public function existPermissionByPermissionName($permissionName)
{
$permission = $this->findWhere([
'permission_name' => $permissionName
])->first();
if($permission){
return $permission->toArray();
}
return null;
}
}
......@@ -39,7 +39,7 @@ class PlatformDataEntriesRepositoryEloquent extends BaseRepository implements Pl
$entries = [
'platform_id' => $platformId,
'data_key' => $key,
'data_values' => is_array($values) ? json_encode($values) : $values
'data_values' => is_array($values) ? json_encode($values,JSON_UNESCAPED_UNICODE) : $values
];
return $this->updateOrCreate([
'platform_id' => $platformId,
......
<?php
/*
* This file is part of the Jiannei/lumen-api-starter.
*
* (c) Jiannei <longjian.huang@foxmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Repositories\Models;
class ApiPermissions extends Model
{
protected $connection = 'mysql';
protected $table = 'api_permissions';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id', 'permission_name', 'permission_title', 'router_path', 'remark', 'created_by','updated_by'
];
}
<?php
namespace App\Services\ThirdPlatform;
use App\Repositories\Contracts\ThirdApiPlatformRepository;
use App\Support\Facades\SimpleLogs;
use Illuminate\Support\Facades\DB;
class PlatformBaseService extends PlatformAbstractService
{
use \App\Support\Traits\Helpers;
public function __construct(ThirdApiPlatformRepository $thirdApiPlatformRepository)
{
parent::__construct($thirdApiPlatformRepository);
}
/**
* 注册第三方api平台信息
* @param $registerParams
*/
public function registerPlatform($registerParams)
{
try{
DB::beginTransaction();
$thirdApiPlatformRepo = app(\App\Repositories\Eloquent\ThirdApiPlatformRepositoryEloquent::class);
$result = $thirdApiPlatformRepo->findWhere(['platform_name' => $registerParams['platform_name']])->toArray();
if(is_array($registerParams['platform_params'])){
$registerParams['platform_params'] = json_encode($registerParams['platform_params'],JSON_UNESCAPED_UNICODE);
}
if(!isset($registerParams['platform_icon']) || empty($registerParams['platform_icon'])){
$platform['platform_icon'] = '';
}
if(!$result){
$platform['platform_status'] = '1';
$platform['platform_token'] = $this->randomFromDevice(16);
$platform['created_at'] = date('Y-m-d H:i:s',time());
$platform['updated_at'] = date('Y-m-d H:i:s',time());
}
$thirdApiPlatformRepo->updateOrCreate(['platform_name' => $registerParams['platform_name']],array_merge($registerParams,$platform));
SimpleLogs::writeLog($platform, __CLASS__.':'.__FUNCTION__);
DB::commit();
return true;
}catch(\Exception $e){
SimpleLogs::writeLog($e->getMessage(), __CLASS__.':'.__FUNCTION__, 'error');
DB::rollback();
return false;
}
}
}
......@@ -2,8 +2,8 @@
namespace App\Support\Traits;
use App\Services\SysLogService;
use App\Support\Facades\SimpleLogs;
use GuzzleHttp\Middleware;
trait HttpClientHelpers
{
......@@ -83,6 +83,16 @@ trait HttpClientHelpers
$requestOptions = array_merge_recursive($requestOptions, $options);
$client = app(\GuzzleHttp\Client::class);
if($requestOptions['debug']){
$clientHandler = $client->getConfig('handler');
$tapMiddleware = Middleware::tap(function ($request) {
var_dump($request->getBody()->getContents());
});
$requestOptions = array_merge($requestOptions,['handler' => $tapMiddleware($clientHandler)]);
}
$response = $client->request($requestType,$uri,$requestOptions);
$responseContent = $response->getBody()->getContents();
......
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFinanceInvoiceRecordTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('finance_invoice_record', function (Blueprint $table) {
$table->id();
$table->string('invoice_number')->nullable(false)->comment('发票编号');
$table->string('invoice_real_number')->nullable()->comment('发票真实编号');
$table->integer('invoice_type')->nullable(false)->comment('发票类型 1:蓝字 2:红字');
$table->integer('invoice_status')->nullable(false)->comment('发票状态 0:已申请待确认 1:已确认 2:开票作废 3:红字撤销');
$table->decimal('invoice_money')->nullable(false)->comment('开票金额');
$table->string('invoice_platform')->nullable(false)->comment('订单所属平台: rhawn ,bhua');
$table->string('platform_invoice_id')->nullable(false)->comment('平台发票id');
$table->string('invoice_creater_by')->nullable(false)->comment('开票人');
$table->string('invoice_category')->nullable(false)->comment('开票种类 1:普票 2:专票');
$table->text('invoice_items')->nullable(false)->comment('发票开票项明细');
$table->text('invoice_customer')->nullable(false)->comment('发票购买方信息');
$table->string('invoice_real_date')->nullable()->comment('发票真实开票日期');
$table->string('invoice_pdf_url')->nullable()->comment('发票pdf下载地址');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('finance_invoices_record');
}
}
\ No newline at end of file
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$api->version('v1', function($api) {
$api->group(['namespace'=>'App\Http\Controllers\V1\Finance','middleware' => ['throttle:60,1']], function($api) {
$api->post('/finance/invoice/baiwang/apiCallBack', ['uses'=>'InvoiceController@baiwangInvoiceCallBack']);
});
$api->group(['namespace'=>'App\Http\Controllers\V1\Finance','middleware' => ['throttle:60,1','apiAuth'], 'providers' => 'jwt'], function($api) {
$api->post('/finance/invoice/applyInvoice', ['permission' => 'finance.applyInvoice', 'uses'=>'InvoiceController@applyInvoice']);
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment