1. User agrees to authorize and get code
String redirecturi = HttpUtil.urlEnCode(domain + aliPay + QRCodeUrl); SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Alipay); MyAliPayConfig aliPayConfig = new MyAliPayConfig(); aliPayConfig.setAppId(channel.getAppid()); // Authorization Page Address String requestUrl = aliPayConfig.getAuthgateway(); requestUrl = requestUrl.replace("APPID", aliPayConfig.getAppId()).replace("SCOPE", aliPayConfig.getScope()).replace("REDIRECT_URI", redirecturi); // Redirect to authorization page response.sendRedirect(requestUrl);
2. Obtain openid by code
request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //After the user agrees to authorize, the code can be obtained. String code = request.getParameter("auth_code"); String aliuserid = ""; if (!redisService.exists(code)){ //User agrees to authorize if (!code.equals("")) { SysPayChannel channel = payChannelService.selectByChannelType(PayTypeConstant.Alipay); MyAliPayConfig aliPayConfig = new MyAliPayConfig(); aliPayConfig.setAppId(channel.getAppid()); String certsrc = channel.getPayCertUrl(); Properties propertiesFile = PropertiesUtils.getPropertiesFile(certsrc); if (propertiesFile != null) { aliPayConfig.setPayeeAccount(propertiesFile.getProperty("ALI_PAYEE_ACCOUNT")); aliPayConfig.setAppId(propertiesFile.getProperty("ALI_APP_ID")); aliPayConfig.setAliPayPublicKey(propertiesFile.getProperty("ALI_ALIPAY_PUBLIC_KEY")); aliPayConfig.setAppPayPublicKey(propertiesFile.getProperty("ALI_APP_PAY_PUBLIC_KEY")); aliPayConfig.setAppPrivateKey(propertiesFile.getProperty("ALI_APP_PRIVATE_KEY")); } //Get access_token of webpage authorization AliPayOAuth2Token aliPayOAuth2Token = AliPayOAuth2Util.getOAuth2AccessToken(aliPayConfig,code); //Web Authorization Interface Access Credentials String accessToken = aliPayOAuth2Token.getAccessToken(); //User ID aliuserid = aliPayOAuth2Token.getUserid(); //aliuserid redisService.setex(code, 60, aliuserid); } } else { aliuserid = redisService.get(code); }
3. Resolve the expiration of refresh page code
Because auth_code can only be used once when aliuserid is acquired through auth_code, a little trick is used here to resolve the expiration of auth_code when refreshing a web page. When the aliuserid is first acquired, the aliuserid is cached and refreshed to determine that if aliuserid exists, aliuserid is not acquired through codeauth_code. Of course, the other thing worth noting about these two lines of code is that the cached key is the auth_code value.