PHP支付宝登录

composer.json加入:
"require": {
"alipaysdk/easysdk": "^2.2",
}

composer 下载:composer require alipaysdk/easysdk;

主要文件:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/8/4
 * Time: 16:47
 */

namespace App\Services;

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;

class AliPayLoginService
{
    protected $app_id;
    protected $pid = 2088041118872222;
    protected $private_key;
    protected $ali_public_key; //


    public function __construct()
    {
//        $config = config('pay.YanSongDa.Alipay');
//        $this->app_id = $config['app_id'];
//        $this->pid = 2088041118872222;
//        $this->private_key = $config['private_key'];
//        $this->ali_public_key = $config['ali_public_key'];
    }

    public function init($type)
    {
  
            $this->app_id = env("ALIPAY_PAYMENT_APPID");
            $this->private_key = env("ALIPAY_PRIVATE_KEY");
            $this->ali_public_key = env("ALIPAY_PUBLIC_KEY");
        

    }
    /*---------------------------------------------------【新版】------------------------------------------------------*/
    /**
     * 【新版】
     * auth_token获取用户信息
     * @param $auth_token
     * @return array
     * @throws \Exception
     */
    public function getUserInfo($auth_token)
    {
        if (!empty($auth_token)) {
            try {
                Factory::setOptions($this->getOptions());
                //设置系统参数(OpenAPI中非biz_content里的参数)
                $textParams = array(
                    "auth_token" => "{$auth_token}"
                );
                //设置业务参数(OpenAPI中biz_content里的参数)
                $bizParams = array();
                $resJson = Factory::util()->generic()->execute("alipay.user.info.share", $textParams, $bizParams)->httpBody;
                $resJsonToArray = json_decode($resJson, true);
                if (isset($resJsonToArray['alipay_user_info_share_response'])) {
                    if ($resJsonToArray['alipay_user_info_share_response']['code'] == "10000") {
                        $data = [
                            "avatar" => $resJsonToArray['alipay_user_info_share_response']['avatar'],
                            "city" => $resJsonToArray['alipay_user_info_share_response']['city'],
                            "gender" => $resJsonToArray['alipay_user_info_share_response']['gender'],
                            "nick_name" => $resJsonToArray['alipay_user_info_share_response']['nick_name'],
                            "province" => $resJsonToArray['alipay_user_info_share_response']['province'],
                            "user_id" => $resJsonToArray['alipay_user_info_share_response']['user_id'],
                        ];
                        return array("code" => 200, "msg" => "获取用户信息成功", "data" => $data);
                    } else {
                        throw new \Exception("{$resJsonToArray['alipay_user_info_share_response']['sub_msg']}");
                    }
                } else {
                    throw new \Exception("获取失败");
                }
            } catch (\Exception $exception) {
                throw new \Exception("{$exception->getMessage()}");
            }
        } else {
            return array("code" => 500, "msg" => "auth_token不能为空", "data" => null);
        }
    }

    /**
     * 【新版】
     * 通过前端返回的code获取auth_token
     * @param $code
     * @return array
     * @throws \Exception
     */
    public function getAuthToken($code)
    {
        if (!empty($code)) {
            try {
                Factory::setOptions($this->getOptions());
                // 方法一:
                // $resJson = Factory::base()->oauth()->getToken("{$code}")->httpBody;
                // 方法二:
                //设置系统参数(OpenAPI中非biz_content里的参数)
                $textParams = array(
                    "grant_type" => "authorization_code",
                    "code" => "{$code}",
                );

                //设置业务参数(OpenAPI中biz_content里的参数)
                $bizParams = array();
                $resJson = Factory::util()->generic()->execute("alipay.system.oauth.token", $textParams, $bizParams)->httpBody;
                //-------
                $resJsonToArray = json_decode($resJson, true);
                if (isset($resJsonToArray['alipay_system_oauth_token_response'])) {
                    return array("code" => 200, "msg" => "获取auth_token成功", "data" => $resJsonToArray['alipay_system_oauth_token_response']);
                } else {
                    throw new \Exception("{$resJsonToArray['error_response']['sub_msg']}");
                }
            } catch (\Exception $exception) {
                return array("code" => 500, "msg" => "{$exception->getMessage()}", "data" => null);
            }
        } else {
            return array("code" => 500, "msg" => "code不能为空", "data" => null);
        }
    }

