标签

Honeymoon - Thomas Ng

归档

近期文章

支付宝获取用户信息- PHP实例

本文环境 PHP7.3,Laravel6.0 不懂的可以评论或联系我邮箱:owen@owenzhang.com 著作权归OwenZhang所有。商业转载请联系OwenZhang获得授权,非商业转载请注明出处。

获取 Alipay SDK引入项目中

https://github.com/alipay/alipay-sdk-php-all

支付宝获取用户信息- PHP实例插图

1.手动引入 laravel手动引入包之第三方包导入以及自定义包 2.Laravel使用AlipaySDK加密解密函数名称冲突错误 Cannot redeclare Encrypt() (previously declared in

开通功能

  • 注意:APP支付宝登录不支持沙盒测试
  • 登录https://open.alipay.com/
  • APP支付宝登录
  • 获取会员信息
    支付宝获取用户信息- PHP实例插图1

1.App支付宝登录,获取完整版授权请求参数和返回

/**
     * 绑定支付宝用户信息 - 第1步
     * @notes : 支付宝-app端获取auth_code
     *        App支付宝登录,获取完整版授权请求参数和返回
     *        https://opendocs.alipay.com/open/218/105327?pathHash=e41418be
     * @return array
     * @author: OwenZhang
     * @time  : 2023/4/12 11:57
     */
    public function getUrlUseCode(): array
    {
        try {
            $payConfig              = self::payConfig('alipay');
            $appId                  = $payConfig['app_id'];
            $appPrivateKey          = $payConfig['private_key'];
            $targetId               = time() . rand(0, 100);
            $pid                    = 2ddd66;
            $signString             = 'apiname=com.alipay.account.auth&app_id=' . $appId . '&app_name=mc&auth_type=AUTHACCOUNT&biz_type=openservice&method=alipay.open.auth.sdk.code.get&pid=' . $pid . '&product_id=APP_FAST_LOGIN&scope=kuaijie&sign_type=RSA&target_id=' . $targetId;
            $signData['apiname']    = 'com.alipay.account.auth';
            $signData['app_id']     = $appId;
            $signData['app_name']   = 'mc';
            $signData['auth_type']  = 'AUTHACCOUNT';
            $signData['biz_type']   = 'openservice';
            $signData['method']     = 'alipay.open.auth.sdk.code.get';
            $signData['pid']        = $pid;
            $signData['product_id'] = 'APP_FAST_LOGIN';
            $signData['scope']      = 'kuaijie';
            $signData['sign_type']  = 'RSA';
            $signData['target_id']  = $targetId;
            //整个授权参数信息的签名,即此行以上参数 key 和 value 通过&拼接的字符串的签名值,对此字符串签名后需做 URL 编码。
            $sign            = $this->sign($signData, $appPrivateKey, 'RSA');
            $data['signUrl'] = $signString . '&sign=' . urlencode($sign);

            return ['msg' => '操作成功', 'code' => 200, 'data' => $data];
        } catch (\Exception $e) {
            return ['msg' => $e->getMessage(), 'code' => 400, 'data' => null];
        }
    }

2.用code换取授权访问令牌

/**
     * 绑定支付宝用户信息 - 第2步
     * @notes : 支付宝-用code换取授权访问令牌
     *        https://opendocs.alipay.com/open/02ailc?pathHash=7ebfa7a0
     * @return array
     * @author: OwenZhang
     * @time  : 2023/4/12 11:57
     */
    public function getAccessTokenByCode($code): array
    {
        try {
            $payConfig          = self::payConfig('alipay');
            $appId              = $payConfig['app_id'];
            $appPrivateKey      = $payConfig['private_key'];
            $alipayrsaPublicKey = $payConfig['ali_public_key'];

            $aop                     = new \AopClient();
            $aop->gatewayUrl         = 'https://openapi.alipay.com/gateway.do';
            $aop->appId              = $appId;
            $aop->rsaPrivateKey      = $appPrivateKey;
            $aop->alipayrsaPublicKey = $alipayrsaPublicKey;
            $aop->apiVersion         = '1.0';
            $aop->signType           = 'RSA2';
            $aop->postCharset        = 'utf-8';
            $aop->format             = 'json';
            $request                 = new \AlipaySystemOauthTokenRequest();
            $request->setGrantType('authorization_code');
            $request->setCode($code);
//        $request->setRefreshToken('201208134b2ddddcabd8da5bb087a83b');
            $result = $aop->execute($request);
            $result = objectToArray($result);
            if (!empty($result['alipay_system_oauth_token_response']['access_token'])) {
                return ['code' => 200, 'msg' => 'success', 'data' => $result['alipay_system_oauth_token_response']];
            }
            if (!empty($result['error_response']['sub_msg'])) {
                $msg = $result['error_response']['sub_msg'] . $result['error_response']['code'];
                return ['code' => 400, 'msg' => $msg, 'data' => null];
            }
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => $e->getMessage(), 'data' => null];
        }

        return ['code' => 400, 'msg' => '获取失败', 'data' => null];
    }

