不知鱼耶

导航

快递管家授权,订单导入,单号回传参考

/**
* 注意:http://www.demo.com/Demo/index 所有快递管家授权,回调等地址都是同一地址
* 快递推送
* Class DemoController
* @package Weixin\Controller
*/
class KdexportController extends Controller
{
protected $client_id=''; //app id
protected $client_secret=''; //app key

public function index()
{

$param = I(); //接收所有参数
//授权快递管家并且导入订单到快递管家
if(isset($param['code']) || isset($param['order_id'])) {
file_put_contents("log1.txt",'参数:'.json_encode($param).PHP_EOL,FILE_APPEND);
$code = $param['code'];
$info = $this->get_kd100_access_token($code); //access_token
// var_dump($info);die;
$order = [];
if(empty($param['order_id'])) $this->error('请选择导入的订单');
$order = M('order')->where(['id'=>$param['order_id']])->find();
if(!$order) $this->error('订单不存在');
$res_order_export = $this->export_order($info['access_token'],$order); //导入订单
return $res_order_export;
}
//快递管家订单发货回传接收并处理
$return_order_send_info =file_get_contents("php://input");
file_put_contents("log2.txt",'单号回传接收:'.json_encode($return_order_send_info).PHP_EOL,FILE_APPEND);
//快递管家订单回调发货
if($return_order_send_info){
$return_order_send_info = urldecode($return_order_send_info);
$this->order_accept_return($return_order_send_info);
}
// halt($info);
}

/**
* 导入订单
* @param string $access_token
* @param array $order
*/
public function export_order($access_token='',$order=[])
{
$url = "https://b.kuaidi100.com/v6/open/api/send";
//{
//"itemName": "小米 MIX3",
//"itemUnit": "件",
//"itemCount": 2
//}
$order_goods =[];
// $od = [
// 'recMobile'=>'13117343512', //收件人电话
// 'recName'=>'测试', //收件人姓名
// 'recAddr'=>'广东省深圳市罗湖区游龙街道100号', //收件人详细地址
// 'sendMobile'=>'13117343517', //寄件人电话
// 'sendName'=>'张三', //寄件人姓名
// 'sendAddr'=>'广东省深圳市南山区科技', //寄件人详细地址
// 'orderNum'=>date('Ymd').rand(0,999999), //订单号
// 'cargo'=>'商品', //物品名称
// 'apiPayMode'=>'STANDARD', //扣费模式“STANDARD”:标准的;”SINGLE”:单独的
// ];
$od = [
'recMobile'=>$order['tel'], //收件人电话
'recName'=>$order['consignee'], //收件人姓名
'recAddr'=>$order['city'].$order['address'], //收件人详细地址
'sendMobile'=>'', //寄件人电话
'sendName'=>'', //寄件人姓名
'sendAddr'=>'', //寄件人详细地址
'orderNum'=>$order['order_id'], //订单号
'cargo'=>'商品', //物品名称
'apiPayMode'=>'STANDARD', //扣费模式“STANDARD”:标准的;”SINGLE”:单独的
];
$data = [
'appid'=>$this->client_id,
'access_token'=>$access_token,
'timestamp'=>(int)$this->get_millisecond(),
'data'=>$od,
];
if(!empty($order_goods)) $data['data']['items'] = $order_goods; //物品清单列表
$data['data'] = json_encode($data['data']);
$sign =$this->get_sign($data);
$data['sign'] =$sign;
$res = $this->request_url($url,'POST',$data);
if(!empty($res['status']) && $res['status']!=200) {
echo '<pre>';
var_dump($res);
echo '</pre>';die;
} else {
file_put_contents("log.txt",'订单导入快递管家:'.json_encode($res).PHP_EOL,FILE_APPEND);
M('order')->where('id='.$order['id'])->save(['is_export_kd'=>1]);
$url = U('Order/index');
redirect($url);
$this->success('操作成功',$url);
}
}


/**
* 快递100-发起快递管家授权,获取code
* @param null $redirect_uri 回调url
*/
public function get_kd100_auth($redirect_uri=null)
{
$tm = (int)$this->get_millisecond(); //获取当前时间戳的毫秒数
if($redirect_uri==null) {
$su_str = $this->get_all_url();
$su_arr = explode("?",$su_str);
$redirect_uri = $su_arr[0];
}
//快递100授权发起
$request_data = [
'client_id'=>$this->client_id,
'response_type'=>'code',
'state'=>'yujiu',
'timestamp'=>$tm,
'redirect_uri'=>$redirect_uri,
];
$sign =$this->get_sign($request_data);
$request_data['sign'] =$sign;
$url ='https://b.kuaidi100.com/open/oauth/authorize?response_type='.$request_data['response_type'].
'&client_id='.$request_data['client_id'].
'&redirect_uri='.urlencode($request_data['redirect_uri']).
'&state=yujiu'.
'&timestamp='.$request_data['timestamp'].
'&sign='.$request_data['sign'];

// $url ="https://b.kuaidi100.com/open/oauth/authorize?response_type=code&client_id=NV4GI5zgm1A6&redirect_uri={$request_data['redirect_uri']}&state=yujiu&timestamp={$request_data['timestamp']}&sign={$request_data['sign']}";
// echo "<pre>";
// var_dump($url);
// echo "</pre>";
// die;
header("location:".$url);
return;
}

/**
* 获取access_token
* @param string $code code
* @param null $redirect_uri 当前回调url
*
* @return bool|mixed|string
*/
public function get_kd100_access_token($code='',$redirect_uri=null)
{

if(file_exists("kd100_access_token.json")) { //快递100登录已授权
$info = file_get_contents('kd100_access_token.json');
$info = json_decode($info,true);
//过期刷新
if(time()>$info['expires_in']) $info = $this->request_refresh_access_token($info['refresh_token']);
} else { //快递100登录未授权
// var_dump($code);die;
if(!$code) $this->get_kd100_auth();
$info = $this->request_access_token($code, $redirect_uri);
}
return $info;
}

/**
* 获取access_token
* @param $code code
* @param null $redirect_uri 回调url
*
* @return mixed
*/
public function request_access_token($code,$redirect_uri=null)
{
$url = 'https://b.kuaidi100.com/open/oauth/accessToken';
if($redirect_uri===null) {
$su_str = $this->get_all_url();
$su_arr = explode("?",$su_str);
$redirect_uri = $su_arr[0];
}
$data = [
'client_id'=>$this->client_id,
'client_secret'=>$this->client_secret,
'grant_type'=>'authorization_code',
'code'=>trim($code),
'timestamp'=>(int)$this->get_millisecond(),
'redirect_uri'=>$redirect_uri,
];

$sign =$this->get_sign($data);
$data['sign'] =$sign;
$res = $this->request_url($url,'POST',$data);
// var_dump($res);die;
if(!empty($res['access_token'])) {
$fdata = $res;
//access_token过期,提前20秒过期
$fdata['expires_in'] = $fdata['expires_in']+time()-20;
file_put_contents('kd100_access_token.json',json_encode($fdata));
} else {
echo '<pre>';
var_dump($res);
echo '</pre>';die;
}
return $res;
}

/**
* 刷新access_token 过期时间一年
* @param string $refresh_token
*
* @return mixed
*/
public function request_refresh_access_token($refresh_token='')
{
$url = 'https://b.kuaidi100.com/open/oauth/refreshToken';
$data = [
'client_id'=>$this->client_id,
'client_secret'=>$this->client_secret,
'refresh_token'=>$refresh_token,
'grant_type'=>'refresh_token',
'timestamp'=>(int)$this->get_millisecond(),
];
$sign =$this->get_sign($data);
$data['sign'] =$sign;
$res = $this->request_url($url,'POST',$data);
if(!empty($res['access_token'])) {
$fdata = $res;
//access_token过期,提前20秒过期
$fdata['expires_in'] = $fdata['expires_in']+time()-20;
file_put_contents('kd100_access_token.json',json_encode($fdata));
} else {
echo '<pre>';
var_dump($res);
echo '</pre>';die;
}
return $res;
}

/**
* curl 请求
* @param string $url 请求url
* @param string $method 请求方式
* @param array $data post数据
* @param bool $ssl
*
* @return mixed
*/
public function request_url($url='',$method='GET',$data=null,$ssl=false)
{
$method =strtolower($method);
// $headerArray =array("Content-type:application/json;","Accept:application/json");
$headerArray =array("Content-type: application/x-www-form-urlencoded", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url); //设置请求路径
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $ssl);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,$ssl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //设置返回值
curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray); //设置请求头
if($method=='get') {

} elseif($method=='post') {
curl_setopt($curl, CURLOPT_POST, 1);
$data = is_array($data) ? http_build_query($data) : $data;
if(!empty($data)) curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($curl);
if($output===false) {
echo 'curl error:'.curl_error($curl);
curl_close($curl);
exit;
}
curl_close($curl);
return json_decode($output,true);
}

