PHP 蜂鸟即配封装类 - ThinkPHP框架
//蜂鸟即配
'FNPSELE' => [
'APPID' => '', //App ID
'SecretKey' => '', //密钥
'FORMAL_URL' => 'https://exam-anubis.ele.me/anubis-webapi', // 正式环境
'ADJUSTING_URL' => 'https://open-anubis.ele.me/anubis-webapi', //联调环境
],
把以下封装类,直接丢入公共类模块。
在控制器里直接 use **/Anubis; 使用 new Anubis;调用
<?php
/**
* 蜂鸟即配封装类.
*/
namespace app\common\service\thirdparty;
use think\Cache;
define('APPID', config('FNPSELE.APPID')); //蜂鸟配送APPID
define('SecretKey', config('FNPSELE.SecretKey')); //蜂鸟配送SecretKey
class Anubis
{
private $salt = ''; //随机数
private $formalUrl = []; //正式地址
private $adjustingUrl = []; //联调地址
/**
* 赋值各个地址
* Ele constructor.
*/
function __construct()
{
$this->formalUrl = config('FNPSELE.FORMAL_URL');//蜂鸟配送APPID
$this->adjustingUrl = config('FNPSELE.ADJUSTING_URL');//蜂鸟配送SecretKey
$this->salt = mt_rand(1000, 9999);
}
/**
* 获取token
* @return mixed
*/
public function getToken()
{
$eleToken = Cache::get('eleToken');
if(!empty($eleToken)){
return Cache('eleToken');
}else{
$url = $this->requestUrl(true, 'get_access_token') . '?app_id=' . APPID . '&salt=' . $this->salt . '&signature=' . $this->tokenSign();
$postUrl = $this->requestHttp($url);
if ($postUrl['code'] == 200 && isset($postUrl['data']['access_token'])) {
Cache::set('eleToken',$postUrl['data']['access_token'],3600*23);
return Cache::get('eleToken');
}
return $postUrl; //错误会返回code
}
}
/**
* 请求地址
* @param string $type (1为正式地址,0为联调地址)
* @param string $urlType
* @return mixed|string
*/
private function requestUrl($type = '1', $urlType = '')
{
$url = '';
switch ($type) {
case 1:
$url = $this->adjustingUrl;
break;
case 0:
$url = $this->formalUrl;
break;
}
return $url.'/'.$urlType;
}
/**
* 获取token时的签名
* @return string
*/
private function tokenSign()
{
$sign = 'app_id=' . APPID