新增腾讯im。

This commit is contained in:
wucongxing 2023-03-09 16:01:03 +08:00
parent e1a015e960
commit 0850d6e3f3
19 changed files with 1265 additions and 46 deletions

View File

@ -55,7 +55,7 @@ class CancelUnpayOrdersDelayDirectConsumer extends ConsumerMessage
return Result::DROP;// 销毁 return Result::DROP;// 销毁
} }
if ($order_inquiry['inquiry_refund_status'] != 0 && $order_inquiry['inquiry_refund_status'] != 5) { if (!in_array($order_inquiry['inquiry_refund_status'],[0,4,5])) {
// 问诊订单退款状态0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭) // 问诊订单退款状态0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭)
Log::getInstance()->error("队列执行失败原因:订单正在退款中"); Log::getInstance()->error("队列执行失败原因:订单正在退款中");
return Result::DROP;// 销毁 return Result::DROP;// 销毁
@ -67,10 +67,16 @@ class CancelUnpayOrdersDelayDirectConsumer extends ConsumerMessage
return Result::DROP;// 销毁 return Result::DROP;// 销毁
} }
// 检测订单删除状态
if ($order_inquiry['is_delete'] == 1) {
// 删除状态0:否 1:是)
Log::getInstance()->error("取消未支付订单:订单已被删除");
return Result::ACK;// 销毁
}
// 取消问诊订单 // 取消问诊订单
$data = array(); $data = array();
$data['inquiry_status'] = 7; $data['inquiry_status'] = 7;
$data['inquiry_refund_status'] = 2;
$data['inquiry_pay_status'] = 5; $data['inquiry_pay_status'] = 5;
$data['cancel_time'] = date("Y-m-d H:i:s",time()); $data['cancel_time'] = date("Y-m-d H:i:s",time());
$data['cancel_reason'] = 5; // 取消订单原因1:医生未接诊 2:主动取消 3:无可分配医生 4:客服取消 5:支付超时) $data['cancel_reason'] = 5; // 取消订单原因1:医生未接诊 2:主动取消 3:无可分配医生 4:客服取消 5:支付超时)

View File

@ -105,4 +105,39 @@ class InquiryController extends AbstractController
$data = $InquiryService->getPatientInquiryOrderInfo(); $data = $InquiryService->getPatientInquiryOrderInfo();
return $this->response->json($data); return $this->response->json($data);
} }
/**
* 取消患者问诊订单
* @return ResponseInterface
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function putCancelPatientInquiryOrder(): ResponseInterface
{
$InquiryService = new InquiryService();
$data = $InquiryService->putCancelPatientInquiryOrder();
return $this->response->json($data);
}
/**
* 删除问诊订单
* @return ResponseInterface
*/
public function deletePatientInquiryOrder(): ResponseInterface
{
$InquiryService = new InquiryService();
$data = $InquiryService->deletePatientInquiryOrder();
return $this->response->json($data);
}
/**
* 问诊订单取消支付
* @return ResponseInterface
*/
public function putPatientInquiryOrderCancelPay(): ResponseInterface
{
$InquiryService = new InquiryService();
$data = $InquiryService->putPatientInquiryOrderCancelPay();
return $this->response->json($data);
}
} }

View File

@ -11,6 +11,12 @@ use App\Request\UserRequest;
use App\Services\UserDoctorService; use App\Services\UserDoctorService;
use App\Services\UserService; use App\Services\UserService;
use App\Utils\Http; use App\Utils\Http;
use Extend\TencentIm\Account;
use Extend\TencentIm\Friend;
use Extend\TencentIm\Group;
use Extend\TencentIm\Message;
use Extend\TencentIm\MessageParams;
use Extend\TencentIm\Profile;
use Extend\Wechat\Wechat; use Extend\Wechat\Wechat;
use Extend\Wechat\WechatPay; use Extend\Wechat\WechatPay;
use Hyperf\Amqp\Producer; use Hyperf\Amqp\Producer;
@ -75,27 +81,22 @@ class UserController extends AbstractController
// 支付测试 // 支付测试
public function testpay(){ public function testpay(){
// $weChat = new Wechat(1);
//
// $wx_info_data = $weChat->codeToSession("0219AIFa1ROoUE0e4lIa1bO27I29AIF9");
// dump($wx_info_data);die;
// 发起支付 // 发起支付
$out_trade_no = $this->request->input('out_trade_no'); // $out_trade_no = $this->request->input('out_trade_no');
$generator = $this->container->get(IdGeneratorInterface::class); // $generator = $this->container->get(IdGeneratorInterface::class);
//
$WechatPay = new WechatPay(1); // $WechatPay = new WechatPay(1);
//
// 获取预支付交易会话标识 // // 获取预支付交易会话标识
$total = 0.01 * 100; // $total = 0.01 * 100;
$prepay = $WechatPay->getJsapiPrepayId($out_trade_no,$total,"omgU35DlE-rxTAGgcBjOuc4xdcX8"); // $prepay = $WechatPay->getJsapiPrepayId($out_trade_no,$total,"omgU35DlE-rxTAGgcBjOuc4xdcX8");
if (empty($prepay)){ // if (empty($prepay)){
return fail(HttpEnumCode::SERVER_ERROR, "订单创建失败"); // return fail(HttpEnumCode::SERVER_ERROR, "订单创建失败");
} // }
//
// 获取小程序支付配置 // // 获取小程序支付配置
$pay_config = $WechatPay->getAppletsPayConfig($prepay['prepay_id']); // $pay_config = $WechatPay->getAppletsPayConfig($prepay['prepay_id']);
return $this->response->json($pay_config); // return $this->response->json($pay_config);
// 发起退款 // 发起退款
// $WechatPay = new WechatPay(1); // $WechatPay = new WechatPay(1);
@ -117,5 +118,53 @@ class UserController extends AbstractController
// //
// $result = $WechatPay->refund($options); // $result = $WechatPay->refund($options);
// dump($result); // dump($result);
// 创建账号
$account = new Account();
$profile = new Profile();
$group = new Group();
$friend = new Friend();
$message = new Message();
// $result = $account->createAccount(1234567,'测试患者',"https://img.applets.igandanyiyuan.com/applet/doctor/avatar/03dc8df2-e7c0-4ad9-b87e-5133e40e0f76.jpg");
// 查询账号导入状态
// $result = $account->checkAccountStatus("123456");
// 设置账户资料
// $arg = array();
// $arg['Tag_Profile_IM_Gender'] = "Gender_Type_Male";
// $arg['Tag_Profile_IM_BirthDay'] = 19961007;
// $arg['Tag_Profile_Custom_Hname'] = "协和医院";
// $arg['Tag_Profile_Custom_Title'] = "主任医师";
// $result = $profile->setProfile("123456",$arg);
// 添加用户好友分组
// $result = $group->addUserGroup('123456');
// 获取用户好友分组
// $result = $group->getUserGroup('123456');
// 添加好友
// $result = $friend->addFriend("123456",'1234567',"快速问诊");
// 发送消息
$arg = array();
$arg['From_Account'] = "1234567"; // 发送方user_id 如系统发送,无需填写
$arg['To_Account'] = "123456"; // 接收方user_id
$arg['ForbidCallbackControl'] = ['ForbidBeforeSendMsgCallback'];
$arg['MsgBody'] = [
[
"MsgType" => "TIMTextElem",
"MsgContent" => [
"Text" => "测试消息",
],
]
];
$result = $message->sendMessage($arg);
dump($result);
} }
} }

