<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ping {

	private $ci;

	public $base_url;
	public $apikey;
	public $app_id;
	public $charge;



	public function __construct(){
		$this->ci = &get_instance();
		$this->base_url = 'https://api.pingxx.com/v1/charges';  //http无稳定，应当使用https，服务若无应当安装
		$this->ci->load->model('Pay_model','pay');
		$info = $this->ci->pay->get();
		$this->apikey = $info['key'];
		$this->app_id = $info['appid'];

	}

	public function createCharge($ordernumber, $amount, $channle, $subject, $body){
		$data = array(
	        'order_no'  => $ordernumber,
	        'amount'    => $amount,
	        'app'       => array('id' => $this->app_id),
	        'channel'   => $channle,
	        'currency'  => 'cny',
	        'client_ip' => $this->ci->input->ip_address(),
	        'subject'   => $subject,
	        'body'      => $body
	    );

	    $this->charge = $data;

	    return $data;
	}


	public function createHeader(){
		$header = array();
		$header[] = 'Authorization: Bearer ' . $this->apikey;
		$header[] = 'Content-type: application/json;charset=UTF-8';
		return $header;
	}

	public function request(){

		if(empty($this->app_id) || empty($this->apikey)){
			$this->ci->json('550', 'appid或apikey为空');
		}

		$ch = curl_init();  
		curl_setopt($ch, CURLOPT_URL, $this->base_url);  
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);  
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $this->createHeader());
		curl_setopt($ch, CURLOPT_POST, 1);  
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->charge));
		$ret = curl_exec($ch);  
		if(!$ret){
			$message = curl_error($ch);
			echo $message;exit;
		}
		curl_close($ch); 

		return $ret; 
	}









}