<?php

namespace app\api\controller;

header('Access-Control-Allow-Origin: *');

use app\BaseController;

use think\facade\Db; // 数据库的链接

use think\facade\Cache;

use think\facade\Log;

class Pay extends BaseController

{

    const PAY_URL = 'https://paygateway.stmshopping.com/api/pay/unifiedOrderH5';

    const AppID = ''; // 

    const MERCHANT_NO = '';

    const KEY_MD5 = '';

    

    public function pay()

    {

        $post = input();

        $UID = request()->UID;

        $data = array(

            'ordersn' =>ordersn('cz',$UID),

            'uid' => $UID,

            'money' => $post['inputNum'],

            'is_state' => 0,

            'addto_time' => time(),

        );

        Db::name('recharge')->insert($data);

        $res = $this->pays($data);

        return json(['code' => 200 ,'data' => $res['data']]);

    }

    

    public function pays($data)

    {

        $user = DB::name('user')->where('id',1)->find();

        $price = $data['money'];

        $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/api/notify_url?ordersn='.$data['ordersn'];

        $return_url = 'https://'.$_SERVER['HTTP_HOST'].'/api/notify_url?ordersn='.$data['ordersn']; // 跳转地址

        $param["amount"] = (int)$price. '';

        $param["mchOrderNo"] = $data['ordersn']. '';

        $param["subject"] = '充值积分';

        $param["wayCode"] = '';

        $param["appId"] = self::AppID. '';

        $param["signType"] = "MD5";

        $param["currency"] = "cny";

        $param["reqTime"] = time();

        $param["body"] =  '充值积分';

        $param["mchNo"] = self::MERCHANT_NO. '';

        $param["version"] = "1.0";

        $param["mbrTel"] = '18888888888';

        $param["notifyUrl"] = $notify_url;

        $param["returnUrl"] = $return_url;

        ksort($param);  //字典排序

        reset($param);

        $md5str = "";

        foreach ($param as $key => $val) {

            if( strlen($key)  && strlen($val) ){

                $md5str = $md5str . $key . "=" . $val . "&";

            }

        }

        $param['sign'] = strtoupper(md5($md5str . "key=" . self::KEY_MD5));  //签名

        // 验签方式 MD5

        $res = $this->HttpRequest(self::PAY_URL,$param);

        $resk = json_decode($res,true);

        return $resk;

    }

    

    public function HttpRequest($url, $data)

    {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_FAILONERROR, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    

        $body_string = '';

        if(is_array($data) && 0 < count($data))

        {

            foreach($data as $k => $v)

            {

                $body_string .= $k.'='.urlencode($v).'&';

            }

            curl_setopt($ch, CURLOPT_POST, true);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $body_string);

        }

        $headers = array('content-type: application/x-www-form-urlencoded;charset=UTF-8');

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $reponse = curl_exec($ch);

        if(curl_errno($ch))

        {

            return false;

        } else {

            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            if(200 !== $httpStatusCode)

            {

                return false;

            }

        }

        curl_close($ch);

        return $reponse;

    }

    public function notify_url()

    {

        $post = input();

        $order = DB::name('recharge')->where('ordersn',$post['ordersn'])->find();

        if($order['is_state'] == 0){

            Db::name('recharge')->where('ordersn',$post['ordersn'])->update(['is_state' => 1]);

            Db::name('user')->where('id',$order['uid'])->inc('balance',$order['money'])->update();

            //  * uid 用户id

            //  * type 	0提现 1消费 2收益 3充值

            //  * number 操作金额数量

            //  * operation_type 0加 1减

            //  * is_state 0待处理 1完成 2拒绝

            //  * notes 操作备注

            Balancerecord($order['uid'],3,$order['money'],0,1,'充值',0);

        }

    }

}