View File

@ -9,12 +9,18 @@ use App\Request\UserDoctorRequest;
use App\Services\DoctorAuthService; use App\Services\DoctorAuthService;
use App\Services\DoctorInquiryService; use App\Services\DoctorInquiryService;
use App\Services\UserDoctorService; use App\Services\UserDoctorService;
use Extend\TencentIm\Account;
use Hyperf\Amqp\Producer; use Hyperf\Amqp\Producer;
use Hyperf\DbConnection\Db; use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext; use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface; use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
class UserDoctorController extends AbstractController class UserDoctorController extends AbstractController
{ {
@ -280,6 +286,13 @@ class UserDoctorController extends AbstractController
/** /**
* 获取医生名片 * 获取医生名片
* @return ResponseInterface * @return ResponseInterface
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/ */
public function getDoctorInfoCard(): ResponseInterface public function getDoctorInfoCard(): ResponseInterface
{ {
@ -287,4 +300,9 @@ class UserDoctorController extends AbstractController
$data = $UserDoctorService->getDoctorInfoCard(); $data = $UserDoctorService->getDoctorInfoCard();
return $this->response->json($data); return $this->response->json($data);
} }
// 获取医生问诊消息列表
public function getDoctorMessageList(){
}
} }

View File

@ -678,6 +678,157 @@ class InquiryService extends BaseService
return success($order_inquiry->toArray()); return success($order_inquiry->toArray());
} }
/**
* 取消患者问诊订单
* @return array
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function putCancelPatientInquiryOrder(): array
{
$user_info = $this->request->getAttribute("userInfo") ?? [];
$order_inquiry_id = $this->request->route('order_inquiry_id');
// 获取订单数据
$params = array();
$params['patient_id'] = $user_info['client_user_id'];
$params['order_inquiry_id'] = $order_inquiry_id;
$params['is_delete'] = 0;
$order_inquiry = OrderInquiry::getOne($params);
if (empty($order_inquiry)){
return fail();
}
// 检测订单状态
if (!in_array($order_inquiry['inquiry_status'],[1,2,3])) {
// 问诊订单状态1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消)
return fail(HttpEnumCode::HTTP_ERROR,"订单无法取消");
}
if (!in_array($order_inquiry['inquiry_refund_status'],[0,4,5])) {
// 问诊订单退款状态0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭)
return fail(HttpEnumCode::HTTP_ERROR,"订单正在退款中");
}
// 支付状态1:未支付 2:已支付 3:支付中 4:支付失败 5:支付超时 6:支付关闭 7:已撤销 8:转入退款)
Db::beginTransaction();
try {
// 修改问诊订单为取消
$data = array();
$data['inquiry_status'] = 7;
$data['cancel_time'] = date("Y-m-d H:i:s",time());
$data['cancel_reason'] = 2; // 取消订单原因1:医生未接诊 2:主动取消 3:无可分配医生 4:客服取消 5:支付超时)
$data['updated_at'] = date("Y-m-d H:i:s",time());
$params = array();
$params['order_inquiry_id'] = $order_inquiry['order_inquiry_id'];
OrderInquiry::edit($params,$data);
// 检测支付状态,判断是否需要退款处理
if ($order_inquiry['inquiry_pay_status'] == 2){
// 需退款
$this->inquiryRefund($order_inquiry['order_inquiry_id'],"取消问诊");
}
} catch (\Exception $e) {
Db::rollBack();
return fail(HttpEnumCode::HTTP_ERROR, $e->getMessage());
}
return success();
}
/**
* 删除问诊订单
* @return array
*/
public function deletePatientInquiryOrder(): array
{
$user_info = $this->request->getAttribute("userInfo") ?? [];
$order_inquiry_id = $this->request->route('order_inquiry_id');
// 获取订单数据
$params = array();
$params['patient_id'] = $user_info['client_user_id'];
$params['order_inquiry_id'] = $order_inquiry_id;
$params['is_delete'] = 0;
$order_inquiry = OrderInquiry::getOne($params);
if (empty($order_inquiry)){
return fail();
}
// 检测订单状态
if (!in_array($order_inquiry['inquiry_status'],[1,5])) {
// 问诊订单状态1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消)
return fail(HttpEnumCode::HTTP_ERROR,"订单无法删除");
}
if (!in_array($order_inquiry['inquiry_refund_status'],[0,4,5])) {
// 问诊订单退款状态0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭)
return fail(HttpEnumCode::HTTP_ERROR,"订单正在退款中");
}
// 修改订单删除状态
$data = array();
$data['is_delete'] = 1;
$params = array();
$params['order_inquiry_id'] = $order_inquiry['order_inquiry_id'];
OrderInquiry::edit($params,$data);
return success();
}
/**
* 问诊订单取消支付
* @return array
*/
public function putPatientInquiryOrderCancelPay(): array
{
$user_info = $this->request->getAttribute("userInfo") ?? [];
$order_inquiry_id = $this->request->route('order_inquiry_id');
// 获取订单数据
$params = array();
$params['patient_id'] = $user_info['client_user_id'];
$params['order_inquiry_id'] = $order_inquiry_id;
$params['is_delete'] = 0;
$order_inquiry = OrderInquiry::getOne($params);
if (empty($order_inquiry)){
return fail();
}
// 检测订单状态
if (!in_array($order_inquiry['inquiry_status'],[1])) {
// 问诊订单状态1:待支付 2:待分配 3:待接诊 4:已接诊 5:已完成 6:已结束 7:已取消)
return fail(HttpEnumCode::HTTP_ERROR,"订单无法删除");
}
if (!in_array($order_inquiry['inquiry_refund_status'],[0,4,5])) {
// 问诊订单退款状态0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭)
return fail(HttpEnumCode::HTTP_ERROR,"订单正在退款中");
}
// 修改订单删除状态
$data = array();
$data['inquiry_status'] = 7;
$data['cancel_time'] = date("Y-m-d H:i:s",time());
$data['cancel_reason'] = 2; // 取消订单原因1:医生未接诊 2:主动取消 3:无可分配医生 4:客服取消 5:支付超时)
$data['cancel_remarks'] = "未支付取消";
$data['updated_at'] = date("Y-m-d H:i:s",time());
$params = array();
$params['order_inquiry_id'] = $order_inquiry['order_inquiry_id'];
OrderInquiry::edit($params,$data);
return success();
}
/** /**
* 获取医生未接诊订单数量 * 获取医生未接诊订单数量
@ -797,7 +948,7 @@ class InquiryService extends BaseService
} }
// 检测订单退款状态 // 检测订单退款状态
if (in_array($order_inquiry['inquiry_refund_status'], [2, 3, 4, 5])) { if (in_array($order_inquiry['inquiry_refund_status'], [2, 3, 5])) {
// 问诊订单退款状态0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭) // 问诊订单退款状态0:无退款 1:申请退款 2:退款中 3:退款成功 4:拒绝退款 5:退款关闭)
throw new BusinessException("订单退款状态错误"); throw new BusinessException("订单退款状态错误");
} }

View File

@ -25,6 +25,7 @@ class Auth
"/area/county" => "get", // 获取区县信息 "/area/county" => "get", // 获取区县信息
"/callback/wxpay/inquiry/success" => "post", // 微信支付回调 "/callback/wxpay/inquiry/success" => "post", // 微信支付回调
"/callback/wxpay/inquiry/refund" => "post", // 微信退款回调 "/callback/wxpay/inquiry/refund" => "post", // 微信退款回调
"/callback/im" => "post", // im回调
"/testpay" => "get", // 测试 "/testpay" => "get", // 测试
]; ];
} }

View File

@ -18,12 +18,13 @@ class HttpRequest
/** /**
* 请求封装 * 请求封装
* post请求
* @param string $path * @param string $path
* @param array $option * @param array $option
* @return array * @return array
* @throws GuzzleException * @throws GuzzleException
*/ */
public function getRequest(string $path,array $option = []): array public function postRequest(string $path, array $option = []): array
{ {
$response = $this->client->post($path, $option); $response = $this->client->post($path, $option);

View File

@ -35,7 +35,8 @@
"hyperf/redis": "~3.0.0", "hyperf/redis": "~3.0.0",
"hyperf/snowflake": "^3.0", "hyperf/snowflake": "^3.0",
"hyperf/validation": "^3.0", "hyperf/validation": "^3.0",
"w7corp/easywechat": "^6.7" "w7corp/easywechat": "^6.7",
"ext-zlib": "*"
}, },
"require-dev": { "require-dev": {
"friendsofphp/php-cs-fixer": "^3.0", "friendsofphp/php-cs-fixer": "^3.0",

View File

@ -71,5 +71,6 @@ return [
'im' =>[ // 腾讯im 'im' =>[ // 腾讯im
"app_id" => "1400796919", "app_id" => "1400796919",
"secret" => "a5bcd8c583181cf004e9d91a47687d719d4b5d2a10ce33fbee95d587889447d8", "secret" => "a5bcd8c583181cf004e9d91a47687d719d4b5d2a10ce33fbee95d587889447d8",
"base_url" => "https://console.tim.qq.com/",
], ],
]; ];

