日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

蚂蚁开放平台开发第三方授权登陆(二):PC端

發布時間:2023/12/14 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 蚂蚁开放平台开发第三方授权登陆(二):PC端 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在《螞蟻金服開放平臺開發前期準備》準備后,已經獲取應用AppID以及應用私鑰、支付寶公鑰、回調地址。可以進行網站應用的開發。

一、需求

用戶點擊登錄后,選擇第三方登錄中的“支付寶”,跳轉到登錄頁面使用支付寶掃碼進行授權登錄。用戶同意登錄后獲取到用戶的基本信息。

PC端授權獲取用戶基本信息流程

二、開發環境及使用到的技術

1.采用IDEA2017 進行開發

2.基于JDK1.8,使用SpringBoot1.5.14進行快速開發,json庫采用阿里開源的fastjson1.2.4,對于數據緩存方面使用redis對臨時數據進行保存。

3.采用Maven進行管理開發

三、開發步驟

目錄結構

1.配置文件:

Application.properties

#thymelea模板配置 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html spring.thymeleaf.cache=false spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/**application.url =? http://y422e8.natappfree.cc spring.profiles.active = prod

1)生產環境Application-prod.properties

# 網關 alipay.serverUrl = https://openapi.alipay.com/gateway.do # 用于獲取用戶信息詳情 alipay.authUrl = https://openauth.alipay.com/oauth2/publicAppAuthorize.htm # APPID alipay.appid = # 應用私鑰 alipay.privatekey= # 支付寶公鑰 alipay.publickey = # 回調地址 alipay.redirect_userinfo_uri = /alipay/alipayUserInfo/pc

2)開發環境Application-dev.properties

# 網關 alipay.serverUrl = https://openapi.alipay.com/gateway.do # 用于獲取用戶信息詳情 alipay.authUrl = https://openauth.alipay.com/oauth2/publicAppAuthorize.htm # APPID alipay.appid = # 應用私鑰 alipay.privatekey= # 支付寶公鑰 alipay.publickey = # 回調地址 alipay.redirect_userinfo_uri = /alipay/alipayUserInfo/pc

上述空白處填寫《螞蟻金服開放平臺開發前期準備.doc》中填寫的信息。包括appid、應用私鑰、支付寶公鑰、回調地址,

2.View層:

引導用戶點擊第三方授權中的“支付寶”按鈕,進入第三方授權

Login.html中

?

3.生成state然后向螞蟻金服開放平臺發送請求

對于引導用戶訪問支付寶授權頁面的url拼接。

1Scope目前有五種類型:分別為auth_user(獲取用戶信息、網站支付寶登錄)、auth_base(用戶信息授權,僅僅用于靜默獲取用戶支付寶的uid)、auth_ecard(商戶會員卡)、auth_invoice_info(支付寶閃電開票)、auth_puc_charge(生活繳費)。

由于是授權登錄獲取用戶信息,這里直接拼接scope=auth_user可以達到需求。

2 state是可選的參數,為了安全,這里采用redis去暫存uuid生成的隨機字符串作為state,后續再支付寶回調的時候將帶上state參數,可以通過判斷state參數防止CSRF(跨站請求偽造)攻擊

