<?php
namespace app\meituan\controller;
//美团
use Meituan\Dianping;
class Index
{
	//获取auth_code
   private $api_url="https://openapi.dianping.com/router";
   private $appkey="370926cf832f39e3";
   private $secret="a10badba03f3cb7a4c00ba28a5c160e3dfaaa137";
   public function index(){
		  $auth_code = input('auth_code');
		  if(!isset($auth_code)) {
			   $app_key=$this->appkey;
			   $state=input('data')?input('data'):'teststate';
			   $redirect_url=request()->domain()."/meituan.php";
			   $scope=["tuangou"];
			   $url='https://e.dianping.com/dz-open/merchant/auth?';
			   $data=[
			    'app_key' =>$this->appkey,
			    'state' => $state,
			    'redirect_url' =>$redirect_url,
			    'scope' =>$scope,
			   ];
			   $postdata = http_build_query($data);
			   Header("Location: $url$postdata");
		  } else {
		  	  $state=input('state');
		  	  $data=json_decode(base64_decode($state),1);
		  	  $res=self::get_session($auth_code);
		  	  $getShopid=self::getShopid($res['access_token'],$res['bid']);
		  	  $url="https://".$data['url']."/web/#/plugin/index?acid={$data['acid']}";
		  	  $res = base64_encode(json_encode($res));
		  	  $getShopid = base64_encode(json_encode($getShopid));
		  	  $url=$url."&session={$res}"."&getShopid=".$getShopid;
		  	  Header("Location: $url");
		  }
	}
	//https://chashi.youdiy.cn/meituan.php?data=eyJ1cmwiOiJjaGFzaGkueW91ZGl5LmNuIiwiYWNpZCI6MX0=
	 //查询券、验券
	 public function prepare($qr_code="",$open_shop_uuid="",$session=""){
		  $data = [
		   'app_key' => $this->appkey,
		   'timestamp' => date('Y-m-d H:i:s'),
		   'sign_method' => 'MD5',
		   'format' => 'json',
		   'v' => 1,
		   'session' => $session,
		  ];
		  $arr = [
		   'receipt_code' => $qr_code,
		   'open_shop_uuid' => $open_shop_uuid,
		  ];
		  $data = array_merge($data, $arr);
		  ksort($data);
		  $sign = $this->cal_sign($this->secret, $data);//获取签名
		  $data['sign'] = $sign;
		  $data = array_merge($data, $arr);
		  $postdata = http_build_query($data);
		  $url = 'https://openapi.dianping.com/router/tuangou/receipt/prepare';//输码查询券
		  $res=$this->httpRequest($url,"POST",$data);
		  if($res['code']==200){
		  	 $data=$res['data'];
		  	 //消费券
		  	 $ret=self::consume([
		  	 	'open_shop_uuid'=>$open_shop_uuid,
		  	 	'session'=>$session,
		  	 	'qr_code'=>$qr_code,
		  	 ],[
		  	 	'requestid'=>$data['deal_id'],
		  	 	'qr_code'=>$qr_code,
		  	 	'count'=>$data['count'],
		  	 ]);
		  	 return [
		  	 	'code'=>0,
		  	 	'msg'=>'验券成功',
		  	 	'data'=>$data
		  	 ];
		  }else{
		  	 return [
		  	 	'code'=>1,
		  	 	'msg'=>$res['msg'],
		  	 	'data'=>[]
		  	 ];
		  }
	 }
	 public function refreshToken($refresh_token=""){
	 		$url="https://openapi.dianping.com/router/oauth/token?app_key={$this->appkey}&app_secret={$this->secret}&grant_type=refresh_token&refresh_token=".$refresh_token;
	 		$res=$this->httpRequest($url,"POST");
	 		if($res['code']==200){
	 			  return [
			  	 	'code'=>0,
			  	 	'msg'=>'刷新成功access_token成功',
			  	 	'data'=>[
                       'access_token'=>$res['access_token'],
                       'remain_refresh_count'=>$res['remain_refresh_count'],
                       'refresh_token'=>$res['refresh_token'],
                       'bid'=>$res['bid'],
			  	 	]
			  	  ];
	 		}else{
		  	 return [
		  	 	'code'=>1,
		  	 	'msg'=>'刷新失败',
		  	 	'data'=>[]
		  	 ];
		  }
	 }
	 /*
	  *验证券
	  *config[
	  *		open_shop_uuid
	  *		session
	  *]
	  *param[
	  *     requestid
	  *     qr_code
	  *     count
	  *]
	  **/
	 private function consume($config=[],$param=[]){
		  $data = [
		    'app_key' => $this->appkey,
		    'timestamp' => date('Y-m-d H:i:s'),
		    'sign_method' => 'MD5',
		    'format' => 'json',
		    'v' => 1,
		    'session' => $config['session'],
		  ];
		  $arr = [
		   'requestid'=>$param['requestid'],
		   'receipt_code' =>$param['qr_code'],
		   'open_shop_uuid' =>$config['open_shop_uuid'],
		   'count'=>$param['count'],
		   'app_shop_account' =>$param['qr_code'],
		   'app_shop_accountname' =>$param['qr_code'],
		  ];
		  $data = array_merge($data, $arr);
		  ksort($data);
		  $sign = $this->cal_sign($this->secret, $data);//获取签名
		  $data['sign'] = $sign;
		  $data = array_merge($data, $arr);
		  $postdata = http_build_query($data);
		  $url = 'https://openapi.dianping.com/router/tuangou/receipt/consume';//验券
		  $tmpInfo=$this->httpRequest($url,"POST",$data);
		  return $tmpInfo;
	 }
 