View File

@ -23,7 +23,6 @@ use App\Controller\PatientCaseController;
use App\Controller\PatientCenterController; use App\Controller\PatientCenterController;
use App\Controller\PatientDoctorController; use App\Controller\PatientDoctorController;
use App\Controller\PatientFamilyController; use App\Controller\PatientFamilyController;
use App\Controller\PayController;
use App\Controller\SafeController; use App\Controller\SafeController;
use App\Controller\SystemController; use App\Controller\SystemController;
use App\Controller\UserController; use App\Controller\UserController;
@ -75,6 +74,9 @@ Router::addGroup('/doctor', function () {
// 获取患者问诊病例 // 获取患者问诊病例
Router::get('/case/{inquiry_case_id:\d+}', [InquiryController::class, 'getPatientInquiryCase']); Router::get('/case/{inquiry_case_id:\d+}', [InquiryController::class, 'getPatientInquiryCase']);
// 获取医生问诊消息列表
Router::get('/message', [UserDoctorController::class, 'getDoctorMessageList']);
}); });
//银行卡 //银行卡
@ -163,7 +165,6 @@ Router::addGroup('/doctor', function () {
// 获取医生名片 // 获取医生名片
Router::get('/card', [UserDoctorController::class, 'getDoctorInfoCard']); Router::get('/card', [UserDoctorController::class, 'getDoctorInfoCard']);
}); });
}); });
/** /**
@ -208,6 +209,15 @@ Router::addGroup('/patient', function () {
// 获取患者问诊订单详情 // 获取患者问诊订单详情
Router::get('/{order_inquiry_id:\d+}', [InquiryController::class, 'getPatientInquiryOrderInfo']); Router::get('/{order_inquiry_id:\d+}', [InquiryController::class, 'getPatientInquiryOrderInfo']);
// 取消患者问诊订单-1:待支付 2:待分配 3:待接诊
Router::put('/cancel/{order_inquiry_id:\d+}', [InquiryController::class, 'putCancelPatientInquiryOrder']);
// 删除问诊订单-1:待支付 5:已完成
Router::delete('/{order_inquiry_id:\d+}', [InquiryController::class, 'deletePatientInquiryOrder']);
// 问诊订单取消支付-1未支付
Router::put('/cancel-pay/{order_inquiry_id:\d+}', [InquiryController::class, 'putPatientInquiryOrderCancelPay']);
}); });
// 医生数据 // 医生数据
@ -405,30 +415,13 @@ Router::addGroup('/user', function () {
Router::put('/loginout', [UserController::class, 'putLoginout']); Router::put('/loginout', [UserController::class, 'putLoginout']);
}); });
// im
Router::addGroup('/im', function () {
// 修改用户头像
Router::put('/avatar', [UserController::class, 'putUserAvatar']);
});
Router::get('/testpay', [UserController::class, 'testpay']); Router::get('/testpay', [UserController::class, 'testpay']);
// 未开发接口 // 未开发接口
// 取消问诊-问诊订单-未接诊时
Router::post('/5', [CallBackController::class, 'imCallBack']);
// 删除问诊订单-问诊订单-订单完成
Router::post('/6', [CallBackController::class, 'imCallBack']);
// 取消支付-问诊订单-未支付
Router::post('/7', [CallBackController::class, 'imCallBack']);
// 获取药品订单列表-药品订单 // 获取药品订单列表-药品订单
Router::post('/8', [CallBackController::class, 'imCallBack']); Router::post('/8', [CallBackController::class, 'imCallBack']);

View File

@ -0,0 +1,81 @@
<?php
namespace Extend\TencentIm;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use App\Utils\HttpRequest;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Utils\ApplicationContext;
/**
* 账号
*/
class Account extends Base
{
private string $version = 'v4';
/**
* 创建单个账号
* @param string $user_id 用户id
* @param string $nick_name 用户昵称
* @param string $avatar 用户头像 URL
* @return array
* @throws GuzzleException
*/
public function createAccount(string $user_id,string $nick_name,string $avatar): array
{
try {
$options = [
"json"=> [
"UserID" => $user_id,
"Nick" => $nick_name,
"FaceUrl" => addAliyunOssWebsite($avatar),
]
];
$path = $this->config['base_url'] . $this->version . "/im_open_login_svc/account_import?" . $this->buildRequestParams();
return $this->postRequest($path,$options);
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
/**
* 查询账号导入状态-单条
* @param string $user_id
* @return bool
* @throws GuzzleException
*/
public function checkAccountStatus(string $user_id): bool
{
try {
$options = [
"json"=> [
"CheckItem" => [
[
"UserID" => $user_id
]
]
]
];
$path = $this->config['base_url'] . $this->version . "/im_open_login_svc/account_check?" . $this->buildRequestParams();
$result = $this->postRequest($path,$options);
if (empty($result['ResultItem'])){
throw new BusinessException("im返回值错误");
}
foreach ($result['ResultItem'] as $item){
if ($item['AccountStatus'] != "Imported"){
// 未导入
return false;
}
}
return true;
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
}

107
extend/TencentIm/Base.php Normal file
View File

@ -0,0 +1,107 @@
<?php
namespace Extend\TencentIm;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\HandlerStackFactory;
use Psr\Container\ContainerInterface;
class Base
{
protected array $config;// 系统配置
protected string $identifier = "administrator";// 管理员账户
public function __construct()
{
$this->config = config("im");
if (empty($this->config)) {
throw new BusinessException("系统配置错误", HttpEnumCode::SERVER_ERROR);
}
}
/**
* 获取用户签名
* @param string $user_id
* @return string
*/
protected function getUserSign(string $user_id = ""): string
{
try {
$TLSSigAPIv2 = new TLSSigAPIv2($this->config['app_id'], $this->config['secret']);
if (empty($user_id)){
$user_sign = $TLSSigAPIv2->genUserSig($this->identifier);
}else{
$user_sign = $TLSSigAPIv2->genUserSig($user_id);
}
if (empty($user_sign)) {
throw new BusinessException("获取im用户签名失败");
}
return $user_sign;
} catch (\Exception $e) {
throw new BusinessException($e->getMessage());
}
}
/**
* 组合请求参数
* @return string
*/
protected function buildRequestParams(): string
{
$result = array();
$result['sdkappid'] = $this->config['app_id'];
$result['identifier'] = $this->identifier;
$result['usersig'] = $this->getUserSign();
$result['random'] = mt_rand(0, 4294967295);
$result['contenttype'] = "json";
return http_build_query($result);
}
/**
* 封装请求
* @param string $path
* @param array $option
* @return array
* @throws GuzzleException
*/
protected function postRequest(string $path, array $option = []): array
{
$factory = new HandlerStackFactory();
$stack = $factory->create();
$client = make(Client::class, [
'config' => [
'handler' => $stack,
'timeout' => 10,
'verify' => false,
],
]);
$response = $client->post($path, $option);
if ($response->getStatusCode() != '200'){
// 请求失败
throw new BusinessException($response->getBody()->getContents());
}
$content = json_decode($response->getBody(),true);
dump($content);
if (empty($content)){
throw new BusinessException("请求失败");
}
if ($content['ErrorCode'] != 0){
throw new BusinessException($content['ErrorInfo']);
}
return $content;
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace Extend\TencentIm;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use GuzzleHttp\Exception\GuzzleException;
/**
* 好友
*/
class Friend extends Base
{
private string $version = 'v4';
/**
* 添加好友
* 单个好友添加
* @param string $user_id
* @param string $friend_user_id
* @param string $group_name
* @return array
* @throws GuzzleException
*/
public function addFriend(string $user_id,string $friend_user_id,string $group_name): array
{
try {
$options = [
"json"=> [
"From_Account" => $user_id,
"AddFriendItem" => [
[
"To_Account" => $friend_user_id,
"AddSource" => "AddSource_Type_Applets", // 加好友来源字段
]
],
"ForceAddFlags" => 1, // 管理员强制加好友标记1表示强制加好友0表示常规加好友方式
]
];
$path = $this->config['base_url'] . $this->version . "/profile/portrait_set?" . $this->buildRequestParams();
$result = $this->postRequest($path,$options);
if (isset($result['Fail_Account'])){
// 返回处理失败的用户列表,仅当存在失败用户时才返回该字段
throw new BusinessException("添加好友异常,未返回结果:" . json_encode($result['ResultItem'],JSON_UNESCAPED_UNICODE));
}
return $result;
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace Extend\TencentIm;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use GuzzleHttp\Exception\GuzzleException;
/**
* 分组
*/
class Group extends Base
{
private string $version = 'v4';
/**
* 添加用户好友分组
* @param string $user_id
* @param array $group_name 分组名称
* @return array
* @throws GuzzleException
*/
public function addUserGroup(string $user_id,array $group_name = ["专家问诊","快速问诊","快速问诊","问诊购药"]): array
{
try {
$options = [
"json"=> [
"From_Account" => $user_id,
"GroupName" => $group_name,
]
];
$path = $this->config['base_url'] . $this->version . "/sns/group_add?" . $this->buildRequestParams();
return $this->postRequest($path,$options);
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
/**
* 获取用户好友分组
* @param string $user_id
* @return array
* @throws GuzzleException
*/
public function getUserGroup(string $user_id): array
{
try {
$options = [
"json"=> [
"From_Account" => $user_id,
"NeedFriend" => "Need_Friend_Type_Yes",
]
];
$path = $this->config['base_url'] . $this->version . "/sns/group_get?" . $this->buildRequestParams();
$result = $this->postRequest($path,$options);
return $result['ResultItem'];
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
/**
* 删除用户好友分组
* @param string $user_id
* @param array $group_name 分组名称
* @return array
* @throws GuzzleException
*/
public function deleteUserGroup(string $user_id,array $group_name = ["专家问诊","快速问诊","快速问诊","问诊购药"]): array
{
try {
$options = [
"json"=> [
"From_Account" => $user_id,
"NeedFriend" => "Need_Friend_Type_Yes",
]
];
$path = $this->config['base_url'] . $this->version . "/sns/group_get?" . $this->buildRequestParams();
$result = $this->postRequest($path,$options);
return $result['ResultItem'];
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace Extend\TencentIm;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
class MyStruct{
}
/**
* 消息
*/
class Message extends Base
{
private string $version = 'v4';
// 发送消息参数
private array $arg;
public function __construct()
{
parent::__construct();
$this->arg = [
// 把消息同步到 From_Account 在线终端和漫游上;消息不同步至 From_Account
'SyncOtherMachine' => 1,
//消息随机数32位无符号整数
'MsgRandom' => random_int(1, 4292967295),
/**
* 消息回调禁止开关,只对本条消息有效
* ForbidBeforeSendMsgCallback 表示禁止发消息前回调
* ForbidAfterSendMsgCallback 表示禁止发消息后回调
*/
'ForbidCallbackControl' => ['ForbidBeforeSendMsgCallback','ForbidAfterSendMsgCallback'],
/**
* 消息发送控制选项,是一个 String 数组,只对本条消息有效。
* "NoUnread"表示该条消息不计入未读数。
* "NoLastMsg"表示该条消息不更新会话列表。
* "WithMuteNotifications"表示该条消息的接收方对发送方设置的免打扰选项生效(默认不生效)
*/
'SendMsgControl' => ['NoUnread','NoLastMsg','WithMuteNotifications'],
'MsgBody' => [
/**
* 消息对象类型
* TIMTextElem文本消息
* TIMLocationElem位置消息
* TIMFaceElem表情消息
* TIMCustomElem自定义消息
* TIMSoundElem语音消息
* TIMImageElem图像消息
* TIMFileElem文件消息
* TIMVideoFileElem视频消息
*/
'MsgType' => "TIMTextElem",
// 消息内容,对于每种 MsgType 用不同的 MsgContent 格式
'MsgContent' => null,
],
/**
* 消息自定义数据(云端保存,会发送到对端,程序卸载重装后还能拉取到)
* 如聊天类型。json格式
* order_inquiry_id
* inquiry_type
*/
'CloudCustomData' => "",
];
}
public function sendMessage(array $arg){
try {
// 合并发送参数
$arg = array_merge($this->arg,$arg);
$options = [
"json"=> $arg
];
dump($options);
$path = $this->config['base_url'] . $this->version . "/openim/sendmsg?" . $this->buildRequestParams();
return $this->postRequest($path,$options);
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace Extend\TencentIm;
use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use GuzzleHttp\Exception\GuzzleException;
/**
* 账户资料
*/
class Profile extends Base
{
private string $version = 'v4';
/**
* 设置账户资料
* @param string $user_id 用户id
* @param array $arg
* 内置字段https://cloud.tencent.com/document/product/269/1500#.E6.A0.87.E9.85.8D.E8.B5.84.E6.96.99.E5.AD.97.E6.AE.B5
* 自定义字段:控制台->应用配置>功能配置->新增
* Tag_Profile_Custom_Hname:医院名称
* Tag_Profile_Custom_Title:医生职称
* @return array
* @throws GuzzleException
*/
public function setProfile(string $user_id,array $arg): array
{
try {
$profileItem = [];
foreach ($arg as $key => $value){
$profileItem[] = [
'Tag' => $key,
'Value' => $value
];
}
$options = [
"json"=> [
"From_Account" => $user_id,
"ProfileItem" => $profileItem,
]
];
$path = $this->config['base_url'] . $this->version . "/profile/portrait_set?" . $this->buildRequestParams();
return $this->postRequest($path,$options);
}catch (\Exception $e) {
throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR);
}
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Extend\TencentIm;
/**
* 会话
*/
class RecentContact extends Base
{
// 分页拉取会话列表
public function getRecentContactPage(){
}
}

View File

@ -0,0 +1,470 @@
<?php
namespace Extend\TencentIm;
class TLSSigAPIv2
{
private $key = false;
private $sdkappid = 0;
/**
*【功能说明】用于签发 TRTC IM 服务中必须要使用的 UserSig 鉴权票据
*
*【参数说明】
* @param string userid - 用户id限制长度为32字节只允许包含大小写英文字母a-zA-Z、数字0-9)及下划线和连词符。
* @param string expire - UserSig 票据的过期时间,单位是秒,比如 86400 代表生成的 UserSig 票据在一天后就无法再使用了。
* @return string 签名字符串
* @throws \Exception
*/
/**
* Function: Used to issue UserSig that is required by the TRTC and IM services.
*
* Parameter description:
* @param userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
* @param expire - UserSig expiration time, in seconds. For example, 86400 indicates that the generated UserSig will expire one day after being generated.
* @return string signature string
* @throws \Exception
*/
public function genUserSig( $userid, $expire = 86400*180 ) {
return $this->__genSig( $userid, $expire, '', false );
}
/**
*【功能说明】
* 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
* PrivateMapKey 需要跟 UserSig 一起使用,但 PrivateMapKey UserSig 有更强的权限控制能力:
* - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
* - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
* 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】=>【应用管理】=>【应用信息】中打开“启动权限密钥”开关。
*
*【参数说明】
* @param userid - 用户id限制长度为32字节只允许包含大小写英文字母a-zA-Z、数字0-9)及下划线和连词符。
* @param expire - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
* @param roomid - 房间号,用于指定该 userid 可以进入的房间号
* @param privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限开关:
* - 1 0000 0001 = 1,创建房间的权限
* - 2 0000 0010 = 2,加入房间的权限
* - 3 0000 0100 = 4,发送语音的权限
* - 4 0000 1000 = 8,接收语音的权限
* - 5 0001 0000 = 16,发送视频的权限
* - 6 0010 0000 = 32,接收视频的权限
* - 7 0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
* - 8 1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
* - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
* - privilegeMap == 0010 1010 == 42 代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
*/
/**
* Function:
* Used to issue PrivateMapKey that is optional for room entry.
* PrivateMapKey must be used together with UserSig but with more powerful permission control capabilities.
* - UserSig can only control whether a UserID has permission to use the TRTC service. As long as the UserSig is correct, the user with the corresponding UserID can enter or leave any room.
* - PrivateMapKey specifies more stringent permissions for a UserID, including whether the UserID can be used to enter a specific room and perform audio/video upstreaming in the room.
* To enable stringent PrivateMapKey permission bit verification, you need to enable permission key in TRTC console > Application Management > Application Info.
*
* Parameter description:
* userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
* roomid - ID of the room to which the specified UserID can enter.
* expire - PrivateMapKey expiration time, in seconds. For example, 86400 indicates that the generated PrivateMapKey will expire one day after being generated.
* privilegeMap - Permission bits. Eight bits in the same byte are used as the permission switches of eight specific features:
* - Bit 1: 0000 0001 = 1, permission for room creation
* - Bit 2: 0000 0010 = 2, permission for room entry
* - Bit 3: 0000 0100 = 4, permission for audio sending
* - Bit 4: 0000 1000 = 8, permission for audio receiving
* - Bit 5: 0001 0000 = 16, permission for video sending
* - Bit 6: 0010 0000 = 32, permission for video receiving
* - Bit 7: 0100 0000 = 64, permission for substream video sending (screen sharing)
* - Bit 8: 1000 0000 = 200, permission for substream video receiving (screen sharing)
* - privilegeMap == 1111 1111 == 255: Indicates that the UserID has all feature permissions of the room specified by roomid.
* - privilegeMap == 0010 1010 == 42: Indicates that the UserID has only the permissions to enter the room and receive audio/video data.
*/
public function genPrivateMapKey( $userid, $expire, $roomid, $privilegeMap ) {
$userbuf = $this->__genUserBuf( $userid, $roomid, $expire, $privilegeMap, 0, '' );
return $this->__genSig( $userid, $expire, $userbuf, true );
}
/**
*【功能说明】
* 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
* PrivateMapKey 需要跟 UserSig 一起使用,但 PrivateMapKey UserSig 有更强的权限控制能力:
* - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
* - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
* 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】=>【应用管理】=>【应用信息】中打开“启动权限密钥”开关。
*
*【参数说明】
* @param userid - 用户id限制长度为32字节只允许包含大小写英文字母a-zA-Z、数字0-9)及下划线和连词符。
* @param expire - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
* @param roomstr - 房间号,用于指定该 userid 可以进入的房间号
* @param privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限开关:
* - 1 0000 0001 = 1,创建房间的权限
* - 2 0000 0010 = 2,加入房间的权限
* - 3 0000 0100 = 4,发送语音的权限
* - 4 0000 1000 = 8,接收语音的权限
* - 5 0001 0000 = 16,发送视频的权限
* - 6 0010 0000 = 32,接收视频的权限
* - 7 0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
* - 8 1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
* - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
* - privilegeMap == 0010 1010 == 42 代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
*/
/**
* Function:
* Used to issue PrivateMapKey that is optional for room entry.
* PrivateMapKey must be used together with UserSig but with more powerful permission control capabilities.
* - UserSig can only control whether a UserID has permission to use the TRTC service. As long as the UserSig is correct, the user with the corresponding UserID can enter or leave any room.
* - PrivateMapKey specifies more stringent permissions for a UserID, including whether the UserID can be used to enter a specific room and perform audio/video upstreaming in the room.
* To enable stringent PrivateMapKey permission bit verification, you need to enable permission key in TRTC console > Application Management > Application Info.
*
* Parameter description:
* @param userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
* @param roomstr - ID of the room to which the specified UserID can enter.
* @param expire - PrivateMapKey expiration time, in seconds. For example, 86400 indicates that the generated PrivateMapKey will expire one day after being generated.
* @param privilegeMap - Permission bits. Eight bits in the same byte are used as the permission switches of eight specific features:
* - Bit 1: 0000 0001 = 1, permission for room creation
* - Bit 2: 0000 0010 = 2, permission for room entry
* - Bit 3: 0000 0100 = 4, permission for audio sending
* - Bit 4: 0000 1000 = 8, permission for audio receiving
* - Bit 5: 0001 0000 = 16, permission for video sending
* - Bit 6: 0010 0000 = 32, permission for video receiving
* - Bit 7: 0100 0000 = 64, permission for substream video sending (screen sharing)
* - Bit 8: 1000 0000 = 200, permission for substream video receiving (screen sharing)
* - privilegeMap == 1111 1111 == 255: Indicates that the UserID has all feature permissions of the room specified by roomid.
* - privilegeMap == 0010 1010 == 42: Indicates that the UserID has only the permissions to enter the room and receive audio/video data.
*/
public function genPrivateMapKeyWithStringRoomID( $userid, $expire, $roomstr, $privilegeMap ) {
$userbuf = $this->__genUserBuf( $userid, 0, $expire, $privilegeMap, 0, $roomstr );
return $this->__genSig( $userid, $expire, $userbuf, true );
}
public function __construct( $sdkappid, $key ) {
$this->sdkappid = $sdkappid;
$this->key = $key;
}
/**
* 用于 url base64 encode
* '+' => '*', '/' => '-', '=' => '_'
* @param string $string 需要编码的数据
* @return string 编码后的base64串失败返回false
* @throws \Exception
*/
/**
* base64 encode for url
* '+' => '*', '/' => '-', '=' => '_'
* @param string $string data to be encoded
* @return string The encoded base64 string, returns false on failure
* @throws \Exception
*/
private function base64_url_encode( $string ) {
static $replace = Array( '+' => '*', '/' => '-', '=' => '_' );
$base64 = base64_encode( $string );
if ( $base64 === false ) {
throw new \Exception( 'base64_encode error' );
}
return str_replace( array_keys( $replace ), array_values( $replace ), $base64 );
}
/**
* 用于 url base64 decode
* '+' => '*', '/' => '-', '=' => '_'
* @param string $base64 需要解码的base64串
* @return string 解码后的数据失败返回false
* @throws \Exception
*/
/**
* base64 decode for url
* '+' => '*', '/' => '-', '=' => '_'
* @param string $base64 base64 string to be decoded
* @return string Decoded data, return false on failure
* @throws \Exception
*/
private function base64_url_decode( $base64 ) {
static $replace = Array( '+' => '*', '/' => '-', '=' => '_' );
$string = str_replace( array_values( $replace ), array_keys( $replace ), $base64 );
$result = base64_decode( $string );
if ( $result == false ) {
throw new \Exception( 'base64_url_decode error' );
}
return $result;
}
/**
* TRTC业务进房权限加密串使用用户定义的userbuf
* @brief 生成 userbuf
* @param account 用户名
* @param dwSdkappid sdkappid
* @param dwAuthID 数字房间号
* @param dwExpTime 过期时间:该权限加密串的过期时间. 过期时间 = now+dwExpTime
* @param dwPrivilegeMap 用户权限255表示所有权限
* @param dwAccountType 用户类型, 默认为0
* @param roomStr 字符串房间号
* @return userbuf string 返回的userbuf
*/
/**
* User-defined userbuf is used for the encrypted string of TRTC service entry permission
* @brief generate userbuf
* @param account username
* @param dwSdkappid sdkappid
* @param dwAuthID digital room number
* @param dwExpTime Expiration time: The expiration time of the encrypted string of this permission. Expiration time = now+dwExpTime
* @param dwPrivilegeMap User permissions, 255 means all permissions
* @param dwAccountType User type, default is 0
* @param roomStr String room number
* @return userbuf string returned userbuf
*/
private function __genUserBuf( $account, $dwAuthID, $dwExpTime, $dwPrivilegeMap, $dwAccountType,$roomStr ) {
//cVer unsigned char/1 版本号填0
if($roomStr == '')
$userbuf = pack( 'C1', '0' );
else
$userbuf = pack( 'C1', '1' );
$userbuf .= pack( 'n', strlen( $account ) );
//wAccountLen unsigned short /2 第三方自己的帐号长度
$userbuf .= pack( 'a'.strlen( $account ), $account );
//buffAccount wAccountLen 第三方自己的帐号字符
$userbuf .= pack( 'N', $this->sdkappid );
//dwSdkAppid unsigned int/4 sdkappid
$userbuf .= pack( 'N', $dwAuthID );
//dwAuthId unsigned int/4 群组号码/音视频房间号
$expire = $dwExpTime + time();
$userbuf .= pack( 'N', $expire );
//dwExpTime unsigned int/4 过期时间 (当前时间 + 有效期单位建议300秒
$userbuf .= pack( 'N', $dwPrivilegeMap );
//dwPrivilegeMap unsigned int/4 权限位
$userbuf .= pack( 'N', $dwAccountType );
//dwAccountType unsigned int/4
if($roomStr != '')
{
$userbuf .= pack( 'n', strlen( $roomStr ) );
//roomStrLen unsigned short /2 字符串房间号长度
$userbuf .= pack( 'a'.strlen( $roomStr ), $roomStr );
//roomStr roomStrLen 字符串房间号
}
return $userbuf;
}
/**
* 使用 hmac sha256 生成 sig 字段内容,经过 base64 编码
* @param $identifier 用户名utf-8 编码
* @param $curr_time 当前生成 sig unix 时间戳
* @param $expire 有效期,单位秒
* @param $base64_userbuf base64 编码后的 userbuf
* @param $userbuf_enabled 是否开启 userbuf
* @return string base64 后的 sig
*/
/**
* Use hmac sha256 to generate sig field content, base64 encoded
* @param $identifier Username, utf-8 encoded
* @param $curr_time The unix timestamp of the current generated sig
* @param $expire Validity period, in seconds
* @param $base64_userbuf base64 encoded userbuf
* @param $userbuf_enabled 是No enable userbuf
* @return string sig after base64
*/
private function hmacsha256( $identifier, $curr_time, $expire, $base64_userbuf, $userbuf_enabled ) {
$content_to_be_signed = 'TLS.identifier:' . $identifier . "\n"
. 'TLS.sdkappid:' . $this->sdkappid . "\n"
. 'TLS.time:' . $curr_time . "\n"
. 'TLS.expire:' . $expire . "\n";
if ( true == $userbuf_enabled ) {
$content_to_be_signed .= 'TLS.userbuf:' . $base64_userbuf . "\n";
}
return base64_encode( hash_hmac( 'sha256', $content_to_be_signed, $this->key, true ) );
}
/**
* 生成签名。
*
* @param $identifier 用户账号
* @param int $expire 过期时间,单位秒,默认 180
* @param $userbuf base64 编码后的 userbuf
* @param $userbuf_enabled 是否开启 userbuf
* @return string 签名字符串
* @throws \Exception
*/
/**
* Generate signature.
*
* @param $identifier user account
* @param int $expire Expiration time, in seconds, default 180 days
* @param $userbuf base64 encoded userbuf
* @param $userbuf_enabled Whether to enable userbuf
* @return string signature string
* @throws \Exception
*/
private function __genSig( $identifier, $expire, $userbuf, $userbuf_enabled ) {
$curr_time = time();
$sig_array = Array(
'TLS.ver' => '2.0',
'TLS.identifier' => strval( $identifier ),
'TLS.sdkappid' => intval( $this->sdkappid ),
'TLS.expire' => intval( $expire ),
'TLS.time' => intval( $curr_time )
);
$base64_userbuf = '';
if ( true == $userbuf_enabled ) {
$base64_userbuf = base64_encode( $userbuf );
$sig_array['TLS.userbuf'] = strval( $base64_userbuf );
}
$sig_array['TLS.sig'] = $this->hmacsha256( $identifier, $curr_time, $expire, $base64_userbuf, $userbuf_enabled );
if ( $sig_array['TLS.sig'] === false ) {
throw new \Exception( 'base64_encode error' );
}
$json_str_sig = json_encode( $sig_array );
if ( $json_str_sig === false ) {
throw new \Exception( 'json_encode error' );
}
$compressed = gzcompress( $json_str_sig );
if ( $compressed === false ) {
throw new \Exception( 'gzcompress error' );
}
return $this->base64_url_encode( $compressed );
}
/**
* 验证签名。
*
* @param string $sig 签名内容
* @param string $identifier 需要验证用户名utf-8 编码
* @param int $init_time 返回的生成时间unix 时间戳
* @param int $expire_time 返回的有效期,单位秒
* @param string $userbuf 返回的用户数据
* @param string $error_msg 失败时的错误信息
* @return boolean 验证是否成功
* @throws \Exception
*/
/**
* Verify signature.
*
* @param string $sig Signature content
* @param string $identifier Need to authenticate user name, utf-8 encoding
* @param int $init_time Returned generation time, unix timestamp
* @param int $expire_time Return the validity period, in seconds
* @param string $userbuf returned user data
* @param string $error_msg error message on failure
* @return boolean Verify success
* @throws \Exception
*/
private function __verifySig( $sig, $identifier, &$init_time, &$expire_time, &$userbuf, &$error_msg ) {
try {
$error_msg = '';
$compressed_sig = $this->base64_url_decode( $sig );
$pre_level = error_reporting( E_ERROR );
$uncompressed_sig = gzuncompress( $compressed_sig );
error_reporting( $pre_level );
if ( $uncompressed_sig === false ) {
throw new \Exception( 'gzuncompress error' );
}
$sig_doc = json_decode( $uncompressed_sig );
if ( $sig_doc == false ) {
throw new \Exception( 'json_decode error' );
}
$sig_doc = ( array )$sig_doc;
if ( $sig_doc['TLS.identifier'] !== $identifier ) {
throw new \Exception( "identifier dosen't match" );
}
if ( $sig_doc['TLS.sdkappid'] != $this->sdkappid ) {
throw new \Exception( "sdkappid dosen't match" );
}
$sig = $sig_doc['TLS.sig'];
if ( $sig == false ) {
throw new \Exception( 'sig field is missing' );
}
$init_time = $sig_doc['TLS.time'];
$expire_time = $sig_doc['TLS.expire'];
$curr_time = time();
if ( $curr_time > $init_time+$expire_time ) {
throw new \Exception( 'sig expired' );
}
$userbuf_enabled = false;
$base64_userbuf = '';
if ( isset( $sig_doc['TLS.userbuf'] ) ) {
$base64_userbuf = $sig_doc['TLS.userbuf'];
$userbuf = base64_decode( $base64_userbuf );
$userbuf_enabled = true;
}
$sigCalculated = $this->hmacsha256( $identifier, $init_time, $expire_time, $base64_userbuf, $userbuf_enabled );
if ( $sig != $sigCalculated ) {
throw new \Exception( 'verify failed' );
}
return true;
} catch ( \Exception $ex ) {
$error_msg = $ex->getMessage();
return false;
}
}
/**
* userbuf 验证签名。
*
* @param string $sig 签名内容
* @param string $identifier 需要验证用户名utf-8 编码
* @param int $init_time 返回的生成时间unix 时间戳
* @param int $expire_time 返回的有效期,单位秒
* @param string $error_msg 失败时的错误信息
* @return boolean 验证是否成功
* @throws \Exception
*/
/**
* Verify signature with userbuf.
*
* @param string $sig Signature content
* @param string $identifier Need to authenticate user name, utf-8 encoding
* @param int $init_time Returned generation time, unix timestamp
* @param int $expire_time Return the validity period, in seconds
* @param string $error_msg error message on failure
* @return boolean Verify success
* @throws \Exception
*/
public function verifySig( $sig, $identifier, &$init_time, &$expire_time, &$error_msg ) {
$userbuf = '';
return $this->__verifySig( $sig, $identifier, $init_time, $expire_time, $userbuf, $error_msg );
}
/**
* 验证签名
* @param string $sig 签名内容
* @param string $identifier 需要验证用户名utf-8 编码
* @param int $init_time 返回的生成时间unix 时间戳
* @param int $expire_time 返回的有效期,单位秒
* @param string $userbuf 返回的用户数据
* @param string $error_msg 失败时的错误信息
* @return boolean 验证是否成功
* @throws \Exception
*/
/**
* Verify signature
* @param string $sig Signature content
* @param string $identifier Need to authenticate user name, utf-8 encoding
* @param int $init_time Returned generation time, unix timestamp
* @param int $expire_time Return the validity period, in seconds
* @param string $userbuf returned user data
* @param string $error_msg error message on failure
* @return boolean Verify success
* @throws \Exception
*/
public function verifySigWithUserBuf( $sig, $identifier, &$init_time, &$expire_time, &$userbuf, &$error_msg ) {
return $this->__verifySig( $sig, $identifier, $init_time, $expire_time, $userbuf, $error_msg );
}
}

View File

@ -34,7 +34,7 @@ class IdCard extends Base
$this->options["form_params"] = $this->params; $this->options["form_params"] = $this->params;
$result = $this->httpRuest->getRequest($api_url,$this->options); $result = $this->httpRuest->postRequest($api_url,$this->options);
if (empty($result)){ if (empty($result)){
return "身份证认证失败"; return "身份证认证失败";