<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: YingZi
// +----------------------------------------------------------------------
// | Date: 2022-05-27 15:14
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace library\utils;
use WeChatPay\Builder;
use WeChatPay\Formatter;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Util\PemUtil;
use WeChatPay\Request\WeChatPayTradeOutTradeNoQueryRequest;

class weixinPay{
    private $config;
    private $client;
    public $errorMsg="系统错误";
    private $merchantPrivateKeyInstance="";
    /**
     * 构造函数
     * @param type $config
     */
    public function __construct($config = [])
    {
        if(empty($config)) $config = config('wxpay');
        $this->config = $config;
        //「商户API私钥文件」
        $merchantPrivateKeyFilePath = $this->config["PrivateKey"];//示例:file:///path/to/merchant/apiclient_key.pem
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);//「商户API私钥」
        $merchantCertificateSerial = $this->config["merchantSerialNumber"];//商户API证书」的「证书序列号」示例:'3775B6A45ACD588826D15E583A95F5DD********';
        // 「微信支付平台证书」
        $platformCertificateFilePath = $this->config["Certificate"];//示例:file:///path/to/wechatpay/cert.pem
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);//
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);//「微信支付平台证证书序列号」
        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid'      => $this->config["MCHID"],
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);
        $this->merchantPrivateKeyInstance = $merchantPrivateKeyInstance;
        $this->client = $instance;
    }
    /**
     * 微信小程序支付
     * @param type $post
     */
    public function wxmpPay($post=[]){
        $apiUrl = "v3/pay/transactions/jsapi";
        $jsonData = [];
        //商户信息
        $jsonData["appid"] = $this->config["APPID"];
        $jsonData["mchid"] = $this->config["MCHID"];
        $jsonData["notify_url"] = $this->config["NOTIFY_URL"];
        //必填参数
        $jsonData["description"] = $post["description"];//描述
        $jsonData["out_trade_no"] = $post["out_trade_no"];//商户订单号
        $jsonData["amount"] = [
            "total"=> (int)(floatval($post["total"])*100),//订单金额，分
            "currency" => 'CNY'
        ];
        $jsonData["scene_info"] = [//支付场景描述
            "payer_client_ip"=>empty($post["payer_client_ip"])?"127.0.0.1":$post["payer_client_ip"],//客户端IP
        ];
        $jsonData["time_expire"] = date("Y-m-d\TH:i:s+08:00",time()+30*60);//交易结束时间2018-06-08T10:34:56+08:00
        $jsonData["payer"]=[
            "openid"=>$post["openid"]
        ];
        $result = $this->clientHttp("POST", $apiUrl, $jsonData);
        if(empty($result)){
            if(empty($this->errorMsg)){
                $this->errorMsg = "支付错误001";
            }
            return false;
        }
        $resuleAr = json_decode($result,true);
        if(empty($resuleAr)){
            if(empty($this->errorMsg)){
                $this->errorMsg = "支付错误002";
            }
            return false;
        }
        if(empty($resuleAr["prepay_id"])){
            if(empty($this->errorMsg)){
                $this->errorMsg = "支付错误003";
            }
            return false;
        }
        //组装支付参数
        $payInfo=array();
        $data=$this->makeSign(["appId"=>$this->config["APPID"],"prepay_id"=>$resuleAr["prepay_id"]]);
        $data["payData"] = $jsonData;
        return $data;
    }
    /**
     * 查询订单
     * @param type $out_trade_no 商户订单号
     */
    public function searchOrder($out_trade_no){
        $apiUrl = "v3/pay/transactions/out-trade-no/{out_trade_no}";
        $result = $this->clientHttp("GET", $apiUrl,[
            "out_trade_no"=>$out_trade_no,
            "query"=>["mchid"=>$this->config["MCHID"]],
        ]);
        return $result;
    }
    /**
     * 关闭订单
     * @param type $out_trade_no 商户订单号
     */
    public function closeOrder($out_trade_no){
        $apiUrl = "v3/pay/transactions/out-trade-no/{out_trade_no}/close";
        $result = $this->clientHttp("GET", $apiUrl,[
            "out_trade_no"=>$out_trade_no,
            "query"=>["mchid"=>$this->config["MCHID"]],
        ]);
        return $result;
    }
    /**
     * 生成签名
     * @param type $info
     * @return string
     */
    private function makeSign($info){
        $params = [
            'appId'     => $info["appId"],
            'timeStamp' => (string)Formatter::timestamp(),
            'nonceStr'  => Formatter::nonce(),
            'package'   => 'prepay_id='.$info["prepay_id"],
        ];
        $params["paySign"] = Rsa::sign(Formatter::joinedByLineFeed(...array_values($params)),$this->merchantPrivateKeyInstance);
        $params["signType"] = 'RSA';
        return $params;
    }
    /**
     * 解密回调参数
     * @param type $data
     * @return type
     */
    public function aesGcmDecrypt($data){
        // 加密文本消息解密
        $inBodyResource = AesGcm::decrypt($data["ciphertext"], $this->config["apiv3Key"], $data["nonce"], $data["associated_data"]);
        // 把解密后的文本转换为PHP Array数组
        $inBodyResourceArray = (array)json_decode($inBodyResource, true);
        return $inBodyResourceArray;
    }
    /**
     * http提交[同步请求]
     * @param type $type
     * @param type $url 示例:v3/pay/transactions/native
     * @param type $json
     * @return boolean
     */
    private function clientHttp($type='POST',$url='',$json=[]){
        try {
            $resp=null;
            if($type=="POST"){
                $resp = $this->client->chain($url)->post(['json' => $json]);
                if(empty($json)){
                    $resp = $this->client->chain($url)->post();
                }else{
                    $resp = $this->client->chain($url)->post(['json' => $json]);
                }
            }
            if($type=="GET"){
                if(empty($json)){
                    $resp = $this->client->chain($url)->get();
                }else{
                    $resp = $this->client->chain($url)->get($json);
                }
            }
            if(empty($resp)){
                $this->errorMsg="提交方式错误";
                return false;
            }
            $statusCode =  $resp->getStatusCode();
            if ($statusCode == 200) { //处理成功
                return $resp->getBody()->getContents();
            } else if ($statusCode == 204) { //处理成功，无返回Body
                $this->errorMsg = "处理成功，无返回Body";
                return false;
            }else{
                $this->errorMsg = "未知错误";
                return false;
            }
        } catch (\Exception $e) {
            // 进行错误处理
            $this->errorMsg =  $e->getMessage();
            if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                $r = $e->getResponse();
                $this->errorMsg=$r->getStatusCode()."".$r->getReasonPhrase().$r->getBody();
            }
            return false;
        }
    }
    
}