//获取当前页面的url
public function get_all_url()
{
$http = $_SERVER['SERVER_PORT']=='80' ? 'http://' :'https://';
if(empty($_SERVER['REQUEST_URI'])) {
$url = $http.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
} else {
$url = $http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
return $url;
}

//获取当前时间的毫秒数
public function get_millisecond()
{
//设置时区
date_default_timezone_set('Asia/Shanghai');
list($msec, $sec) = explode(' ', microtime());
$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
return $msectime;
}

/**
* 签名
* @param array $data 签名参数
* @param string $client_secret 签名key
*
* @return array|string
*/
public function get_sign($data=[]){
if(empty($data)) return ['code'=>0,'msg'=>'签名参数不能为空'];
ksort($data);
$str = '';
foreach ($data as $k =>$v) {
$str.=$k.$v;
}
$sgin = strtoupper(md5($this->client_secret.$str.$this->client_secret));
return $sgin;
}


//导入订单信息推送接收
public function order_accept_return($info)
{
try{
$sucess = ['status'=>200];
$error = ['status'=>400];
file_put_contents("ldlog1.txt",'回调通知:'.$info.PHP_EOL,FILE_APPEND);
if($info) {
$info = json_decode($info,true);
$order_data = $info['data'];
if(is_array($order_data)) {
foreach ($order_data as $v) {
$send_info = [
'express_id'=>$v['kuaidinum'], //快递单号
'company'=>$v['kuaidicom'], //快递公司编码shunfeng
'company_name'=>$v['kuaidicomName'], //快递公司名
'state'=>3, //快递公司名
];
file_put_contents("ldlog.txt",'订单数据:'.json_encode($send_info),FILE_APPEND);
if(!empty($send_info)) {
M('order')->where('order_id='.$v['orderNum'])->setField($send_info);
}

}
}
}
return json_encode($sucess);

} catch (\Exception $e) {
file_put_contents("ldlog.txt",'订单推送接收错误:'.json_encode(['line'=>$e->getLine(),'msg'=>$e->getMessage()]),FILE_APPEND);
}

}

}

posted on 2020-04-20 09:35  不知鱼耶  阅读(923)  评论(0编辑  收藏  举报