<?php
/**
 * @copyright   2008-2020 伯乐发卡 <http://www.lailiyun.com>
 * @creatdate   2020-9-10 Mr wang <634273662@qq.com>
 * @version   伯乐发卡V3（个人自动发卡系统）
 */

require_once '../inc.php';

use BL\app\libs\Log;

    $model = '当面付';

$payconf = $payDao->checkAcp("1");

//支付宝公钥，账户中心->密钥管理->开放平台密钥，找到添加了支付功能的应用，根据你的加密类型，查看支付宝公钥
$alipayPublicKey=$payconf['ali_public_key'];
$aliPay = new AlipayService($alipayPublicKey);
//验证签名
$result = $aliPay->rsaCheck($_POST);
if($result===true){

    if($_POST['trade_status'] == "TRADE_SUCCESS"&&$_POST['app_id']==$payconf['app_id']){
        $res = $payDao->updateOrder($_POST['out_trade_no'],$model,$_POST['trade_no']);
        //处理你的逻辑，例如获取订单号$_POST['out_trade_no']，订单金额$_POST['total_amount']等
        //程序执行完后必须打印输出“success”（不包含引号）。如果商户反馈给支付宝的字符不是success这7个字符，支付宝服务器会不断重发通知，直到超过24小时22分钟。一般情况下，25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）；
        echo 'success';exit();
    }
    
}
    echo 'error';exit();

class AlipayService
{
    protected $alipayPublicKey;
    public function __construct($alipayPublicKey)
    {
        $this->alipayPublicKey=$alipayPublicKey;
    }
    /**
     *  验证签名
     **/
    public function rsaCheck($params) {
        if ($params['sign_type'] == 'RSA') {
            if (!$this->verify($this->getStr($params), $this->alipayPublicKey, $params['sign'])) {
              	return false;
			} else {
				return true;
            }
        } elseif ($params['sign_type'] == 'RSA2') {
            if (!$this->verify($this->getStr($params), $this->alipayPublicKey, $params['sign'], 'RSA2')) {
            	return false;
			} else {
				return true;
            }
        }
    }
	public function verify($data, $public_key, $sign, $type = 'RSA') {
        $search = [
            "-----BEGIN PUBLIC KEY-----",
            "-----END PUBLIC KEY-----",
            "\n",
            "\r",
            "\r\n"
        ];
        $public_key = str_replace($search, "", $public_key);
        $public_key = $search[0] . PHP_EOL . wordwrap($public_key, 64, "\n", true) . PHP_EOL . $search[1];
        $res = openssl_get_publickey($public_key);
        if ($res) {
            if ($type == 'RSA') {
                $result = (bool)openssl_verify($data, base64_decode($sign), $res);
            } elseif ($type == 'RSA2') {
                $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
            }
            openssl_free_key($res);
        } else {
            return false;
        }
        return true;
    }
    
    public function getStr($arr, $type = 'RSA')
    {
        //筛选  
        if (isset($arr['sign'])) {
            unset($arr['sign']);
        }
        if (isset($arr['sign_type']) && $type == 'RSA') {
            unset($arr['sign_type']);
        }
        //排序  
        ksort($arr);
        //拼接
        return $this->getUrl($arr, true);
    }
    
    public function getUrl($arr, $encode = true)
    {
        if ($encode) {
            return http_build_query($arr);
        } else {
            return urldecode(http_build_query($arr));
        }
    }
}
?>