一個專案如何請求訪問,另一個封裝好的介面專案的資料
//請求介面資料
public function getGoods()
{
$gids = implode(',', $gids);
$time = time();
$token = md5($time.'|'.$gids.'|'.$this['config']['token_key']['value']);
$url = sprintf("%s/app/shop/getGoodsDetails/%s/%d/%s?id=%s", $this['config']['api_url'], $token, $time, $this['config']['token_key']['key'], $gids);
$data = json_decode($this->response($url), true);
$result = $data['result'];
$this['redis']->set($key, $result);
return $result;
}
//介面定義:
public function getGoodsDetailsAction(Request $request, $token, $time, $appid)
{
$appValue = $this->getTokenKey($appid);
$id = $request->get('id'); //產品id
$sign = md5($time.'|'.$id.'|'.$appValue);
if (empty($id)) {
$this->success([]);
}
if($sign ) {
// $key = 'D_'.$id;
// $re = $this->getcache($key);
// if($re){
// $this->s($re);
// }
$token = strtoupper(md5($id.$this->appid));
$header = ["Method:GetProductGroupList","Token:{$token}"];
$url = $this->url.'/goodapi';
$post = [
'pgids' => $id,
];
$re = $this->_curl($url,$post,$header,'GET');
//增加介面呼叫次數統計
$this->_net_interface_call(NetInterface::GetProductGroupList);
$tmp = json_decode($re, true);
if (200 !== (int) $tmp[0]['status']) {
// $this->error(Code::STATUS_ERROR_API);
$this->success([]);
}
//介面獲取商品詳情後,追加圖片(傳父ID)
// $result['Images'] = $this->getGoodsEntity()->getImages($result['ParentID']);
$em = $this->getDoctrines('shop');
foreach ($tmp[0]['data'] as $k => $value) {
$key = sprintf("goodsImages_%s", $value['ParentID']);
$results = $this->redis->get($key);
if (!$results) {
$results = $em->createQueryBuilder()
->select('a.*')
->from('goods', 'a')
->where('a.goods_id = :goods_id')
->setParameter(':goods_id', $value['ParentID'])
->orderBy('a.sort', 'ASC')
->execute()
->fetch();
if ($results) {
$this->redis->set($key, $results);
}
}
$tmp[0]['data'][$k]['Images'] = $results;
}
$this->success($tmp[0]['data']);
}
$this->error(Code::STATUS_ERROR_TOKEN_ERROR);
}
/**
* 獲取介面資料
*/
protected function response($url, array $data = array(), $method = 'GET', $header = '')
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
if ('POST' === $method) {
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// '' != $header & (curl_setopt($curl, CURLOPT_HTTPHEADER, $header));
}
// curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
// curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
// $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
// if (400 < (int) $httpCode){
// return json_encode(['status' => -1, 'message' =>'伺服器錯誤']);
// }
curl_close($curl);
return $result;
}