验签类RSA.php
<?php
namespace App\Library;
class RSA{
/**
* RSA签名
* @param $data 待签名数据
* @param $private_key 私钥字符串
* return 签名结果
*/
function rsaSign($data, $private_key,$type = 'RSA') {
$search = [
"-----BEGIN RSA PRIVATE KEY-----",
"-----END RSA PRIVATE KEY-----",
"\n",
"\r",
"\r\n"
];
$private_key=str_replace($search,"",$private_key);
$private_key=$search[0] . PHP_EOL . wordwrap($private_key, 64, "\n", true) . PHP_EOL . $search[1];
$res=openssl_get_privatekey($private_key);
if($res)
{
if($type == 'RSA'){
openssl_sign($data, $sign,$res);
}elseif($type == 'RSA2'){
//OPENSSL_ALGO_SHA256
openssl_sign($data, $sign,$res,OPENSSL_ALGO_SHA256);
}
openssl_free_key($res);
}else {
exit("私钥格式有误");
}
$sign = base64_encode($sign);
return $sign;
}
/**
* RSA验签
* @param $data 待签名数据
* @param $public_key 公钥字符串
* @param $sign 要校对的的签名结果
* return 验证结果
*/
function rsaCheck($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{
exit("公钥格式有误!");
}
return $result;
}
}
?>
基础类Alipay.php
<?php
namespace App\Library;
class Alipay extends RSA{
/**
* 以下信息需要根据自己实际情况修改
*/
const PID = '123456787293293730';//'支付宝后台获取 合作伙伴ID'
const PAYGAGEWAY = '/gateway.do';
const CHECKURL = '/gateway.do?service=notify_verify&partner=' . self::PID . '¬ify_id=';
const APPPRIKEY = '3445dsdsddBAQEFAASCBKcwggSjAgEAAoIBAQCAB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MizWkVVcTwnGwMOG2Q8Ef4h2SiGQ3YuLQt97n0pKIRST9QRfTJgLU/TzLBOpvaasPmUQfGcTOUZDyw/QYtJuJCEgHfj19SiAq5h2iRB+beRnntfEyD6cxTzi6Ts+fg1GGB/LfAHOBqBrrsw/ovA7dAoGBAIyOez0t4Y+ivHr63E5tkBMR/RCXF4+9pTqpCKwDtV7Jsp+3YH2tqb/AFA02UuXogB9bhtDjl/6KI+DiL2my23woJWlOx7Z479qaJplFsjP0QjVeGDk//ORH3t8CxECmkDqmjnFtiNAmc5AlGfQNT1uCebEjfZkA2EQt6FA4cS1RAoGAdU4hbkhtA2AnueaYQR6uGFBbfbFhxVdvt6ZgbPIV40cvGksVJTT78e8vkCm+i7+gHR3bkIVTLEHuNugy4mCbvtWJ8LW4c/B/llsjT8NZedCCLfbpy3X4VaAd6LvuJ1F7dmRr8zSaoD3ruz2cCW+QdWYlNmNO7B8jojUs+YmUSlk=';//应用私钥
const APPID = '12121212680043';//应用APPID;
const NEW_ALIPUBKE = 'dfdserrgfdfdesre45qGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB';//支付宝公钥
const NEW_PAYGATEWAY = '/gateway.do';
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,false);
}
//将数组转换为url格式的字符串
public function getUrl($arr,$encode = true){
if($encode){
return http_build_query($arr);
}else{
return urldecode(http_build_query($arr));
}
}
//获取签名MD5
public function getSign($arr){
return md5($this->getStr($arr) . self::KEY );
}
//获取含有签名的数组MD5
public function setSign($arr){
$arr['sign'] = $this->getSign($arr);
return $arr;
}
//获取签名RSA
public function getRsaSign($arr){
return $this->rsaSign($this->getStr($arr), self::APPPRIKEY) ;
}
//获取含有签名的数组RSA
public function setRsaSign($arr){
$arr['sign'] = $this->getRsaSign($arr);
return $arr;
}
//获取签名RSA2
public function getRsa2Sign($arr){
return $this->rsaSign($this->getStr($arr,'RSA2'), self::APPPRIKEY,'RSA2') ;
}
//获取含有签名的数组RSA
public function setRsa2Sign($arr){
$arr['sign'] = $this->getRsa2Sign($arr);
return $arr;
}
//记录日志
public function logs($filename,$data){
file_put_contents('/www/paylog/'.$filename, $data . "\r\n",FILE_APPEND);
}
//2.验证签名
public function checkSign($arr){
$sign = $this->getSign($arr);
if($sign == $arr['sign']){
return true;
}else{
return false;
}
}
//验证是否来之支付宝的通知
public function isAlipay($arr){
$str = file_get_contents(self::CHECKURL . $arr['notify_id']);
if($str == 'true'){
return true;
}else{
return false;
}
}
// 4.验证交易状态
public function checkOrderStatus($arr){
if($arr['trade_status'] == 'TRADE_SUCCESS' || $arr['trade_status'] == 'TRADE_FINISHED'){
return true;
} else {
return false;
}
}
}
?>
项目中生成支付二维码接口
/*发起支付宝支付请求
@author tjg
@param string order_no 订单号
@param string user_id用户id
@param string total_amount 订单金额(单位:分)
@param string desc订单描述
@return json
*/
public function sendAliPay($param=''){
if(!empty($param['total_amount'])){
$total_amount=$param['total_amount']/100;
}else{
$total_amount=0.01;
}
if(!empty($param['desc'])){
$subject=$param['desc'];
}else{
$subject='新版支付宝支付';
}
$order_no=$param['order_no'];//订单号
$user_id=$param['user_id'];//用户id
$order_money=$total_amount;//订单金额
$Alipay=new Alipay();
//公共参数
$pub_params = [
'app_id' => config('auth.alipay.APP_ID'),
'method' => 'alipay.trade.page.pay', //接口名称 应填写固定值alipay.trade.page.pay
'format' => 'JSON', //目前仅支持JSON
// 'return_url' => Env('APP_URL').'/fontend/pay/sendAliRE', //同步返回地址
'charset' => 'UTF-8',
'sign_type' => 'RSA2',//签名方式
'sign' => '', //签名
'timestamp' => date('Y-m-d H:i:s'), //发送时间 格式0000-00-00 00:00:00
'version' => '1.0', //固定为1.0
'notify_url' => Env('APP_URL').'/fontend/pay/sendAliNO', //异步通知地址
'biz_content' => '', //业务请求参数的集合
];
$passback_params=UrlEncode('order_no='.$order_no.'&user_id='.$user_id.'&order_money='.$order_money);
//业务参数
$api_params = [
'out_trade_no' => date('YmdHis'),//商户订单号
'product_code' => 'FAST_INSTANT_TRADE_PAY', //销售产品码 固定值
'total_amount' =>$total_amount, //总价 单位为元
'subject' => $subject, //订单标题
'qr_pay_mode'=>4,
'passback_params'=>$passback_params,
];
$pub_params['biz_content'] = json_encode($api_params,JSON_UNESCAPED_UNICODE);
$pub_params = $Alipay->setRsa2Sign($pub_params);
//支付二维码地址
$url = config('auth.alipay.NEW_PAYGATEWAY') . '?' . $Alipay->getUrl($pub_params);
if(!empty($url)){
$data['alipay_code']=$url;
}else{
$data['alipay_code']='';
}
return json_encode(['code'=>0,'msg'=>'请求成功','data'=>$data]);
}
异步回调处理数据库
/*支付宝异步通知地址
@author tjg
@return json
*/
public function sendAliNO($result=''){
$Alipay=new Alipay();
$resultDecode=urldecode($result);
parse_str($resultDecode,$arr);
$json_return=json_encode($arr);
$passback_params=$arr['passback_params'];
$passback_params_arr=explode('&',$passback_params);
$order_no=$passback_params_arr[0];
$order_no_arr=explode('=',$order_no);
//平台订单号
$order_no_val=$order_no_arr[1];
$user_id=$passback_params_arr[1];
$user_id_arr=explode('=',$user_id);
//用户id
$user_id_val=$user_id_arr[1];
$order_money=$passback_params_arr[2];
$order_money_arr=explode('=',$order_money);
$order_money_val=$order_money_arr[1];
//支付金额(单位:分)
$paid_amount=$order_money_val*100;
//支付类型
$pay_type='ALI_PAY';
//判断是否支付成功
if($arr['trade_status']=='TRADE_SUCCESS'){
$addTrade['trade_no']=$arr['out_trade_no'];
$addTrade['pay_id']=2;
$addTrade['subject']='购买商品';
$addTrade['body']='购买商品';
$addTrade['price']=$paid_amount;
$addTrade['pay_amount']=$arr['total_amount']*100;
$addTrade['receipt_amount']=$arr['total_amount']*100;
$addTrade['trade_status']=1;
$addTrade['pay_time']=date('Y-m-d H:i:s',time());
$addTrade['create_at']=date('Y-m-d H:i:s',time());
$addTrade['row_data']=$result;
$addTrade['order_no']=$order_no_val;
DB::table('info_pay_trade')->insert($addTrade);
$strsuccess=date('Y-m-d H:i:s',time()).'异步通知结果写入时间'.$json_return;
$filename='alipaysuccess.txt';
$Alipay->logs($filename,$strsuccess);
$ret = OrderService::payFinished($order_no_val,$user_id_val,$paid_amount, $pay_type);
echo "success";
}else{
$addTrade['trade_no']=$arr['out_trade_no'];
$addTrade['pay_id']=2;
$addTrade['subject']='购买商品';
$addTrade['body']='购买商品';
$addTrade['price']=$order_money_val;
$addTrade['pay_amount']=$arr['total_amount']*100;
$addTrade['receipt_amount']=$arr['total_amount']*100;
$addTrade['trade_status']=2;
$addTrade['pay_time']=date('Y-m-d H:i:s',time());
$addTrade['create_at']=date('Y-m-d H:i:s',time());
$addTrade['row_data']=$result;
DB::table('info_pay_trade')->insert($addTrade);
$strfail=date('Y-m-d H:i:s',time()).'异步通知结果写入时间'.$json_return;
$filename='alipayfail.txt';
$Alipay->logs($filename,$strfail);
echo "success";
}
}