<?php
namespace Meituan;
class Dianping{
	private $api_url="https://openapi.dianping.com/router";
	private $appkey="370926cf832f39e3";
	private $secret="a10badba03f3cb7a4c00ba28a5c160e3dfaaa137";
	public function __construct($config=[]){

	}
	//获取session
	public function getAccessToken(){
		$url=$this->api_url."/oauth/token";
		$res=self::httpRequest($url,"POST",[
			'app_key'=>$this->appkey,
			'app_secret'=>$this->secret,
			'grant_type'=>'authorize_platform'
		]);
		p($res);
	}
	public function tuangouReceiptPrepare(){
		$url=$this->api_url."/tuangou/receipt/prepare";
		$param['app_key']=$this->appkey;
		$param['timestamp']=date('Y-m-d H:i:s');
		$param['session']="0861d2b1741689ed3a60743d93369db719d1ff79";
		$param['format']="json";
		$param['v']='1';
		$param['sign_method']="MD5";
		$param['receipt_code']="1456465465";
		$param['sign']=self::createSign($param);
		
		$res=self::httpRequest($url,"POST",$param);
		p($param);
		p($res);
	}      
	      
	/**
	 * 创建签名
	 *
	 * @param $app_secret 三方app_secret
	 * @param $req_param 请求参数集合，包括公共参数和业务参数
	 * @return string md5签名
	 */
	private function createSign($param=[]){
	    // 排序所有请求参数
	    ksort($param);
	    $srcValue = "";
	    // 按照key1value1key2value2...keynvaluen拼接
	    foreach ($param as $key=>$value){
	        $srcValue.=($key.$value);
	    }
	    //计算md5
	    return md5($this->secret.$srcValue.$this->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);
        }
    }
}