天天看点

第三方登录-支付宝篇

无聊开始研究第三方登录,研究过qq,baidu,微信,csdn,支付宝基本上都是使用oauth2进行登录授权验证的。

在使用之前,必须要去支付宝开放平台注册为开发者,并创建一个应用。

https://open.alipay.com/productDocument.htm

1. 按照申请的步骤一步一步走,有一个地方需要设置密钥,需要下载阿里的加密工具包,生成公钥和私钥(推荐RSA2),将生成的公钥填入页面要求的地方,保存后,支付宝会生成一个支付宝公钥, 这个支付宝公钥和我们自己生成的私钥 是非常有用的,最好保存起来。

  1. 应用网关可填可不填, 回调地址就是用户使用支付宝登录成功后,回去访问的地址,这个地方要设置好,后面我们要调用这个方法来获取一些需要的数据。

    注册成功后我们就得到了需要的三个数据 appid privatekey publickey

    ————————-OK 准备工作做好啦—————————————————————–

  2. 在自己的工程中添加支付宝登录的链接

    href=”https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=”你的appid”&redirect_uri=你的回调地址” target=”blank” >支付宝登录

  3. 用户登录支付宝后,地址跳转到了后台,后台逻辑
/** 1. 登录成功后,获取返回的code
2. 根据code获取access_token
3. 根据token获取用户的id 头像信息
*/
@RequestMapping("userLogin")
public String userLogin(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException, AlipayApiException, JsonProcessingException {
        Map<String, String> params = new HashMap<String, String>();
        // 获取支付宝登录后反馈回来的数据,存入map中
        Map<String, Object> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = ; i < values.length; i++) {
                valueStr = (i == values.length) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 解决乱码
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"), "utf-8");
        String app_auth_code = new String(request.getParameter("app_auth_code").getBytes("ISO-8859-1"), "utf-8");

        String privateKey = AccountConfigUtil.readConfig(PRIVATE_KEY); // 私钥
        String publicKey = AccountConfigUtil.readConfig(PUBLIC_KEY);// 公钥

        // 请求支付宝后台后获取token
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", app_id, privateKey, "json", "UTF-8", publicKey, "RSA2");
        AlipayOpenAuthTokenAppRequest requestLogin1 = new AlipayOpenAuthTokenAppRequest();
        requestLogin1.setBizContent(
                "{" + "\"grant_type\":\"authorization_code\"," + "\"code\":\"" + app_auth_code + "\"" + "}");
        AlipayOpenAuthTokenAppResponse responseToken = alipayClient.execute(requestLogin1);
        if (responseToken.isSuccess()) {
            String authAppId = responseToken.getAuthAppId();
            String userId = responseToken.getUserId();
            String authToken = responseToken.getAppAuthToken();
            System.out.println("authAppId:" + authAppId + "\r\n" + "userId:" + userId + "\r\n" + "authToken" + authToken);
        }



    return "index";
}
           

ps :我这里调用了ali官方的jar包,如果你也想使用的话,可以去ali官方下载下来,然后存入项目中,

我的jar包放在src下lib中,因此maven中设置如下

<dependency>
    <groupId>alipay</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${basedir}/src/lib/alipay-sdk-java20170829142630.jar</systemPath>
</dependency>
           

—————————–华丽分割线————————————————————————

假如我们不光想获取用户的id和头像,还想获取更多用户信息,则必须去支付宝开放平台添加相关的木块

  1. 添加成功后,我们修改跳转到支付宝的登录接口

    href=”https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=”你的appid”&scope=auth_user&redirect_uri=”你的回调地址”” target=”blank” >支付宝登录

    scope 按照官方文档有多种写法 auth_user 或者 auth_base等

  2. 跳转到后台的逻辑
@RequestMapping("userLogin")
public String userLogin(HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException, AlipayApiException, JsonProcessingException {
        Map<String, String> params = new HashMap<String, String>();
        // 获取支付宝登录后反馈回来的数据,存入map中
        Map<String, Object> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = ; i < values.length; i++) {
                valueStr = (i == values.length) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 解决乱码
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"), "utf-8");
        String auth_user = new String(request.getParameter("scope").getBytes("ISO-8859-1"),"UTF-8");
        String auth_code = new String(request.getParameter("auth_code").getBytes("ISO-8859-1"),"UTF-8");

        String privateKey = AccountConfigUtil.readConfig(PRIVATE_KEY); // 私钥
        String publicKey = AccountConfigUtil.readConfig(PUBLIC_KEY);// 公钥
        AlipayClient alipayClient =
                 new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",app_id,
                         privateKey,"json","UTF-8",publicKey,"RSA2");//沙箱下的网关
        //根据auto_code 获取用户信息授权 accestoken
        AlipaySystemOauthTokenRequest requestLogin2 = new AlipaySystemOauthTokenRequest();
        requestLogin2.setCode(auth_code);
        requestLogin2.setGrantType("authorization_code");
        AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(requestLogin2);

        //根据accessToken 去获取用户信息
        AlipayUserInfoShareRequest requestUser = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse userinfoShareResponse = 
                 alipayClient.execute(requestUser, oauthTokenResponse.getAccessToken());
        String userId = userinfoShareResponse.getUserId();    // 用户id
        String userType = userinfoShareResponse.getUserType();  //用户类型
        String userStatus = userinfoShareResponse.getUserStatus(); //用户账户动态
        String email = userinfoShareResponse.getEmail();    //email
        String taobaoId = userinfoShareResponse.getTaobaoId(); //淘宝id
        String isCertified = userinfoShareResponse.getIsCertified(); //是否身份认真
        System.out.println("userId: "+userId+"\r\n"+"userType: "+userType+"\r\n"+"userStatus"+userStatus+"\r\n"
                +"email: "+email+"\r\n"+"taobaoId: "+taobaoId+"\r\n"+"isCertified: "+isCertified); 
        System.out.println("用户所在省份: "+userinfoShareResponse.getProvince()+",所在市"+userinfoShareResponse.getCity());
        return "index";
}