SpringBoot+Vue implements third-party Alipay login (2)

1. Alipay login authorization process

The authorization process of Alipay login on the website complies with the OAuth2.0 protocol, see the figure below for details. Among them, the user information that can be obtained by default when applying for the function of obtaining user information includes Alipay user ID, nickname, gender, province, city, and user avatar information.

  1. First, splicing the link of the authorization page according to the rules to guide the user to log in and authorize the merchant;

  2. After the user authorizes, the open platform will redirect the user's browser to the returnUrl set by the merchant (the URL must be consistent with the authorization callback address set by the merchant on the open platform), and will also carry the auth_code parameter;

  3. After obtaining the auth_code, the merchant calls the open platform interface  alipay.system.oauth.token (interface for exchanging the authorized access token), and uses the auth_code to exchange for the authorized access token access_token;

  4. At this point, the merchant can take the access_token and initiate a call to the open platform  alipay.user.info.share (Alipay member authorization information query interface) through the merchant background to obtain user authorization information.

The role of this step :

  Log in to  the open platform console  to obtain the APPID for creating an application

  Before logging in with Alipay, the website needs to first apply to obtain the corresponding appid, so as to ensure that the website and users can be correctly verified and authorized in the subsequent process.

Note: keep the appid and appkey information confidential and do not disclose them at will.

2. Place the "Alipay Login" button

The role of this step :

  Place the "Alipay Login" button on the website page, and add the front-end code to the button, so that the Alipay login dialog box will pop up when the button is clicked.

2.1 Download the "Alipay Login" button image, and place the button at a suitable position on the page

  You can go to the Alibaba Vector Library to download more icons: Alibaba Vector Icon Library  .

2.2 Add the "Alipay Login" button to the page

2.2.1 Effect demonstration

2.2.2 Front-end code (Vue)

  In order to achieve the above effects, you should add the following front-end login page code to the "Alipay Login" button image:

<div style="line-height: 22px;margin:0 0 8px 0;color: #9b9b9b;">
        <span style="vertical-align:middle">第三方登录:</span>
        <img :src="qqIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="QQ">
        <img :src="baiduIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="百度">
        <img :src="weiboIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="微博">
        <img :src="zhifubaoIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="支付宝">
        <img :src="giteeIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="Gitee">
        <img :src="githubIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="GitHub">
</div>

2.2.3 Backend code (Java)

1. Alipay login profile information:

# 支付宝登录配置
zhifubao.appID = 66666666 ( 替换成你的 )
zhifubao.redirectURI = https://www.youyoushop.work/zhiFuBaoCallback ( 替换成你的 )
zhifubao.authorizeURL = https://openauth.alipay.com/oauth2/publicAppAuthorize.htm
zhifubao.gateway = https://openapi.alipay.com/gateway.do
zhifubao.appPrivateKey = MIIujfisdfasdf33232ufsdf0d8fsad ( 替换成你的私钥 )
zhifubao.alipayPublicKey = MIIBIjANBgkqhkiG9w0BAQEFfffffffasdfasdfaer3fsadfbovsgdTUqaUKhF ( 替换成你的公钥 )

2. Read configuration file information constant class:

package com.liyh.constants;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 支付宝登陆常量配置类
 *
 * @author Liyh
 */
@Data
@Configuration
@PropertySource("classpath:config.properties")
public class ZhiFuBaoConstants {

    @Value("${zhifubao.appID}")
    private String appID;

    @Value("${zhifubao.redirectURI}")
    private String redirectURI;

    @Value("${zhifubao.authorizeURL}")
    private String authorizeURL;

    @Value("${zhifubao.gateway}")
    private String gateway;

    @Value("${zhifubao.appPrivateKey}")
    private String appPrivateKey;

    @Value("${zhifubao.alipayPublicKey}")
    private String alipayPublicKey;

}

3. Conteoller (get the url of Alipay login)

@ApiOperation("获得跳转到支付宝登录页的url")
@GetMapping("/getZhiFuBaoCode")
public ResponseEntity<Object> getZhiFuBaoCode() throws Exception {
    // 授权地址 ,进行Encode转码
    String authorizeURL = zhiFuBaoConstants.getAuthorizeURL();

    // 回调地址 ,回调地址要进行Encode转码
    String redirectUri = zhiFuBaoConstants.getRedirectURI();

    //用于第三方应用防止CSRF攻击
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    // 保存到Redis
    redisUtils.set(ZHIFUBAOSTATE + "-" + uuid, uuid, expiration, TimeUnit.MINUTES);

    // https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?
    // app_id=appid
    // &scope=auth_user
    // &redirect_uri=redirectUri
    // &state=init

    // 拼接url
    StringBuilder url = new StringBuilder();
    url.append(authorizeURL);
    url.append("?app_id=" + zhiFuBaoConstants.getAppID());
    // 转码
    url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirectUri));
    url.append("&state=" + uuid);
    url.append("&scope=auth_user");

    return ResponseEntity.ok(url);
}

3. Use Authorization_Code to get Access_Token (official document: address )

The role of this step :

  Through user authentication, login and authorization, Access Token is obtained to prepare for the next step to obtain the user's OpenID.

  At the same time, Access Token is a parameter that must be passed in when the application calls OpenAPI to access and modify user data.

