小程序登陸 之 支付寶受權

衆所周知,微信小程序是能夠經過微信自己受權後再登陸,平臺能夠拿到微信用的的帳號相關信息,而後保存到數據庫中,那麼同理在支付寶小程序開發過程當中,登陸功能的設計也能夠如此前端

上圖是官方提供的時序圖,具體看一下流程:數據庫

  1. 在小程序端獲取 auth_code,目的是獲取用戶受權碼json

  2. 把第一步獲取的受權碼 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
                  });
                }
              });
            }
          },
        });
    複製代碼

     

  3. 後臺拿到這個 auth_code 以後,須要調用支付寶的受權平臺,從而獲取用戶的惟一 token 以及 支付寶的userid,都是惟一的,調用的接口爲 [alipay.system.oauth.token]後端

  4. 獲取到userid後,判斷一下這個userid是否在咱們本身的數據庫中存在,若是存在,直接獲取信息,而且直接返回用戶對象到前臺;若是不存在,則須要從支付寶受權平臺再一次去獲取支付寶用戶的信息。微信小程序

  5. ​調用 [alipay.user.info.share],獲取用戶信息,這個用戶對象裏包含了大量的用戶真實信息,具體參考以下api

複製代碼
@Autowired
    private UserService userService;

    @ApiOperation(value = "統一登陸接口", 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 - 調用成功");
            /**
             *  獲取到用戶信息後保存到數據
             *  1. 若是數據庫不存在對用的 alipayUserId, 則註冊
             *  2. 若是存在,則獲取數據庫中的信息再返回
             */
            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獲取用戶的信息後,再註冊用戶到本身平臺數據庫
                // 獲取會員信息
                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;
    }
複製代碼

拿到的支付寶用戶信息如圖:服務器

最終頁面的展現效果爲:微信

相關文章
相關標籤/搜索