    /**
     * 【新版】配置
     * @return Config
     */
    private function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = $this->app_id;

        // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = $this->private_key;
        //$options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径,例如:/foo/alipayCertPublicKey_RSA2.crt -->';
        //$options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径,例如:/foo/alipayRootCert.crt" -->';
        //$options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径,例如:/foo/appCertPublicKey_2019051064521003.crt -->';
        //注:如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可
        // $options->alipayPublicKey = '<-- 请填写您的支付宝公钥,例如:MIIBIjANBg... -->';
        $options->alipayPublicKey = $this->ali_public_key;

        //可设置异步通知接收服务地址(可选)
        // $options->notifyUrl = "";
        //可设置AES密钥,调用AES加解密相关接口时需要(可选)
        // $options->encryptKey = "";

        return $options;
    }

    /**
     * 返回给前端获取code
     * 【新旧都可用】
     * InfoStr APP登录需要的的infostr
     * @return String
     */
    public function infoStr()
    {
        $infoStr = http_build_query([
            'apiname' => 'com.alipay.account.auth',
            'method' => 'alipay.open.auth.sdk.code.get',
            'app_id' => $this->app_id,
            'app_name' => 'mc',
            'biz_type' => 'openservice',
            'pid' => $this->pid,
            'product_id' => 'APP_FAST_LOGIN',
            'scope' => 'kuaijie',
            'target_id' => time(), //商户标识该次用户授权请求的ID,该值在商户端应保持唯一
            'auth_type' => 'AUTHACCOUNT', // AUTHACCOUNT代表授权;LOGIN代表登录
            'sign_type' => 'RSA2',
        ]);
        $infoStr .= '&sign=' . $this->enRSA2($infoStr);
        return $infoStr;
    }

    /**
     * 【生成签名sign】
     * enRSA2 RSA加密
     * @param String $data
     * @return String
     */
    private function enRSA2($data)
    {
        $str = chunk_split(trim($this->private_key), 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
       // print_r($key);die;
        // $key = file_get_contents(storage_path('rsa_private_key.pem')); 为文件时这样引入
        $signature = '';
        //$signature = openssl_sign($data, $signature, $key, OPENSSL_ALGO_SHA256)?base64_encode($signature):NULL;
        $signature = openssl_sign($data, $signature, $key, OPENSSL_ALGO_SHA256) ? base64_encode($signature) : NULL;
        return $signature;
    }

    /*---------------------------------------------------【旧版】------------------------------------------------------*/
    /**
     * 【旧版】
     * AlipayToken 获得用户 请求token, 通过它获得 用户信息
     * 需要按照支付宝加签流程来。
     */
    public function userInfo($app_auth_token)
    {
        $infoArr = [
            'method' => 'alipay.system.oauth.token',
            'app_id' => $this->app_id,
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'code' => $app_auth_token,
            'grant_type' => 'authorization_code',
        ];

        $signStr = $this->myHttpBuildQuery($infoArr);
        $sign = urlencode($this->enRSA2($signStr));
        $qureStr = $signStr . '&sign=' . $sign;

        $res = new Client();
        $body = $res->get('https://openapi.alipay.com/gateway.do?' . $qureStr)->getBody()->getContents();
        $body = json_decode($body);
        if (!isset($body->alipay_system_oauth_token_response->access_token)) {
            return false;
        } else {
            $autho_token = $body->alipay_system_oauth_token_response->access_token;
            $userinfo = $this->aliPayUserInfo($autho_token);
            return $userinfo; // 或则 返回 json_encode($userinfo) 根据实际需求来
        }
    }

    /**
     * 【旧版】
     * AliPayUserInfo 通过 token 获取用户信息
     */
    private function aliPayUserInfo($autho_token)
    {
        $infoArr = [
            'method' => 'alipay.user.info.share',
            'app_id' => $this->app_id,
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'auth_token' => $autho_token,
        ];

        $signStr = $this->myHttpBuildQuery($infoArr);
        $sign = urlencode($this->enRSA2($signStr));
        $qureStr = $signStr . '&sign=' . $sign;

        $res = new Client();
        $body = $res->get('https://openapi.alipay.com/gateway.do?' . $qureStr)->getBody()->getContents();
        $body = json_decode($body);
        if (!isset($body->alipay_user_info_share_response)) {
            return '接口异常';
        }
        $body = $body->alipay_user_info_share_response;
        return $body;
    }

    /**
     * myHttpBuildQuery 返回一个 http Get 传参数组
     * 之所以不用 自带函数 http_build_query 时间带 ‘:’ 会被转换
     *
     * @param Array
     * @return String
     */
    private function myHttpBuildQuery($dataArr)
    {
        ksort($dataArr);
        $signStr = '';
        foreach ($dataArr as $key => $val) {
            if (empty($signStr)) {
                $signStr = $key . '=' . $val;
            } else {
                $signStr .= '&' . $key . '=' . $val;
            }
        }
        return $signStr;
    }
}

