1. 支付寶登錄授權流程
網站支付寶登錄的授權流程遵照 OAuth2.0 協議,具體請見下圖。其中,申請獲取用戶信息功能時默認可獲取的用戶信息包含支付寶用戶 ID、昵稱、性別、省份、城市、用戶頭像信息。
1. 首先,按照規則拼接授權頁面的鏈接引導用戶登錄並授權給商家;
2. 用戶授權后,開放平台會將用戶瀏覽器重定向到商家設置的 returnUrl(該 URL 需與商家在開放平台設置的授權回調地址保持一致),同時會帶上 auth_code 參數;
3. 商家在獲取 auth_code 后,調用開放平台接口 alipay.system.oauth.token(換取授權訪問令牌接口),使用 auth_code 換取授權訪問令牌 access_token;
4. 此時,商家就可以拿着 access_token,通過商戶后台發起對開放平台 alipay.user.info.share(支付寶會員授權信息查詢接口)的調用,獲取用戶授權的信息。
本步驟的作用:
登錄 開放平台控制台 獲取創建應用的 APPID
接入支付寶登錄前,網站需首先進行申請,獲得對應的appid,以保證后續流程中可正確對網站與用戶進行驗證與授權。
注意:對appid和appkey信息進行保密,不要隨意泄漏。
2. 放置“支付寶登錄”按鈕
本步驟的作用:
在網站頁面上放置“支付寶登錄”按鈕,並為按鈕添加前台代碼,實現點擊按鈕即彈出支付寶登錄對話框 。
2.1 下載“支付寶登錄”按鈕圖片,並將按鈕放置在頁面合適的位置
可以到阿里矢量圖庫下載更多圖標:阿里巴巴矢量圖標庫 。
2.2 把“支付寶登錄”按鈕添加到頁面
2.2.1 效果演示
2.2.2 前端代碼(Vue)
為了實現上述效果,應該為“支付寶登錄”按鈕圖片添加如下前台登錄頁面代碼:
<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 后端代碼(Java)
1. 支付寶登錄配置文件信息:
# 支付寶登錄配置
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. 讀取配置文件信息常量類:
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(獲取支付寶登錄的url)
@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. 使用Authorization_Code獲取Access_Token(官方文檔:地址)
本步驟的作用:
通過用戶驗證登錄和授權,獲取Access Token,為下一步獲取用戶的OpenID做准備。
同時,Access Token是應用在調用OpenAPI訪問和修改用戶數據時必須傳入的參數。
3.1 簡介
適用於需要從web server訪問的應用,例如Web網站。
對於應用而言,需要進行兩步:
1. 獲取Authorization Code。
2. 通過Authorization Code獲取Access Token。
3.2 獲取Authorization Code
示例代碼
https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?
app_id=66666
&scope=auth_user
&redirect_uri=redirectUri
&state=asdfsdf
請求參數:
參數 | 是否必須 | 含義 |
---|---|---|
app_id | 必須 | 開發者應用的app_id,相同支付寶賬號下,不同的app_id獲取的token切忌混用。 |
scope | 必須 | 接口權限值,目前只支持auth_user(獲取用戶信息、網站支付寶登錄)、auth_base(用戶信息授權)、auth_ecard(商戶會員卡)、auth_invoice_info(支付寶閃電開票)、auth_puc_charge(生活繳費)五個值;多個scope時用”,”分隔,如scope為”auth_user,auth_ecard”時,此時獲取到的access_token,可以用來獲取用戶信息 |
redirect_uri | 必須 | 授權回調地址,是經過URLENCODE轉義 的url鏈接(url必須以http或者https開頭); 在請求之前,開發者需要先到開發者中心對應應用內,配置授權回調地址。 redirect_uri與應用配置的授權回調地址域名部分必須一致。 |
state | 否 | 自定義參數,用戶授權后,重定向到redirect_uri時會原樣回傳給商戶。 為防止CSRF攻擊,建議開發者請求授權時傳入state參數,該參數要做到既不可預測,又可以證明客戶端和當前第三方網站的登錄認證狀態存在 |
返回說明:
1. 如果用戶成功登錄並授權,則會跳轉到指定的回調地址,並在redirect_uri地址后帶上Authorization Code和原始的state值。如:
http://example.com/doc/toAuthPage.html?app_id=2014101500013658&source=alipay_wallet&scope=auth_user&auth_code=ca34ea491e7146cc87d25fca24c4cD11
注意:此code會在10分鍾內過期。
2. 如果用戶在登錄授權過程中取消登錄流程,對於PC網站,登錄頁面直接關閉。
錯誤碼說明:
接口調用有錯誤時,會返回code和msg字段,以url參數對的形式返回,value部分會進行url編碼(UTF-8)。
PC網站接入時,錯誤碼詳細信息請參見:PC網站接入時的公共返回碼
3.3 通過Authorization Code獲取Access Token
請求說明:
支付寶登錄和qq等第三方登錄方式不一樣,需要使用支付寶的依賴
<!--支付寶依賴-->
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.1.0</version>
</dependency>
請求參數:
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
接口實例代碼:
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. 通過Access Token 獲取用戶信息
本步驟的作用:
通過輸入在上一步獲取的Access Token,得到對應用戶的信息。
請求參數:
AlipayClient alipayClient = new DefaultAlipayClient(zhiFuBaoConstants.getGateway(), zhiFuBaoConstants.getAppID(), zhiFuBaoConstants.getAppPrivateKey(), "json", "GBK", zhiFuBaoConstants.getAlipayPublicKey(), "RSA2");
接口實例代碼:
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());
}
返回數據:
{
"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. 測試網站(地址),需要的小伙伴可以測試
5.1 每個人做的項目需求不同,可能會出現不同的問題,文章僅供參考
5.2 SpringBoot+Vue實現第三方支付寶登錄(一)
5.3 其他第三方登錄方式:https://www.cnblogs.com/liyhbk/category/2089783.html
6. 源碼購買
6.1 簡潔版(淘寶源碼)
包含登錄,第三方登錄,跳轉首頁,SpringBoot+SpringSecurity+Mysql+Redis+Vue+ElementUI等
6.2 多功能版本(淘寶源碼)
包含登錄,注冊,第三方登錄,完整的系統管理模塊,系統工具模塊,系統監控模塊,個人中心等,SpringBoot+SpringSecurity+Mysql+Redis+Vue+ElementUI等