<?php
namespace wstshop\mobile\controller;
use think\Loader;
use wstshop\common\model\Payments as M;
use wstshop\common\model\Orders as OM;
use wstshop\common\model\LogMoneys as LM;
use wstshop\common\model\ChargeItems as CM;
/**
 * ============================================================================
 * wstshop多用户商城
 * 版权所有 2016-2066 广州商淘信息科技有限公司，并保留所有权利。
 * 官网地址:http://www.wstshop.net
 * 交流社区:http://bbs.shangtao.net
 * 联系QQ:153289970
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 微信支付控制器
 */
class Weixinpays extends Base{
	
	/**
	 * 初始化
	 */
	private $wxpayConfig;
	private $wxpay;
	public function _initialize() {
		header ("Content-type: text/html; charset=utf-8");
		Loader::import('wxpay.WxPayConf');
		Loader::import('wxpay.WxJsApiPay');
		
		$this->wxpayConfig = array();
		$m = new M();
		$this->wxpay = $m->getPayment("weixinpays");
		$this->wxpayConfig['appid'] = $this->wxpay['appId']; // 微信公众号身份的唯一标识
		$this->wxpayConfig['appsecret'] = $this->wxpay['appsecret']; // JSAPI接口中获取openid
		$this->wxpayConfig['mchid'] = $this->wxpay['mchId']; // 受理商ID
		$this->wxpayConfig['key'] = $this->wxpay['apiKey']; // 商户支付密钥Key
		$this->wxpayConfig['notifyurl'] = url("mobile/weixinpays/notify","",true,true);
		$this->wxpayConfig['curl_timeout'] = 30;
		$this->wxpayConfig['returnurl'] = url("mobile/orders/index","",true,true);
		// 初始化WxPayConf
		new \WxPayConf($this->wxpayConfig);
	}
	

	public function toPay(){
		$data = [];
	    $payObj = input("payObj/s");
		$returnurl = "";
	    if($payObj=="recharge"){
	    	$returnurl = url("mobile/logmoneys/usermoneys","",true,true);
	    	$cm = new CM();
	    	$itemId = (int)input("itemId/d");
	    	$targetType = 0;
	    	$targetId = (int)session('WST_USER.userId');
	    	$needPay = 0;
	    	if($itemId>0){
	    		$item = $cm->getItemMoney($itemId);
	    		$needPay = isSet($item["chargeMoney"])?$item["chargeMoney"]:0;
	    	}else{
	    		$needPay = (int)input("needPay/d");
	    	}
	    	$out_trade_no = (int)input("trade_no");
	    	$lm = new LM();
	    	$log = $lm->getLogMoney(['targetType'=>$targetType,'targetId'=>$targetId,'dataId'=>$out_trade_no,'dataSrc'=>4]);
	    	if(!empty($log)){
	    		header("Location:".$returnurl);
				exit();
	    	}
	    	$body = "钱包充值";
	    	$data["status"] = $needPay>0?1:-1;
	    	$attach = $payObj."@".$targetId."@".$targetType."@".$needPay."@".$itemId;
	    	
			
	    }else{
			$orderId = (int)WSTBase64urlDecode(input("pkey"));
			$m = new OM();
			$userId = (int)session('WST_USER.userId');
			$obj["userId"] = $userId;
			$obj["orderId"] = $orderId;
			$order = $m->getPayOrders($obj);
			$totalAmount = $order["needPay"];
			$payRand = $order["payRand"];
		
			$out_trade_no = $obj["orderId"]."a1".$payRand;
			$needPay = WSTBCMoney($totalAmount,0,2);
			$body = "支付订单";
			$attach = $userId."@".$obj["orderId"];
			$returnurl = url("mobile/orders/index","",true,true);
			$rs = $m->getByUnique('3',0,$orderId);
			$this->assign('rs',$rs);
		}
		if($needPay==0){
			header("Location:".$returnurl);
			exit();
		}

		//使用统一支付接口
		$unifiedOrder = new \UnifiedOrder();
		$notify_url = $this->wxpayConfig ['notifyurl'];
	
		//自定义订单号，此处仅作举例
		$unifiedOrder->setParameter("out_trade_no",$out_trade_no);//商户订单号
		$unifiedOrder->setParameter("notify_url",$notify_url);//通知地址
		$unifiedOrder->setParameter("trade_type","MWEB");//交易类型
	
		$unifiedOrder->setParameter("body",$body);//商品描述
		$unifiedOrder->setParameter("total_fee", $needPay * 100);//总金额
		$unifiedOrder->setParameter("attach",$attach);//附加数据
	
		$wap_name = WSTConf('CONF.mallName');
    	$unifiedOrder->setParameter("scene_info", "{'h5_info': {'type':'Wap','wap_url': '".$notify_url."','wap_name': '".$wap_name."'}}");//总金额

    	$this->assign('needPay',$needPay);
	    $this->assign('returnUrl',$returnurl );
	    $this->assign('payObj',$payObj);
	   	$wxResult = $unifiedOrder->getResult();
	    $this->assign('mweb_url',$wxResult['mweb_url']."&redirect_url".urlencode($returnurl));
	    
		return $this->fetch('users/orders/orders_wxpay');
	}
	
	
	
	public function notify() {
		// 使用通用通知接口
		$notify = new \Notify();
		// 存储微信的回调
		$xml = file_get_contents("php://input");
		$notify->saveData ( $xml );
		if ($notify->checkSign () == FALSE) {
			$notify->setReturnParameter ( "return_code", "FAIL" ); // 返回状态码
			$notify->setReturnParameter ( "return_msg", "签名失败" ); // 返回信息
		} else {
			$notify->setReturnParameter ( "return_code", "SUCCESS" ); // 设置返回码
		}
		$returnXml = $notify->returnXml ();
		if ($notify->checkSign () == TRUE) {
			if ($notify->data ["return_code"] == "FAIL") {
				// 此处应该更新一下订单状态，商户自行增删操作
			} elseif ($notify->data ["result_code"] == "FAIL") {
				// 此处应该更新一下订单状态，商户自行增删操作
			} else {
				$order = $notify->getData ();
				$rs = $this->process($order);
				if($rs["status"]==1){
					echo "SUCCESS";
				}else{
					echo "FAIL";
				}
			}
		}
	}
	
	//订单处理
	private function process($order) {
	
		$obj = array();
		$obj["trade_no"] = $order['transaction_id'];
		$obj["total_fee"] = (float)$order["total_fee"]/100;
		$extras =  explode ( "@", $order ["attach"] );
		
		if($extras[0]=="recharge"){//充值
			$targetId = (int)$extras [1];
			$targetType = (int)$extras [2];
			$itemId = (int)$extras [4];

			$obj["out_trade_no"] = $order['out_trade_no'];
			$obj["targetId"] = $targetId;
			$obj["targetType"] = $targetType;
			$obj["itemId"] = $itemId;
			$obj["payFrom"] = 'weixinpays';
			// 支付成功业务逻辑
			$m = new LM();
			$rs = $m->complateRecharge ( $obj );
		}else{
			$obj["userId"] = $extras[0];
			$obj["out_trade_no"] = $extras[1];
			$obj["payFrom"] = "weixinpays";
			
			// 支付成功业务逻辑
			$m = new OM();
			$rs = $m->complatePay ( $obj );
		}
		return $rs;
		
	}

}