	 //获取session
	public function get_session($auth_code=''){
		  $app_key=$this->appkey;
		  $app_secret=$this->secret;
		  $grant_type='authorization_code';
		  $redirect_url=request()->domain()."/meituan.php";
		  $data=[
		   'app_key' =>$app_key,
		   'app_secret' => $app_secret,
		   'redirect_url' =>$redirect_url,
		   'auth_code' =>$auth_code,
		   'grant_type' =>$grant_type
		  ];
		  $url='https://openapi.dianping.com/router/oauth/token';
		  $tmpInfo=$this->httpRequest($url,"POST",$data);
		  return $tmpInfo;
	 }

	//获取所有店铺的id
	 public function getShopid($session='',$bid=''){
		  $app_key= $this->appkey;
		  $secret = $this->secret; //秘钥
		  $sign_method='MD5';
		  $timestamp = date('Y-m-d H:i:s');
		  $format = 'json';
		  $v = 1;
		  // //$session = 'f44d594ab895c******85b70bade02c';
		  // $session = '6d9f986b7238a578e2b0084ef3a5380d37d0d767';
		  // $bid='43d7934c9987f743545749a2bfe0a506';//和session一起返回的
		  $offset =0;
		  $limit = 20;
		  $url='https://openapi.dianping.com/router/oauth/session/scope?';
		  $data=[
		   'app_key' =>$app_key,
		   'sign_method' => $sign_method,
		   'timestamp' =>$timestamp,
		   'format' =>$format,
		   'v' =>$v,
		   'session' =>$session,
		   'bid' =>$bid,
		   'offset' =>$offset,
		   'limit' =>$limit,
		  ];
		  ksort($data);
		  $sign = $this->cal_sign($secret, $data);
		  $data['sign'] = $sign;
		  $postdata = http_build_query($data);
		  //$tmpInfo=$this->curl_get($url.$postdata);
		  $temp=$this->httpRequest($url.$postdata,"GET");
		  return $temp;
	 }
	 /**
	  * 计算签名
	  *
	  * @param $app_secret 三方app_secret
	  * @param $req_param 请求参数集合，包括公共参数和业务参数
	  * @return string md5签名
	  */
	 function cal_sign($app_secret, $req_param)
	 {
		  // 排序所有请求参数
		  ksort($req_param);
		  $src_value = "";
		  // 按照key1value1key2value2...keynvaluen拼接
		  foreach ($req_param as $key => $value) {
		   $src_value .= ($key . $value);
		  }
		  //计算md5
		  return md5($app_secret . $src_value . $app_secret);
	 }

	 public function httpRequest($url="",$method="POST",$request=[],$header=["Content-Type: application/x-www-form-urlencoded"]){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt_array($curl, array(
          CURLOPT_URL => $url,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => $method,
          CURLOPT_POSTFIELDS => http_build_query($request),
          CURLOPT_HTTPHEADER => $header,
        ));
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
          return ['code'=>1,'msg'=>"cURL Error #:" . $err];
        } else {
          return json_decode($response,1);
        }
    }

}