支付宝 APP登录 获取用户信息 PHP(转)

转载自:https://blog.csdn.net/wang78699425/article/details/78666401

支付宝 APP登录 获取用户信息 PHP(转)

支付宝APP登录服务端流程如下: 
1、换取授权访问令牌 
2、查询用户信息

APP调用sdk组装授权登录请求(系统交互流程),成功后,支付宝会返回 auth_code,利用此 auth_code 请求 PHP,PHP接收到参数后,先利用 auth_code 获取到 授权访问令牌 access_token(接口文档),再根据 access_token 来获取用户信息(接口文档)。

具体代码如下:

try {
        $code = trim($_POST['auth_code']);
        if (empty($code)) {
            throw new Exception('缺少参数', 0);
        }

        //获取access_token
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $alipay_config['app_id'];
        $aop->rsaPrivateKey = trim($alipay_config['application_private']);
        $aop->format = 'json';
        $aop->charset = 'UTF-8';
        $aop->signType = 'RSA2';
        $aop->alipayrsaPublicKey = trim($alipay_config['alipay_public']);
        $aop->apiVersion = '1.0';
        $request = new AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($code);

        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultData = (array) $result->$responseNode;
        if (empty($resultData['access_token'])) {
            throw new Exception('获取access_token失败', 0);
        }
        //获取用户信息
        $request = new AlipayUserInfoShareRequest ();
        $result = $aop->execute ( $request , $resultData['access_token'] );
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $userData = (array) $result->$responseNode;
        if (empty($userData['code']) || $userData['code'] != 10000) {
            throw new Exception('获取用户信息失败', 0);
        }
        /**
         * user_id  支付宝用户的userId
         * avatar   用户头像地址
         * province 省份名称
         * city 市名称。
         * nick_name    用户昵称
         * is_student_certified 是否是学生
         * user_type    用户类型(1/2)  1代表公司账户2代表个人账户
         * user_status  用户状态(Q/T/B/W)。 Q代表快速注册用户 T代表已认证用户 B代表被冻结账户 W代表已注册,未激活的账户
         * is_certified 是否通过实名认证。T是通过 F是没有实名认证。
         * gender   性别(F:女性;M:男性)。
         *
         */

        //业务逻辑


        echo json_encode(['code' => 1, 'msg' => '登录成功']);
        exit;
    } catch (Exception $exception) {
        echo json_encode(['code' => $exception->getCode(), 'msg' => $exception->getMessage()]);
        exit;
    }
原文地址:https://www.cnblogs.com/crazytata/p/9962909.html