3.用accessToken换取用户信息

/**
     * 绑定支付宝用户信息 - 第3步
     * @notes : 支付宝-用accessToken换取用户信息
     *        https://opendocs.alipay.com/open/02ailc?pathHash=7ebfa7a0
     * @return array
     * @author: OwenZhang
     * @time  : 2023/4/12 11:57
     */
    public function getUserInfoByAccessToken($accessToken): array
    {
        try {
            $payConfig          = self::payConfig('alipay');
            $appId              = $payConfig['app_id'];
            $appPrivateKey      = $payConfig['private_key'];
            $alipayrsaPublicKey = $payConfig['ali_public_key'];

            $aop                     = new \AopClient();
            $aop->gatewayUrl         = 'https://openapi.alipay.com/gateway.do';
            $aop->appId              = $appId;
            $aop->rsaPrivateKey      = $appPrivateKey;
            $aop->alipayrsaPublicKey = $alipayrsaPublicKey;
            $aop->apiVersion         = '1.0';
            $aop->signType           = 'RSA2';
            $aop->postCharset        = 'utf-8';
            $aop->format             = 'json';
            $request                 = new \AlipayUserInfoShareRequest();
            $result                  = $aop->execute($request, $accessToken);
            $result                  = objectToArray($result);
            if (!empty($result['alipay_user_info_share_response']['user_id'])) {
                $avatar = !empty($result['alipay_user_info_share_response']['avatar']) ? $result['alipay_user_info_share_response']['avatar'] : '';
                $data   = [
                    'user_id'   => $result['alipay_user_info_share_response']['user_id'],
                    'nick_name' => $result['alipay_user_info_share_response']['nick_name'],
                    'avatar'    => $avatar,
                ];
                return ['code' => 200, 'msg' => 'success', 'data' => $data];
            }
            if (!empty($result['error_response']['sub_msg'])) {
                $msg = $result['error_response']['sub_msg'] . $result['error_response']['code'];
                return ['code' => 400, 'msg' => $msg, 'data' => null];
            }
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => $e->getMessage(), 'data' => null];
        }

        return ['code' => 400, 'msg' => '获取失败', 'data' => null];
    }

生成签名

/**
     * 签名.
     * https://opendocs.alipay.com/common/057k53?pathHash=7b14a0af
     * @param $data
     * @param $appPrivateKey  私有证书文件内容.
     * @param $singType
     * @return string
     * @throws \Exception
     */
    public function sign($data, $appPrivateKey, $singType)
    {
        $content = $this->parseSignData($data);
        $key     = $appPrivateKey;
        $method  = 'signPrivate';
        switch ($singType) {
            case 'RSA':
                $result = RSA::$method($content, $key);
                break;
            case 'RSA2':
                $result = RSA2::$method($content, $key);
                break;
            default:
                throw new \Exception('未知的加密方式:' . $this->signType);
        }

        return base64_encode($result);
    }

         /**
     * 处理验证数据.
     *
     * @param array $data
     *
     * @return string
     */
    public function parseSignData($data)
    {
        if (isset($data['sign'])) {
            unset($data['sign']);
        }
        ksort($data);
        $content = '';
        foreach ($data as $k => $v) {
            if ('' !== $v && null !== $v && !\is_array($v)) {
                $content .= $k . '=' . $v . '&';
            }
        }

        return trim($content, '&');
    }

Buy me a cup of coffee 🙂

觉得对你有帮助,就给我打赏吧,谢谢!

微信赞赏码链接,点击跳转:

https://www.owenzhang.com/wechat_reward.png

支付宝获取用户信息- PHP实例插图2
Tags: