<?php
class paybaoguan_sdk{

	static function send_request($channel, $request){
		$param = array(
			'channel' => $channel,
			'request' => is_string($request) ? $request : json_encode($request),
		);
		return self::curl_post(
			'{{REQUEST_URL}}', 
			$param
		);
	}

	static function send_response($channel, $param = array(),$extend = array()){
		if($channel == 'weixin'){
			$response = $param ? $param : file_get_contents('php://input');
		}else{
			$response = json_encode($param ? array_merge($_POST, $param) : $_POST);
		}
		if(!empty($response)){
			$param = array(
				'channel'  => $channel,
				'response' => $response,
			);
			$param =  array_merge($param,$extend);
			return self::curl_post(
				'{{RESPONSE_URL}}', 
				$param
			);
		}
		return 'fail';
	}

	static function curl_post($url = '', $data = array()){
		$postfield = $s = '';
		if(!empty($data)){
			if(is_array($data)){
				foreach($data as $k => $v){
					$postfield .= $s.$k.'='.rawurlencode($v);
					$s         = '&';
				}
			}
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; SeaPort/1.2; Windows NT 5.1; SV1; InfoPath.2)");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		if(stripos($url, 'https://') !== FALSE){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		}
		$value = curl_exec($ch);
		if(curl_errno($ch)){
		}
		curl_close($ch);
		return $value;
	}
}