??? @RequestMapping("/login/pc")public String aLiPayUserInfo(HttpServletRequest httpServletRequest) {// 獲取用戶詳情String state = UUID.randomUUID().toString().replaceAll("-", "");RedisPoolUtil.setEx("alipay-state-" + httpServletRequest.getSession().getId(), state, 1800);String qrAliLoginUrl =env.getProperty("alipay.authUrl").trim() +"?" +"app_id=" +env.getProperty("alipay.appid").trim() +"&scope=auth_user" + //這里硬編碼,就是為了獲取用戶的信息"&redirect_uri=" +env.getProperty("application.url") +env.getProperty("alipay.redirect_userinfo_uri").trim() +"&state=" + state;log.info("redirect url:" + qrAliLoginUrl);return "redirect:" + qrAliLoginUrl;}

然后重定向到這個url中,最后螞蟻金服會回調到拼接的回調地址,并附帶code

4.根據code獲取token

需要先對state進行判斷,防止攻擊。

用戶同意授權后,將回調到我們提供的url地址上。同時帶回appid、scope、state和code。

這個code可以用于請求,獲取到token。

根據阿里提供的開發包中的AlipaySystemOauthTokenRequest類,以及獲取到的code,執行請求成功后,獲取到token。有了token,就可以進一步獲取到用戶信息

@RequestMapping("/alipayUserInfo/pc")public String getALiPayPCUserInfo(HttpServletRequest httpServletRequest, Model model) {String appId = httpServletRequest.getParameter("app_id");String scope = httpServletRequest.getParameter("scope");String authCode = httpServletRequest.getParameter("auth_code");String state = httpServletRequest.getParameter("state");log.info("appID:" + appId + "? scope:" + scope + "?? authCode:" + authCode + "?? state:" + state);if (appId == null || scope == null || authCode == null || state == null) {throw new RuntimeException("參數為空");}// 判斷是否是之前的請求,防止CSRF攻擊String alipayState = RedisPoolUtil.get("alipay-state-" + httpServletRequest.getSession().getId());if (alipayState != null) {if (!state.equals(alipayState)) {throw new RuntimeException("非法請求");}}// 判定appid是否是我們的if (!appId.equals(env.getProperty("alipay.appid").trim())) {throw new RuntimeException("非法請求");}AlipayClient alipayClient = new DefaultAlipayClient(env.getProperty("alipay.serverUrl"),env.getProperty("alipay.appid"),env.getProperty("alipay.privatekey"),"json", "UTF-8",env.getProperty("alipay.publickey"),"RSA2");AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();request.setCode(authCode);request.setGrantType("authorization_code");try {AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);log.info("AccessToken:" + oauthTokenResponse.getAccessToken());// 獲取用戶信息AliPayUserInfo aliPayUserInfo = getAliPayUserInfo(alipayClient, oauthTokenResponse.getAccessToken());if (aliPayUserInfo == null) {throw new RuntimeException("獲取用戶信息失敗");}model.addAttribute(aliPayUserInfo);} catch (AlipayApiException e) {//處理異常e.printStackTrace();}return "alipayUser"; }

5.根據token獲取用戶信息

通過阿里提供的庫文件中的AlipayUserInfoShareResponse。根據token去向支付寶開放平臺發出請求,然后獲取用戶的基本信息

private AliPayUserInfo getAliPayUserInfo(AlipayClient alipayClient, String token) {AlipayUserInfoShareRequest requestUser = new AlipayUserInfoShareRequest();try {// 根據獲取的TOKEN獲取用戶公開信息AlipayUserInfoShareResponse userinfoShareResponse = alipayClient.execute(requestUser, token);String body = userinfoShareResponse.getBody();log.info(body.toString());// 設置返回過來的信息AliPayUserInfo aliPayUserInfo = new AliPayUserInfo();aliPayUserInfo.setUserId(userinfoShareResponse.getUserId());aliPayUserInfo.setNickName(userinfoShareResponse.getNickName());aliPayUserInfo.setAvatar(userinfoShareResponse.getAvatar());aliPayUserInfo.setCity(userinfoShareResponse.getCity());aliPayUserInfo.setGender(userinfoShareResponse.getGender());aliPayUserInfo.setIs_certified(userinfoShareResponse.getIsCertified());aliPayUserInfo.setIs_student_certified(userinfoShareResponse.getIsStudentCertified());aliPayUserInfo.setProvince(userinfoShareResponse.getProvince());aliPayUserInfo.setUser_status(userinfoShareResponse.getUserStatus());aliPayUserInfo.setUser_type(userinfoShareResponse.getUserType());return aliPayUserInfo;} catch (AlipayApiException e) {e.printStackTrace();}return null;}

6.阿里用戶信息類:

新建一個javaBean來保存獲取到的基本用戶信息。

@Getter @Setter public class AliPayUserInfo {private String userId;private String nickName;private String avatar;private String city;private String gender;private String is_certified;private String is_student_certified;private String province;private String user_status;private String user_type; }

7.其工具類

I.HttpClient封裝類HttpClientUtils

封裝HttpClient的post和get請求,

其中get請求封裝

public static JSONObject httpGet(String url) {// get請求返回結果JSONObject jsonResult = null;CloseableHttpClient client = HttpClients.createDefault();// 發送get請求HttpGet request = new HttpGet(url);request.setConfig(requestConfig);try {CloseableHttpResponse response = client.execute(request);// 請求發送成功,并得到響應if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 讀取服務器返回過來的json字符串數據HttpEntity entity = response.getEntity();String strResult = EntityUtils.toString(entity, "utf-8");// 把json字符串轉換成json對象jsonResult = JSONObject.parseObject(strResult);} else {logger.error("get請求提交失敗:" + url);}} catch (IOException e) {logger.error("get請求提交失敗:" + url, e);} finally {request.releaseConnection();}return jsonResult; }

II.Jedis封裝類RedisPoolUtil

封裝jedis的方法,讓操作redis更加易用

其中get方法實現:

??? public static String get(String key){Jedis jedis = null;String result = null;try {jedis = RedisPool.getJedis();result = jedis.get(key);} catch (Exception e) {log.error("get key:{} error",key,e);RedisPool.returnBrokenResource(jedis);return result;}RedisPool.returnResource(jedis);return result; }

RedisPool.java也是對redis進行封裝的類,主要對jedis的JedisPoolConfig進行配置。使用池管理Jedis。

四、功能測試

1.開發環境測試

開發環境使用阿里提供的沙箱

最終能夠獲取到測試賬號的信息。

2.線上環境測試

成功獲取用戶基本信息

五、開放平臺文檔鏈接

登錄授權:https://docs.open.alipay.com/289/105656

獲取用戶信息:https://docs.open.alipay.com/api_2/alipay.user.info.share

刷新token:https://docs.open.alipay.com/api_9/alipay.system.oauth.token

?

網站支付寶登陸:https://docs.open.alipay.com/263/105809/

六、相關配置位置

1.PID

PID位置:登錄支付寶官網b.alipay.com。點擊首頁“賬戶管理”,進入賬戶管理頁面,點擊“商戶信息管理”

PID:

?

2.應用配置詳情

進入“網頁&移動應用”頁面

查看APPID和授權回調地址的配置。

應用添加的功能:

總結

以上是生活随笔為你收集整理的蚂蚁开放平台开发第三方授权登陆(二):PC端的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。