小程序登錄之支付寶授權的實現(xiàn)示例
眾所周知,微信小程序是可以通過微信本身授權后再登錄,平臺可以拿到微信用的的賬號相關信息,然后保存到數(shù)據(jù)庫中,那么同理在支付寶小程序開發(fā)過程中,登錄功能的設計也可以如此

上圖是官方提供的時序圖,具體看一下流程:
在小程序端獲取 auth_code,目的是獲取用戶授權碼
把第一步獲取的授權碼 auth_code 傳到咱們自己的后臺,也就是說后臺需要編寫一個接口,方便小程序端的傳入
var me = this;
my.getAuthCode({
scopes: 'auth_user', // 主動授權(彈框):auth_user,靜默授權(不彈框):auth_base
success: (res) => {
if (res.authCode) {
// console.log(app.serverUrl + '/login/' + res.authCode);
// 調用自己的服務端接口,讓服務端進行后端的授權認證
my.httpRequest({
url: app.serverUrl + '/login/' + res.authCode,
method: 'POST',
header:{
'content-type': 'application/json'
},
dataType: 'json',
success: (res) => {
// 授權成功并且服務器端登錄成功
console.log(res);
me.setData({
userInfo: res.data.data
});
}
});
}
},
});
后臺拿到這個 auth_code 之后,需要調用支付寶的授權平臺,從而獲取用戶的唯一 token 以及 支付寶的userid,都是唯一的,調用的接口為 [alipay.system.oauth.token]
獲取到userid后,判斷一下這個userid是否在我們自己的數(shù)據(jù)庫中存在,如果存在,直接獲取信息,并且直接返回用戶對象到前臺;如果不存在,則需要從支付寶授權平臺再一次去獲取支付寶用戶的信息。
調用 [alipay.user.info.share],獲取用戶信息,這個用戶對象里包含了大量的用戶真實信息,具體參考如下
@Autowired
private UserService userService;
@ApiOperation(value = "統(tǒng)一登錄接口", notes = "支付寶小程序喚起登錄后調用", httpMethod = "POST")
@PostMapping("/login/{authCode}")
public IMoocJSONResult items(
@ApiParam(name = "authCode",
value = "授權碼",
required = true,
example = "授權碼") @PathVariable String authCode) throws Exception {
// 1. 服務端獲取access_token、user_id
AlipaySystemOauthTokenResponse response = getAccessToken(authCode);
if (response.isSuccess()) {
System.out.println("獲取access_token - 調用成功");
/**
* 獲取到用戶信息后保存到數(shù)據(jù)
* 1. 如果數(shù)據(jù)庫不存在對用的 alipayUserId, 則注冊
* 2. 如果存在,則獲取數(shù)據(jù)庫中的信息再返回
*/
String accessToken = response.getAccessToken();
String alipayUserId = response.getUserId();
System.out.println("accessToken:" + accessToken);
System.out.println("alipayUserId:" + alipayUserId);
// 2. 查詢該用戶是否存在
Users userInfo = userService.queryUserIsExist(alipayUserId);
if (userInfo != null) {
// 如果用戶存在,直接返回給前端,表示登錄成功
return IMoocJSONResult.ok(userInfo);
} else {
// 如果用戶不存在,則通過支付寶api獲取用戶的信息后,再注冊用戶到自己平臺數(shù)據(jù)庫
// 獲取會員信息
AlipayUserInfoShareResponse aliUserInfo = getAliUserInfo(accessToken);
if (aliUserInfo != null) {
Users newUser = new Users();
newUser.setAlipayUserId(alipayUserId);
newUser.setNickname(aliUserInfo.getNickName());
newUser.setRegistTime(new Date());
newUser.setIsCertified(aliUserInfo.getIsCertified().equals("T") ? 1 : 0);
newUser.setFaceImage(aliUserInfo.getAvatar());
userService.createUser(newUser);
return IMoocJSONResult.ok(newUser);
}
}
} else {
System.out.println("獲取access_token - 調用失敗");
}
return IMoocJSONResult.ok();
}
// 服務端獲取access_token、user_id
private AlipaySystemOauthTokenResponse getAccessToken(String authCode) throws Exception {
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
APPID, // 1. 填入appid
PRIVATE_KEY, // 2. 填入私鑰
"json",
"GBK",
ALIPAY_PUBLIC_KEY, // 3. 填入公鑰
"RSA2");
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(authCode); // 4. 填入前端傳入的授權碼authCode
request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b"); // 0. 不用管
AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
return response;
}
// 獲取支付寶用戶信息
private AlipayUserInfoShareResponse getAliUserInfo (String accessToken) throws Exception {
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
APPID, // 1. 填入appid
PRIVATE_KEY, // 2. 填入私鑰
"json",
"GBK",
ALIPAY_PUBLIC_KEY, // 3. 填入公鑰
"RSA2");
AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response = alipayClient.execute(request, accessToken);
if(response.isSuccess()){
System.out.println("獲取會員信息 - 調用成功");
return response;
}
return null;
}
拿到的支付寶用戶信息如圖:

最終頁面的展示效果為:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
bootstrap multiselect 多選功能實現(xiàn)方法
這篇文章主要介紹了bootstrap multiselect 多選功能實現(xiàn)方法,需要的朋友可以參考下2017-06-06
JavaScript中iframe實現(xiàn)局部刷新的幾種方法匯總
Iframe是一種嵌入網(wǎng)頁的框架形式,Web頁面可以通過更改嵌入的部分,達到部分內容刷新,通過本文和大家一起學習iframe實現(xiàn)局部刷新的幾種方法匯總,對iframe局部刷新相關知識感興趣的朋友一起學習吧2016-01-01
使用Microsoft Ajax Minifier減小JavaScript文件大小的方法
大家用來減小JavaScript文件下載大小的常見的方式有2種: 壓縮(compression)和縮?。╩inification)。2010-04-04
JavaScript實現(xiàn)頁面實時顯示當前時間的簡單實例
這篇文章介紹了頁面實時顯示當前時間的簡單實例,有需要的朋友可以參考需要2013-07-07
深入淺析JavaScript中對事件的三種監(jiān)聽方式
最近這段時間因為每天要修改網(wǎng)站,為網(wǎng)站做特效,所以看了很多的js接觸事件,自己只會使用一小部分,有時用的時候也比較混亂,現(xiàn)在系統(tǒng)的整理了一下,本篇文章跟大家分享的是JavaScript中對事件的三種監(jiān)聽方式2015-09-09

