<?php
namespace Api\Controller;

use Think\Controller;
class IndexController extends Controller {

	// 初始化
	public function _initialize()
	{
		header("Content-type: text/html; charset=utf-8");
		vendor('ali.f2fpay.model.builder.AlipayTradePrecreateContentBuilder');
		vendor('ali.f2fpay.service.AlipayTradeService');
		vendor('ali.f2fpay.model.builder.AlipayTradeRefundContentBuilder');//引入退款文件
	}



	// 二维码的生成
	public function index(){


		$config=C('config');
		// var_dump($config);
		// 需保证商户系统端不能重复，建议通过数据库sequence生成，
		$outTradeNo = "qrpay".date('Ymdhis').mt_rand(100,1000);

		// $subject = $_POST['subject'];
		$subject ='自助售货机支付';

		// $totalAmount = $_POST['total_amount'];
		$totalAmount ='0.01';

		// 支付超时，线下扫码交易定义为5分钟
		$timeExpress = "5m";


		// 创建请求builder，设置请求参数
		$qrPayRequestBuilder = new \AlipayTradePrecreateContentBuilder();
		$qrPayRequestBuilder->setOutTradeNo($outTradeNo);
		$qrPayRequestBuilder->setTotalAmount($totalAmount);
		$qrPayRequestBuilder->setTimeExpress($timeExpress);
		$qrPayRequestBuilder->setSubject($subject);

		// 调用qrPay方法获取当面付应答
		$qrPay = new \AlipayTradeService($config);


		$qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);

		//  根据状态值进行业务处理
		switch ($qrPayResult->getTradeStatus()){
			case "SUCCESS":
				// echo "支付宝创建订单二维码成功:"."<br>---------------------------------------<br>";
				$response = $qrPayResult->getResponse();
				$qrcode = $qrPay->create_erweima($response->qr_code);
				$url=$response->qr_code;
				// $arr=array(
				//   'order'=>'1234566',
				//    'url'=>$url,
				//   );
				// echo json_encode($arr);
				//   // echo $qrcode;
				//   // print_r($response);
				$this->assign('outTradeNo',$outTradeNo);
				$this->assign('qrcode',$url);
				$this->display();
				break;
			case "FAILED":
				echo "支付宝创建订单二维码失败!!!"."<br>--------------------------<br>";
				if(!empty($qrPayResult->getResponse())){
					print_r($qrPayResult->getResponse());
				}
				break;
			case "UNKNOWN":
				echo "系统异常，状态未知!!!"."<br>--------------------------<br>";
				if(!empty($qrPayResult->getResponse())){
					print_r($qrPayResult->getResponse());
				}
				break;
			default:
				echo "不支持的返回状态，创建订单二维码返回异常!!!";
				break;
		}
		return ;



}