Example #1
0
File: AliPayAPI.cs Project: qdjx/C5
    public static AlipayUserInfoShareResponse alipay_user_info_share(string accessToken)
    {
        var client = GetAlipayClient();
        AlipayUserInfoShareRequest  request  = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response = client.Execute(request, accessToken);

        return(response);
    }
Example #2
0
        /// <summary>
        /// 获取用户的信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task <MyJsonResult> GetUserInfoAsync(string token)
        {
            //构建公共参数
            IAopClient client = new DefaultAopClient(ServerUrl, Appid, PriKey, "json", "1.0", "RSA2", PubKey, null, false);
            AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
            //执行
            AlipayUserInfoShareResponse response = await client.ExecuteAsync(request, token);

            //构建返回的结果
            if (response.Code != "10000")
            {
                myJsonResult.code    = (int)MyJsonResultEnum.thirdError;
                myJsonResult.failMsg = response.SubMsg;
            }
            myJsonResult.rows = response;
            return(myJsonResult);
        }
Example #3
0
 /// <summary>
 /// Initializes a <see cref="AlipayAuthenticatedContext"/>
 /// </summary>
 /// <param name="context">The OWIN environment</param>
 /// <param name="user">The JSON-serialized user</param>
 /// <param name="accessToken">Alipay Access token</param>
 public AlipayAuthenticatedContext(IOwinContext context, AlipayUserInfoShareResponse user, string accessToken, int expiresIn)
     : base(context)
 {
     AccessToken = accessToken;
     ExpiresIn   = TimeSpan.FromSeconds(expiresIn);
     User        = user;
     UserId      = user.UserId;
     UserName    = user.UserName;
     NickName    = user.NickName;
     //RealName = TryGetValue(user, "realname");
     //ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "user_id");
     //ClaimActions.MapJsonKey(ClaimTypes.Name, "nick_name");
     ////【注意】只有is_certified为T的时候才有意义,否则不保证准确性. 性别(F:女性;M:男性)。
     //ClaimActions.MapJsonKey(ClaimTypes.Gender, "gender", ClaimValueTypes.Integer);
     //ClaimActions.MapJsonKey(Claims.Avatar, "avatar");
     //ClaimActions.MapJsonKey(Claims.Province, "province");
     //ClaimActions.MapJsonKey(Claims.City, "city");
     //ClaimActions.MapJsonKey(Claims.IsStudentCertified, "is_student_certified");
     //ClaimActions.MapJsonKey(Claims.UserType, "user_type");
     //ClaimActions.MapJsonKey(Claims.UserStatus, "user_status");
     //ClaimActions.MapJsonKey(Claims.IsCertified, "is_certified");
 }
Example #4
0
 public static m_Alipay_server_UserInfo getUserInfoFromAlipay(string app_id, string 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);
         AlipayUserInfoShareRequest  request  = new AlipayUserInfoShareRequest();
         AlipayUserInfoShareResponse response = client.Execute(request, token);
         var user = JsonConvert.DeserializeObject <m_Alipay_server_UserInfo>(response.Body);
         if (null == user)
         {
             return(null);
         }
         else
         {
             return(user);
         }
     }
     catch (Exception ex)
     {
         //记录日志
     }
     return(null);
 }
Example #5
0
        protected override AuthUser getUserInfo(AuthToken authToken)
        {
            string accessToken = authToken.accessToken;
            AlipayUserInfoShareRequest  request  = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse response = null;

            try
            {
                response = this.aopClient.Execute(request, accessToken);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
            if (response.IsError)
            {
                throw new Exception(response.SubMsg);
            }

            string province = response.Province, city = response.City;
            string location = string.Format("{0} {1}", !province.IsNullOrWhiteSpace() ? "" : province, !city.IsNullOrWhiteSpace() ? "" : city);

            var authUser = new AuthUser();

            authUser.username        = response.UserName.IsNullOrWhiteSpace() ? response.NickName : response.UserName;
            authUser.nickname        = response.NickName;
            authUser.avatar          = response.Avatar;
            authUser.location        = location;
            authUser.uuid            = response.UserId;
            authUser.gender          = GlobalAuthUtil.getRealGender(response.Gender);
            authUser.token           = authToken;
            authUser.source          = source.getName();
            authUser.originalUser    = response;
            authUser.originalUserStr = JsonConvert.SerializeObject(response);
            return(authUser);
        }
        /// <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));
        }