public static m_Alipay_Server_Token askTokenByOldFromServer(string app_id, string refresh_token) { try { IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", app_id, "\\RSA\\merchant_private_key_2048.txt", "json", "1.0", "RSA2", "\\RSA\\alipay_public_key_sha256.txt", "GBK", true); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "refresh_token"; //request.Code = "4b203fe6c11548bcabd8da5bb087a83b"; request.RefreshToken = refresh_token;//"201208134b203fe6c11548bcabd8da5bb087a83b"; AlipaySystemOauthTokenResponse response = client.Execute(request); var token = JsonConvert.DeserializeObject <m_Alipay_Server_Token>(response.Body); if (null == token) { return(null); } else { return(token); } } catch (Exception ex) { //记录日志 } return(null); }
/// <summary> /// 使用auth_code换取access_token及用户userId /// </summary> /// <param name="code"></param> /// <param name="redirectUri"></param> /// <returns></returns> protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri) { try { var alipayRequest = new AlipaySystemOauthTokenRequest { Code = code, GrantType = "authorization_code" //GetApiName() }; var alipayResponse = await _alipayClient.ExecuteAsync(alipayRequest); if (alipayResponse.IsError) { Logger.LogError("An error occurred while retrieving an access token: the remote server " + "returned a {Status} response with the following payload: {Headers} {Body}.", /* Status: */ alipayResponse.Code, /* Headers: */ alipayResponse.Msg, /* Body: */ alipayResponse.Body); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } else { var payload = JObject.FromObject(alipayResponse); return(OAuthTokenResponse.Success(payload)); } } catch (Exception ex) { Logger.LogError(ex.ToString()); return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."))); } }
/** * 微信的特殊性,此时返回的信息同时包含 openid 和 access_token * * @param authCallback 回调返回的参数 * @return 所有信息 */ protected override AuthToken getAccessToken(AuthCallback authCallback) { AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "authorization_code"; request.Code = authCallback.auth_code; AlipaySystemOauthTokenResponse response = null; try { response = this.aopClient.Execute(request); } catch (Exception e) { throw new Exception(e.Message); } if (response.IsError) { throw new Exception(response.SubMsg); } var authToken = new AuthToken(); authToken.accessToken = response.AccessToken; authToken.uid = response.UserId; authToken.expireIn = Convert.ToInt32(response.ExpiresIn); authToken.refreshToken = response.RefreshToken; authToken.userId = response.AlipayUserId; return(authToken); }
/// <summary> /// 获取会员基础信息 /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <AuthDto> GetAuthAsync(string code) { var options = new AlipayOptions(); options.AppId = ""; options.AppPrivateKey = ""; options.AlipayPublicKey = ""; var req = new AlipaySystemOauthTokenRequest() { Code = code, RefreshToken = "", GrantType = "authorization_code" }; AlipaySystemOauthTokenResponse response = await _alipayClient.ExecuteAsync(req, options); if (response.IsError) { throw new UserFriendlyException(response.SubMsg); } var dto = new AuthDto(); dto.AccessToken = response.AccessToken; dto.AuthTokenType = response.AuthTokenType; dto.ExpiresIn = response.ExpiresIn; dto.ReExpiresIn = response.ReExpiresIn; dto.RefreshToken = response.RefreshToken; dto.UserId = response.UserId; return(dto); }
public static AlipaySystemOauthTokenResponse alipay_system_oauth_token_Code(string Code) { var client = GetAlipayClient(); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "authorization_code"; request.Code = Code; AlipaySystemOauthTokenResponse response = client.Execute(request); return(response); }
public static AlipaySystemOauthTokenResponse alipay_system_oauth_token(string refresh_token) { var client = GetAlipayClient(); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "refresh_token"; request.RefreshToken = refresh_token; AlipaySystemOauthTokenResponse response = client.Execute(request); return(response); }
/// <inheritdoc /> public ThirdPartyAuthorizeResult Authorize(AuthorizationInput input) { IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", AppId, AppPrivateKey, "json", "1.0", "RSA2", AppPublicKey, "utf-8", false); AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest { Code = input.Code, GrantType = "authorization_code" }; AlipaySystemOauthTokenResponse tokenResponse = client.Execute(tokenRequest); if (tokenResponse.IsError) { throw new UserFriendlyException("认证失败,请重试"); } var thirdPartyUser = _thirdPartyUserRepository .GetAll() .FirstOrDefault(u => u.OpenId == tokenResponse.UserId); if (thirdPartyUser == null) { AlipayUserUserinfoShareRequest userRequest = new AlipayUserUserinfoShareRequest(); AlipayUserUserinfoShareResponse userResponse = client.Execute(userRequest, tokenResponse.AccessToken); if (userResponse.IsError) { throw new UserFriendlyException("认证失败,请重试"); } thirdPartyUser = new ThirdPartyUser { OpenId = tokenResponse.UserId, AccessToken = tokenResponse.AccessToken, Name = userResponse.RealName, NickName = userResponse.NickName, ThirdParty = "Alipay" }; _thirdPartyUserRepository.Insert(thirdPartyUser); CurrentUnitOfWork.SaveChanges(); } thirdPartyUser.AccessToken = tokenResponse.UserId; CurrentUnitOfWork.SaveChanges(); return(new ThirdPartyAuthorizeResult { ThirdPartyUser = new ThirdPartyUserOutput { UserId = thirdPartyUser.UserId, Name = thirdPartyUser.NickName, NickName = thirdPartyUser.NickName }, Token = $"OpenId={tokenResponse.UserId}&date={DateTime.Now:yyyy-MM-dd HH:mm:ss}&type=Alipay".EncryptQueryString(), Success = thirdPartyUser.UserId > 0, RequireCreateNewUser = thirdPartyUser.UserId == 0 });
public AlipaySystemOauthTokenResponse OauthTokenRequest(string authCode) { AlipaySystemOauthTokenRequest oauthTokenRequest = new AlipaySystemOauthTokenRequest(); oauthTokenRequest.GrantType = AlipaySystemOauthTokenRequest.AllGrantType.authorization_code; oauthTokenRequest.Code = authCode; AlipaySystemOauthTokenResponse oauthTokenResponse = (AlipaySystemOauthTokenResponse)null; try { oauthTokenResponse = new DefaultAopClient(this.serverUrl, this.appId, this.privateKey).Execute <AlipaySystemOauthTokenResponse>((IAopRequest <AlipaySystemOauthTokenResponse>)oauthTokenRequest); } catch (AopException ex) { } return(oauthTokenResponse); }
protected AlipaySystemOauthTokenResponse Get_token(string Code, string companyID) { IAopClient client = new DefaultAopClient(ALiConfig.serviceUrl, ALiConfig.APPID, ALiConfig.privateKey, "json", "1.0", "RSA2", ALiConfig.publicKey, "utf-8", false); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "authorization_code"; request.Code = Code; // request.RefreshToken = "201208134b203fe6c11548bcabd8da5bb087a83b"; AlipaySystemOauthTokenResponse response = client.Execute(request); Console.WriteLine(response.Body); //string Str = GetJson("https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=" + appid + "&code=" + Code + "&grant_type=authorization_code&component_appid=" + OpenPFConfig.Appid + "&component_access_token=" + Util.getComAccessToken() + ""); //OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(Str); //Util.Debuglog(companyID + "服务器token=" + Str, "获取token.txt"); return(response); }
public AlipaySystemOauthTokenResponse OauthTokenRequest(string authCode) { AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest { GrantType = "authorization_code", Code = authCode }; AlipaySystemOauthTokenResponse response = null; try { IAopClient client = new DefaultAopClient(this.serverUrl, this.appId, this.privateKey); response = client.Execute <AlipaySystemOauthTokenResponse>(request); } catch (AopException) { } return(response); }
public AlipaySystemOauthTokenResponse OauthTokenRequest(string authCode) { AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest(); alipaySystemOauthTokenRequest.GrantType = AlipaySystemOauthTokenRequest.AllGrantType.authorization_code; alipaySystemOauthTokenRequest.Code = authCode; AlipaySystemOauthTokenResponse result = null; try { IAopClient aopClient = new DefaultAopClient(this.serverUrl, this.appId, this.privateKey); result = aopClient.Execute <AlipaySystemOauthTokenResponse>(alipaySystemOauthTokenRequest); } catch (AopException var_3_3D) { } return(result); }
public void Run() { IAopClient client = new DefaultAopClient( "https://openapi.alipay.com/gateway.do", "2019101868499001", //app_id privateKey, "json", "1.0", "RSA2", alipayPublicKey, "GBK", false); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "authorization_code"; request.Code = "4b203fe6c11548bcabd8da5bb087a83b"; //request.RefreshToken = "201208134b203fe6c11548bcabd8da5bb087a83b"; AlipaySystemOauthTokenResponse response = client.Execute(request); System.Console.WriteLine(response.Body); }
/// <summary> /// 获取openId(蚂蚁金服) /// </summary> /// <param name="request">请求参数</param> /// <param name="config">配置</param> /// <returns>结果</returns> public static string GetOpenidFromCode(OpenidFromCodeRequestInfo request, SdkPay.Config config) { const string url = SdkPay.Config.ServerUrl; string appId = config.GetAppId(); string privateKeyPem = config.GetPrivateKeyPem(); const string format = SdkPay.Config.Format; const string signType = SdkPay.Config.SignType; string publicKeyPem = config.GetPublicKeyPemAliPay(); const string charset = SdkPay.Config.Charset; IAopClient client = new DefaultAopClient(url, appId, privateKeyPem, format, charset, signType, publicKeyPem); AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest { GrantType = "authorization_code", Code = request.Code }; AlipaySystemOauthTokenResponse response = client.Execute(alipaySystemOauthTokenRequest); return(response?.UserId); }
public AlipaySystemOauthTokenResponse GetUserIdByCode(string authCode) { IAopClient client = new DefaultAopClient( "https://openapi.alipay.com/gateway.do", "2019101868499001", //app_id privateKey, "json", "1.0", "RSA2", alipayPublicKey, "utf-8", false); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest { GrantType = "authorization_code", Code = authCode }; //request.RefreshToken = "201208134b203fe6c11548bcabd8da5bb087a83b"; AlipaySystemOauthTokenResponse response = client.Execute(request); return(response); }
protected void Page_Load(object sender, EventArgs e) { string auth_code = Request["auth_code"]; string appId = Request["app_id"]; //PayLogHelper.WritePayLog(auth_code + " ------- " + appId); if (appId.Trim() == AliPayConfig.authAppId.Trim()) { IAopClient client = new DefaultAopClient(AliPayConfig.serverUrl, AliPayConfig.authAppId, AliPayConfig.merchant_auth_private_key, "json", "1.0", "RSA2", AliPayConfig.alipay_auth_public_key, AliPayConfig.charset, false); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.Code = auth_code; request.GrantType = "authorization_code"; try { AlipaySystemOauthTokenResponse oauthTokenResponse = client.Execute(request); //PayLogHelper.WritePayLog(oauthTokenResponse.Body); //PayLogHelper.WritePayLog(oauthTokenResponse.UserId); string aliId = oauthTokenResponse.UserId; string mobile = string.Empty; bool isReg = MobileTokenBusiness.IsHasMobile(aliId, out mobile); string isreg = "0"; if (isReg) { isreg = "1"; } Response.Redirect(string.Format("{0}?userId={1}&isreg={2}", AliPayConfig.AliAuthRedirectUrl, aliId, isreg)); } catch (Exception ex) { } } }
/// <summary> /// 获取授权token等信息 /// </summary> /// <param name="code"></param> /// <returns></returns> public async Task <MyJsonResult> AccessTokenAsync(string code) { //定义一个响应的信息 var res = ""; IAopClient client = new DefaultAopClient(ServerUrl, Appid, PriKey, "json", "1.0", "RSA2", PubKey, null, false); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "authorization_code"; request.Code = code; //request.RefreshToken = "201208134b203fe6c11548bcabd8da5bb087a83b"; AlipaySystemOauthTokenResponse response = await client.ExecuteAsync(request); if (response.AccessToken.IsNullOrEmpty()) { myJsonResult.code = (int)MyJsonResultEnum.thirdError; myJsonResult.failMsg = response.SubMsg; return(myJsonResult); } res = response.ToJson(); myJsonResult.rows = res; return(myJsonResult); }
protected void Page_Load(object sender, EventArgs e) { string code = Request.QueryString["auth_code"]; string state = Request.QueryString["state"]; log.Info("code:" + code + "——state:" + state + "--" + alipaycore.config.privateKey); if (!string.IsNullOrEmpty(code)) { try { //string publicKey = ConfigurationManager.AppSettings["publicKey"]; //string privateKey = ConfigurationManager.AppSettings["privateKey"]; //string publicKeyPem = GetCurrentPath() + "public-key.pem"; //string privateKeyPem = GetCurrentPath() + "aop-sandbox-RSA-private-c#.pem"; //log.Info("publicKeyPem:" + publicKeyPem); //log.Info("privateKeyPem:" + privateKeyPem); IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", "2017062307553030", alipaycore.config.privateKey, "json", "1.0", "RSA", alipaycore.config.publicKey, "GBK", false); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "authorization_code"; request.Code = code; //request.RefreshToken = "201208134b203fe6c11548bcabd8da5bb087a83b"; AlipaySystemOauthTokenResponse response = client.Execute(request); //Console.WriteLine(response.Body); string result = response.Body; JObject jobject = (JObject)JsonConvert.DeserializeObject(result); JObject temp = (JObject)jobject["alipay_system_oauth_token_response"]; string userid = temp["user_id"].ToString(); log.Info(response.Body); log.Info("userid:" + userid); } catch (Exception err) { log.Error("err:", err); } } }
public static string GetAccessToken(string companyId, string auth_code, ref string userId) { try { AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest(); request.GrantType = "authorization_code"; request.Code = auth_code; AlipaySystemOauthTokenResponse response = GetDefaultAopClient(companyId).Execute(request); if (response.IsError) { TxtLogServices.WriteTxtLogEx("AliPayApiServices", string.Format("GetAccessToken(),获取用户授权失败:" + auth_code + ":{0}", response.Body)); } else { userId = response.UserId; return(response.AccessToken); } } catch (Exception ex) { TxtLogServices.WriteTxtLogEx("AliPayApiServices", string.Format("GetAccessToken()获取用户授权失败:" + auth_code + ":{0}", ex.Message)); } return(""); }
/// <summary> /// 根据Code获取第三方access_token信息 /// </summary> /// <param name="code"></param> /// <returns></returns> public override ThirdOpenAuthorizeViewModel GetThirdOAuth(string code) { DefaultAopClient client = new DefaultAopClient(AliPayConfig.gatewayUrl, AliPayConfig.AppId, AliPayConfig.privatekey, "json", "1.0", AliPayConfig.sign_type, AliPayConfig.alipublickey, AliPayConfig.charset, false); AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest { Code = code, GrantType = AliPayConfig.granttype }; AlipaySystemOauthTokenResponse oauthTokenResponse = client.Execute(request); if (oauthTokenResponse.IsError) { throw new Exception(oauthTokenResponse.SubMsg); } ThirdOpenAuthorizeViewModel result = new ThirdOpenAuthorizeViewModel { AlipayId = oauthTokenResponse.UserId, Token = oauthTokenResponse.AccessToken, Expires = int.Parse(oauthTokenResponse.ExpiresIn) }; return(result); }
protected override async Task <HandleRequestResult> HandleRemoteAuthenticateAsync() { // 第一步,处理工作 AuthenticationProperties properties = null; var query = Request.Query; // 若用户禁止授权,则重定向后不会带上 auth_code 参数,仅会带上 state 参数 var code = query["auth_code"]; var state = query["state"]; properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(HandleRequestResult.Fail("The oauth state was missing or invalid.")); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties)) { return(HandleRequestResult.Fail("Correlation failed.")); } if (StringValues.IsNullOrEmpty(code)) { return(HandleRequestResult.Fail("Code was not found.")); } // 第二步,通过 Code 获取 Access Token AlipaySystemOauthTokenResponse resAccessToken = null; try { var alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest { Code = code, GrantType = "authorization_code", RefreshToken = "" }; resAccessToken = _alipayService.Execute(alipaySystemOauthTokenRequest); } catch (Exception) { throw; } if (resAccessToken.IsError) { throw new Exception("Error occur when getting access token from Alipay."); } var identity = new ClaimsIdentity(ClaimsIssuer); if (Options.SaveTokens) { var authTokens = new List <AuthenticationToken> { new AuthenticationToken { Name = "access_token", Value = resAccessToken.AccessToken } }; if (!string.IsNullOrEmpty(resAccessToken.RefreshToken)) { authTokens.Add(new AuthenticationToken { Name = "refresh_token", Value = resAccessToken.RefreshToken }); } if (!string.IsNullOrEmpty(resAccessToken.ExpiresIn)) { if (int.TryParse(resAccessToken.ExpiresIn, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { var expiresAt = Clock.UtcNow + TimeSpan.FromSeconds(value); authTokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) }); } } properties.StoreTokens(authTokens); } var ticket = await CreateTicketAsync(identity, properties, ConvertToOAuthTokenResponse(resAccessToken)); if (ticket != null) { return(HandleRequestResult.Success(ticket)); } else { return(HandleRequestResult.Fail("Failed to retrieve user information from remote server.")); } }
/// <summary> /// /// </summary> /// <returns></returns> protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList <string> values = query.GetValues("auth_code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return(null); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties, _logger)) { return(new AuthenticationTicket(null, properties)); } // Check for error if (Request.Query.Get("error") != null) { return(new AuthenticationTicket(null, properties)); } var alipayRequest = new AlipaySystemOauthTokenRequest { Code = code, GrantType = "authorization_code" //GetApiName() }; AlipaySystemOauthTokenResponse alipayResponse = _alipayClient.Execute(alipayRequest); if (alipayResponse.IsError) { _logger.WriteWarning("An error occurred while retrieving an access token."); return(new AuthenticationTicket(null, properties)); } else { // Request the token //var response = JObject.Parse(alipayResponse.Body); //dynamic tokens = new //{ // Response = response, // AccessToken = response["alipay_system_oauth_token_response"].Value<string>("access_token"), // TokenType = response["alipay_system_oauth_token_response"].Value<string>("token_type"), // RefreshToken = response["alipay_system_oauth_token_response"].Value<string>("refresh_token"), // ExpiresIn = response["alipay_system_oauth_token_response"].Value<string>("expires_in") //}; //var Response = response; //var AccessToken = alipayResponse.AccessToken; //var TokenType = response.Value<string>("token_type"); //var RefreshToken = response.alipay_system_oauth_token_response.expires_in; //var ExpiresIn = response.Value<string>("expires_in"); // Get the Alipay user var requestUser = new AlipayUserInfoShareRequest(); AlipayUserInfoShareResponse userinfoShareResponse = _alipayClient.Execute(requestUser, alipayResponse.AccessToken); if (userinfoShareResponse.IsError) { _logger.WriteWarning("An error occurred while retrieving user information."); throw new HttpRequestException("An error occurred while retrieving user information."); } else { //var user = JObject.FromObject(userinfoShareResponse); var context = new AlipayAuthenticatedContext(Context, userinfoShareResponse, alipayResponse.AccessToken, Convert.ToInt32(alipayResponse.ExpiresIn)) { Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType) }; if (!string.IsNullOrEmpty(context.UserId)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } } } catch (Exception ex) { _logger.WriteError(ex.Message); } return(new AuthenticationTicket(null, properties)); }