cxgj/components/YopointApi.php
2023-11-27 09:45:13 +08:00

626 lines
21 KiB
PHP

<?php
namespace app\components;
use app\models\DevList;
use app\models\Goods;
use app\models\GoodsHub;
use app\models\Order;
use app\models\OrderDetail;
use app\models\YopointNotify;
use app\modules\api\models\MsgCentreForm;
use app\modules\api\models\OrderGoodsForm;
/**
* 有朋api接口
*/
class YopointApi
{
public $appid;
public $appSecret;
public $url;
public $open_secret = "2qWOTUpFr4vKJLhi"; # 第三方支付签名密钥
public $user_id;
public function __construct(){
$this->appid = "179396370818";
$this->appSecret = "d993a8c08bf32b7a9c6aad243af2ba00";
$this->url = "https://api.yopoint.com/api/gateway/index";
}
/**
* 获取sign参数
*/
public function getSign($arr,$type='api'){
ksort($arr);
$res = "";
foreach ($arr as $key=>$val){
$res .= "{$key}={$val}&";
}
if($type == 'openDevCall'){
$res .= $this->open_secret;
return md5($res);
}
$res .= "{$this->appSecret}";
return md5($res);
}
/**
* @ 获取自取柜列表
*/
public function getDeviceList($page=1,$limit=10){
$arr = [
'method' => 'cabinet.list',
'biz_content' => json_encode([
'Page' => $page,
'PageSize' => $limit,
]),
'appid' => $this->appid,
'sign_type' => 'md5',
'timestamp' => time(),
'version' => '1.0.0',
];
$arr['sign'] = $this->getSign($arr);
$res = $this->post_url($this->url,http_build_query($arr));
if(empty($res)){
return false;
}
try{
return json_decode($res,true);
}catch (\Exception $e){
return false;
}
}
/**
* 同步数据库
*/
public function syncDeviceList(){
$page = 1;
$limit = 10;
while (True){
$res = $this->getDeviceList($page,$limit);
if(empty($res)){
break;
}
if(empty($res['data'])){
break;
}
if(empty($res['data']['data'])){
break;
}
$page++;
// 写入库
foreach ($res['data']['data'] as $key=>$val){
$find = DevList::findOne([
'dev_id' => $val['id'],
]);
if(empty($find)){
$find = new DevList();
$find->dev_id = $val['id'];
$find->store_id = 0;
$find->created_at = time();
$find->is_delete = 0;
$find->deleted_at = 0;
}
$find->updated_at = time();
$find->dev_name = $val['Name']??'';
$find->dev_code = $val['DeviceCode']??'';
$find->sc_code = $val['Code']??'';
$find->sell_status = intval($val['SellStatus']);
$find->enable_sell = empty($val['EnableSell'])?2:1;
$find->online_status = intval($val['OnlineStatus']);
$find->province = $val['Province']??'';
$find->city = $val['City']??'';
$find->district = $val['District']??'';
$find->service_phone = $val['ServicePhone'];
$find->address = $val['Address']??'';
$find->save();
}
}
return ['code'=>0,'msg'=>'同步完成'];
}
/**
* @ 获取库存列表
*/
public function getStockList($page=1,$limit=10){
$arr = [
'method' => 'operators.depot.stock.list',
'biz_content' => json_encode([
'page' => $page,
'pageSize' => $limit,
]),
'appid' => $this->appid,
'sign_type' => 'md5',
'timestamp' => time(),
'version' => '1.0.0',
];
$arr['sign'] = $this->getSign($arr);
$res = $this->post_url($this->url,http_build_query($arr));
if(empty($res)){
return false;
}
try{
return json_decode($res,true);
}catch (\Exception $e){
return false;
}
}
/**
* @ 获取商品详情
*/
public function getStockInfo($BarCode){
$arr = [
'method' => 'product.operators.get',
'biz_content' => json_encode([
'BarCode' => $BarCode,
]),
'appid' => $this->appid,
'sign_type' => 'md5',
'timestamp' => time(),
'version' => '1.0.0',
];
$arr['sign'] = $this->getSign($arr);
$res = $this->post_url($this->url,http_build_query($arr));
if(empty($res)){
return false;
}
try{
return json_decode($res,true);
}catch (\Exception $e){
return false;
}
}
/**
* @ 获取商品列表
*/
public function getOrderList($page,$limit,$date='',$end=''){
$arr = [
'method' => 'cabinet.order.list',
'biz_content' => json_encode([
'page' => $page,
'pageSize' => $limit,
'startTime' => strtotime($date),
'endTime' => strtotime($end)
]),
'appid' => $this->appid,
'sign_type' => 'md5',
'timestamp' => time(),
'version' => '1.0.0',
];
$arr['sign'] = $this->getSign($arr);
$res = $this->post_url($this->url,http_build_query($arr));
if(empty($res)){
return false;
}
try{
return json_decode($res,true);
}catch (\Exception $e){
return false;
}
}
/**
* 同步库存数据库
*/
public function syncStockList(){
$page = 1;
$limit = 10;
while (True){
$res = $this->getStockList($page,$limit);
if(empty($res)){
break;
}
if(empty($res['data'])){
break;
}
if(empty($res['data']['data'])){
break;
}
$page++;
// 写入库
foreach ($res['data']['data'] as $key=>$val){
if(empty($val['BarCode'])){
continue;
}
$find = Goods::findOne([
'yopoint_barcode' => $val['BarCode'],
]);
if(empty($find)){
$info = $this->getStockInfo($val['BarCode']);
if(empty($info['data'])){
continue;
}
$goods_hub = new GoodsHub();
$goods_hub->cx_mch_id = 0;
$goods_hub->name = $info['data']['ProductVO']['Name']??"暂无名称";
$goods_hub->subtitle = $info['data']['ProductVO']['Manufacturer']??"暂无信息";
$goods_hub->original_price = intval($info['data']['Price'])/100;
$goods_hub->cost_price = intval($info['data']['Price'])/100;
$goods_hub->detail = "test";
$goods_hub->cover_pic = $this->getImage($val['ProductVO']['ImageUrl'])['save_path']??"";
$goods_hub->pic_urls = "";
$goods_hub->video_url = "";
$goods_hub->unit = "";
$goods_hub->created_at = time();
$goods_hub->updated_at = time();
$goods_hub->deleted_at = 0;
$goods_hub->is_delete = 0;
$goods_hub->type = 0;
if(!$goods_hub->save()){
continue;
}
// 添加
$find = new Goods();
$find->cx_mch_id = 0;
$find->goods_hub_id = $goods_hub->id;
$find->status = 1;
$find->price = intval($info['data']['Price'])/100;
$find->use_attr = 1;
$find->attr_groups = '{}';
$find->goods_stock = 100000; # 库存数量
$find->virtual_sales = 0;
$find->confine_count = 0;
$find->freight_id = 0;
$find->plugin_sign = "";
$find->sort = 0;
$find->created_at = time();
$find->updated_at = time();
$find->deleted_at = 0;
$find->is_delete = 0;
$find->payment_people = 0;
$find->payment_num = 0;
$find->payment_amount = 0;
$find->payment_order = 0;
$find->sales = 0;
$find->viewed_count = 0;
$find->yopoint_barcode = $val['BarCode'];
if(!$find->save()){
continue;
}
}
}
}
return ['code'=>0,'msg'=>'同步完成'];
}
/**
* @ 同步订单
*/
public function syncOrder($yopoint_order){
// 获取订单详细信息
$find = Order::findOne([
'yopoint_order' => $yopoint_order,
'yopoint_status' => 0,
]);
if(empty($find)){
return false;
}
$redis_user_name = "cxgyc:YopointNotify:user:{$find->user_id}";
$data = $this->getOrderInfo($yopoint_order);
if(empty($data)){
// 回退数据
return $yopoint_order;
}
if(empty($data['data'])){
return $yopoint_order;
}
if(empty($data['data']['Products']) && intval($data['data']['ServiceStatus']) === 2){
// 查找友朋回调接口
$find_yopoint = YopointNotify::findOne([
'id' => $find->yopoint_notify_id,
]);
if(!empty($find_yopoint->return_data)){
$json_de = json_decode($find_yopoint->return_data,true);
$this->openDevCall($json_de['data']['NotifyUrl'],$json_de['data']['ReceiptNo'],$find->order_no,1);
}
MsgCentreForm::sendWxAppletGoodsOrderAddRemind($find);
$find->delete();
return false;
}
if(empty($data['data']['Products'])){
var_dump($yopoint_order."还在服务中");
// 还在服务中
// 回退数据
$find->updated_at = time();
$find->is_recycle = 1;
$find->is_delete = 1;
$find->save();
MsgCentreForm::sendWxAppletGoodsOrderAddRemind($find);
return $yopoint_order;
}
$transaction = \Yii::$app->db->beginTransaction();
try{
foreach ($data['data']['Products'] as $key=>$val){
$find_goods = Goods::findOne([
'yopoint_barcode' => $val['BarCode'],
]);
if(empty($find_goods)){
var_dump($yopoint_order."___".$val['BarCode']."没有商品");
$this->syncStockList();
$transaction->rollBack();
$find->updated_at = time();
$find->is_recycle = 1;
$find->is_delete = 1;
$find->save();
// 回退数据
return $yopoint_order;
}
$obj = new OrderDetail();
$obj->cx_mch_id = 0;
$obj->order_id = $find->id;
$obj->goods_id = $find_goods->id;
$obj->num = intval($val['Qty']);
$obj->unit_price = 0;
$obj->total_original_price = 0;
$obj->total_price = 0;
$obj->goods_attr_info = 0;
$obj->is_delete = 0;
$obj->created_at = time();
$obj->updated_at = time();
$obj->deleted_at = 0;
$obj->is_refund = 0;
$obj->refund_status = 0;
$obj->plugin_sign = 'goods';
$obj->serial_no = '';
$obj->goods_type = 0;
$obj->start_time = '';
$obj->end_time = 0;
$obj->duration = 0;
$obj->save();
}
/*// 查找友朋回调接口
$find_yopoint = YopointNotify::findOne([
'id' => $find->yopoint_notify_id,
]);
if(!empty($find_yopoint->return_data)){
$json_de = json_decode($find_yopoint->return_data,true);
$this->openDevCall($json_de['data']['NotifyUrl'],$json_de['data']['ReceiptNo'],$find->order_no,1);
}*/
$order_obj = new OrderGoodsForm();
$order_obj->user_id = $find->user_id;
$order_obj->cx_mch_id = $find->cx_mch_id;
$order_obj->order_id = $find->id;
$order_obj->is_commit = false;
$res = $order_obj->orderBuyGoodsView();
if(!empty($res['code'])){
var_dump($res);
$transaction->rollBack();
$find->updated_at = time();
$find->is_delete = 1;
$find->save();
// 回退数据
return $yopoint_order;
}
\Yii::info(json_encode($res,JSON_UNESCAPED_UNICODE),'yopoint');
\Yii::$app->redis->setex($redis_user_name,60*60,1);
$find->is_delete = 0;
$find->deleted_at = 0;
$find->yopoint_status = 1;# 已执行完毕
$find->created_at = time();# 已执行完毕
$find->is_recycle = 1;
$find->save();
$transaction->commit();
}catch (\Exception $e){
var_dump($yopoint_order.$e->getMessage());
$transaction->rollBack();
\Yii::info(json_encode([$e->getMessage(),$e->getLine(),$e->getFile(),$e->getTraceAsString()]),'yopoint');
// 回退数据
return $yopoint_order;
}
\Yii::info("进入关门提醒",'yopoint');
//关门提醒
try{
MsgCentreForm::sendWxAppletGoodsOrderPayRemind($find,$res);
}catch (\Exception $e){
\Yii::info(json_encode([$e->getMessage(),$e->getLine(),$e->getFile(),$e->getTraceAsString()]),'wx_applet_msg');
}
return false;
}
/**
* 实现下载远程图片保存到本地
* @param $url string 图片链接地址
* @param int $type int 0 远程图片 1 本地图片
* @return array
*/
public function getImage($url)
{
if (trim($url) == '') {
return ['file_name' => '', 'save_path' => '', 'error' => 1];
}
//保存文件名
$ext = str_replace('&pid=hp', '', strrchr($url, '.'));
if (!in_array($ext, ['.png', '.gif', '.jpeg', '.jpg', '.btm'])) {
return ['file_name' => '', 'save_path' => '', 'error' => 3];
}
//文件命名规则
$filename = md5($url).date('his', time()) . $ext;
//创建保存目录,不存在时使用默认规则
$save_dir = \Yii::$app->basePath."/web/upload/yopoint/";
if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
return ['file_name' => '', 'save_path' => '', 'error' => 5];
}
//获取远程文件所采用的方法
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$img = curl_exec($ch);
curl_close($ch);
//文件大小
$fp2 = @fopen($save_dir . $filename, 'a');
fwrite($fp2, $img);
fclose($fp2);
unset($img, $url);
return ['file_name' => $filename, 'save_path' => "/upload/yopoint/". $filename, 'error' => 0];
}
/**
* @ 开柜
*/
public function openDev($cid,$tradeNo,$mobile){
$arr = [
'method' => 'cabinet.open.door',
'biz_content' => json_encode([
'cid' => $cid,
'tradeNo' => $tradeNo,
'mobile' => $mobile,
]),
'appid' => $this->appid,
'sign_type' => 'md5',
'timestamp' => time(),
'version' => '1.0.0',
];
$arr['sign'] = $this->getSign($arr);
$res = $this->post_url($this->url,http_build_query($arr));
if(empty($res)){
return false;
}
$id = $this->insetLog($arr,$res,1);
try{
/*if(!empty($id)){
// 更新数据库
$find_order = Order::findOne([
'order_no' => $tradeNo,
]);
$find_order->yopoint_notify_id = $id;
$find_order->save();
}*/
$json_de = json_decode($res,true);
$json_de['log_id'] = $id;
return $json_de;
}catch (\Exception $e){
return false;
}
}
/**
* @ 开柜
*/
public function openDevCall($url,$receipt_no,$tradeNo,$status){
$arr = [
'receipt_no' => $receipt_no,
'trade_no' => $tradeNo,
'trade_status' => $status,
'trade_raw_data' => '{}',
'complete_status' => 0,
'pay_time' => date('YmdHis'),
];
$arr['sign'] = $this->getSign($arr,'openDevCall');
$res = $this->post_url($url,http_build_query($arr));
if(empty($res)){
return false;
}
$this->insetLog($arr,$res,1);
if($res == 'success'){
// 更新数据库
$find_order = Order::findOne([
'order_no' => $tradeNo,
]);
if(!empty($find_order)){
$find_order->yopoint_status = 2;
$find_order->save();
}
return true;
}else{
return false;
}
}
/**
* @ 获取订单详情
*/
public function getOrderInfo($id){
$arr = [
'method' => 'cabinet.order.get',
'biz_content' => json_encode([
'ReceiptNo' => $id,
]),
'appid' => $this->appid,
'sign_type' => 'md5',
'timestamp' => time(),
'version' => '1.0.0',
];
$arr['sign'] = $this->getSign($arr);
$res = $this->post_url($this->url,http_build_query($arr));
if(empty($res)){
return false;
}
$this->insetLog($arr,$res,1);
try{
return json_decode($res,true);
}catch (\Exception $e){
return false;
}
}
/**
* 写入日志
*/
public function insetLog($arr,$return,$type){
$obj = new YopointNotify();
$obj->appid = $arr['appid']??$this->appid;
$obj->method = $arr['method']??"";
$obj->biz_content = $arr['biz_content']??'';
$obj->timestamp = $arr['timestamp']??'';
$obj->sign_type = $arr['sign_type']??'md5';
$obj->sign = $arr['sign']??'';
if(empty($obj->biz_content)){
$obj->biz_content = json_encode($arr);
}
$obj->created_at = time();
$obj->return_data = $return;
$obj->type = $type;
$obj->user_id = $this->user_id??0;
if(!$obj->save()){
return 0;
}
return $obj->id;
}
/**
* 模拟POST提交
* @param string $url 地址
* @param array|string $data 提交的数据
* @return string 返回结果
*/
public function post_url($url, $data)
{
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); // 模拟用户使用的浏览器
//curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
//curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
$header = [
'ContentType' => 'application/x-www-form-urlencoded;Charset=UTF-8',
];
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包x
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制 防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if(curl_errno($curl))
{
return false;
// echo 'Errno'.curl_error($curl);//捕抓异常
}
curl_close($curl); // 关闭CURL会话
return $tmpInfo; // 返回数据
}
}