请求方法:

/**
     * 支付宝登陆获取InfoStr返回给前端用于获取code
     * @param AliPayLoginService $aliPayLoginService
     * @return JsonResponse
     */
    public function alipayInfoStr(AliPayLoginService $aliPayLoginService)
    {
        $aliPayLoginService->init(1);
        $infoStr = $aliPayLoginService->infoStr();
        return success($infoStr);
    }
 /**
     * 支付宝登陆获取auth_token
     * @param AliPayLoginService $aliPayLoginService
     * @param PhpJwtService $jwtService
     * @return JsonResponse|void
     * @throws Exception
     */
    public function alipayGetAuthToken(AliPayLoginService $aliPayLoginService, PhpJwtService $jwtService)
    {
        DB::beginTransaction();
        try {
            $code = request("code");
            $authKey = env('API_KEY');
            if (!empty($code)) {
                $aliPayLoginService->init(1);
                $res = $aliPayLoginService->getAuthToken($code);
                if ($res['code'] == 200) {
                    //其他操作 
                    DB::commit();
                    return otherReturn(200, "{$msg}", $data);
                } else {
                    DB::rollBack();
                    throw new \Exception("{$res['msg']}");
                }
            } else {
                DB::rollBack();
                throw new \Exception('code不能为空');
            }
        } catch (Exception $exception) {
            DB::rollBack();
            return fail("{$exception->getMessage()}");
        }
    }
 /**
     * 支付宝登陆--绑定账号/获取用户支付宝信息
     * @param AliPayLoginService $aliPayLoginService
     * @param PhpJwtService $phpJwtService
     * @return JsonResponse|void
     * @throws Exception
     */
    public function alipayGetUserInfo(AliPayLoginService $aliPayLoginService, PhpJwtService $phpJwtService)
    {
        DB::beginTransaction();
        try {
            $authKey = env('API_KEY');
            $access_token = trim(request("access_token")); //获取支付宝信息使用
            $phone = trim(request("phone"));
            $code = trim(request("code"));
            // 获取用户支付宝信息
            $aliPayLoginService->init(1);
            $resUserInfo = $aliPayLoginService->getUserInfo("{$access_token}");
            if ($resUserInfo['code'] == 200) {
               // 其他操作 
                
                DB::commit();
                return otherReturn(200, "登录成功", $data);
            } else {
                Db::rollback();
                throw new \Exception("{$resUserInfo['msg']}");
            }
        } catch (Exception $exception) {
            DB::rollBack();
            return fail("{$exception->getMessage()}");
        }
    }

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值