3.1 Introduction

  Applicable to applications that need to be accessed from a web server, such as Web sites.

For the application, two steps are required:

  1. Obtain the Authorization Code.

  2. Obtain an Access Token through the Authorization Code.

3.2 Get Authorization Code

sample code

https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?
app_id=66666
&scope=auth_user
&redirect_uri=redirectUri
&state=asdfsdf

Request parameters :

parameter Is it necessary meaning
app_id  must The app_id of the developer's application, under the same Alipay account, the tokens obtained by different app_ids must not be mixed.
scope  must Interface permission value, currently only supports five values: auth_user (obtain user information, website Alipay login), auth_base (user information authorization), auth_ecard (merchant membership card), auth_invoice_info (Alipay lightning billing), auth_puc_charge (life payment); multiple Use "," to separate the scope. For example, when the scope is "auth_user,auth_ecard", the access_token obtained at this time can be used to obtain user information
redirect_uri must The authorization callback address is the url link escaped by URLENCODE (the url must start with http or https); before requesting, the developer needs to go to the corresponding application in the developer center to configure the authorization callback address. The redirect_uri must be consistent with the domain name part of the authorization callback address configured in the application.
state no Custom parameter, after the user authorizes, it will be sent back to the merchant as it is when redirected to redirect_uri. In order to prevent CSRF attacks, it is recommended that developers pass in the state parameter when requesting authorization. This parameter should be unpredictable and can prove that the login authentication status of the client and the current third-party website exists.

Return instructions :

1. If the user successfully logs in and authorizes, it will jump to the specified callback address, and bring the Authorization Code and the original state value after the redirect_uri address. like:  

http://example.com/doc/toAuthPage.html?app_id=2014101500013658&source=alipay_wallet&scope=auth_user&auth_code=ca34ea491e7146cc87d25fca24c4cD11

NOTE: This code will expire in 10 minutes.

2. If the user cancels the login process during the login authorization process, for PC websites, the login page will be closed directly.

Error code description :

  When there is an error in the interface call, the code and msg fields will be returned in the form of url parameter pairs, and the value part will be url-encoded (UTF-8).

  For more information about error codes when accessing a PC website, see: Common return codes when accessing a PC website

3.3 Obtain Access Token through Authorization Code

Request description :

  Alipay login and third-party login methods such as QQ are different, and Alipay's dependency is required

<!--支付宝依赖-->
<dependency>
    <groupId>com.alipay.sdk</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>3.1.0</version>
</dependency>

Request parameters :

AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");

Interface instance code:

AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); 
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setCode("2e4248c2f50b4653bf18ecee3466UC18");
request.setGrantType("authorization_code");
try {
    AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
    System.out.println(oauthTokenResponse.getAccessToken());
} catch (AlipayApiException e) {
    //处理异常
    e.printStackTrace();
}

4. Obtain user information through Access Token

The role of this step :

  Get the corresponding user information by entering the Access Token obtained in the previous step.

Request parameters:

AlipayClient alipayClient = new DefaultAlipayClient(zhiFuBaoConstants.getGateway(), zhiFuBaoConstants.getAppID(), zhiFuBaoConstants.getAppPrivateKey(), "json", "GBK", zhiFuBaoConstants.getAlipayPublicKey(), "RSA2");

Interface instance code:

AlipayClient alipayClient = new DefaultAlipayClient(
        "https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", "GBK",
        ALIPAY_PUBLIC_KEY);
    AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
    String token =/* 获取步骤3中的token */;
    AlipayUserInfoShareResponse response = alipayClient.execute(request, token);
    if (response.isSuccess()) {
        System.out.println("调用成功");
        System.out.println(ReflectionToStringBuilder.toString(response));
        String userId = response.getUserId();
    } else {
        System.out.println("调用失败");
        System.out.println(response.getSubCode() + ":" + response.getSubMsg());
    }

return data:

{
  "alipay_user_info_share_response": {
    "code": "10000",
    "msg": "Success",
    "user_id": "2088102104794936",
    "avatar": "http://tfsimg.alipay.com/images/partner/T1uIxXXbpXXXXXXXX",
    "province": "安徽省",
    "city": "安庆",
    "nick_name": "支付宝小二",
    "gender": "F"
    },
  "sign": "ERITJKEIJKJHKKKKKKKHJEREEEEEEEEEEE"
}

5. Test website ( address ), small partners who need it can test

5.1 Everyone's project needs are different, and different problems may arise. This article is for reference only

5.2  SpringBoot+Vue implements third-party Alipay login (1)

5.3 Other third-party login methods: https://www.cnblogs.com/liyhbk/category/2089783.html

6. Source code purchase

6.1 Concise version ( Taobao source code )

Including login, third-party login, jump homepage, SpringBoot+SpringSecurity+Mysql+Redis+Vue+ElementUI, etc.

6.2 Multifunctional version ( Taobao source code )

Including login, registration, third-party login, complete system management module, system tool module, system monitoring module, personal center, etc., SpringBoot+SpringSecurity+Mysql+Redis+Vue+ElementUI, etc.

Guess you like

Origin blog.csdn.net/liyh722/article/details/130244804