예제 #1
0
 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);
 }
예제 #2
0
        /// <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);
        }
예제 #3
0
        /**
         * 微信的特殊性,此时返回的信息同时包含 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);
        }
예제 #4
0
        public void TestRefreshToken()
        {
            AlipaySystemOauthTokenResponse response = Factory.Base.OAuth().RefreshToken("1234567890");

            Assert.AreEqual(response.Code, "40002");
            Assert.AreEqual(response.Msg, "Invalid Arguments");
            Assert.AreEqual(response.SubCode, "isv.refresh-token-invalid");
            Assert.AreEqual(response.SubMsg, "刷新令牌refresh_token无效");
            Assert.NotNull(response.HttpBody);
        }
예제 #5
0
        public void TestGetToken()
        {
            AlipaySystemOauthTokenResponse response = Factory.Base.OAuth().GetToken("1234567890");

            Assert.AreEqual(response.Code, "40002");
            Assert.AreEqual(response.Msg, "Invalid Arguments");
            Assert.AreEqual(response.SubCode, "isv.code-invalid");
            Assert.AreEqual(response.SubMsg, "授权码code无效");
            Assert.NotNull(response.HttpBody);
        }
예제 #6
0
파일: AliPayAPI.cs 프로젝트: qdjx/C5
    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);
    }
예제 #7
0
파일: AliPayAPI.cs 프로젝트: qdjx/C5
    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);
    }
예제 #8
0
        /// <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
            });
예제 #9
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);
        }
예제 #10
0
        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);
        }
예제 #11
0
        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);
        }
예제 #12
0
        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);
        }
예제 #13
0
        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);
        }
예제 #14
0
        /// <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);
        }
예제 #15
0
        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);
        }
예제 #16
0
        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)
                {
                }
            }
        }
예제 #17
0
        /// <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);
        }
예제 #18
0
        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);
                }
            }
        }
예제 #19
0
 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("");
 }
예제 #20
0
        /// <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);
        }
        /// <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));
        }
        public void AlipayLoginAction(SiteSettings site)
        {
            if (string.IsNullOrEmpty(AlipayFuwuConfig.appId) && !AlipayFuwuConfig.CommSetConfig(site.AlipayAppid, this.Page.Server.MapPath("~/"), "GBK"))
            {
                this.WriteFuwuError(this.Page.Request.QueryString.ToString(), "服务窗口参数配置不准确!");
                this.Page.Response.Redirect(Globals.ApplicationPath + "/UserLogin.aspx");
            }
            string str  = this.Page.Request.QueryString["auth_code"];
            string str2 = this.Page.Request.QueryString["scope"];

            if (!string.IsNullOrEmpty(str2) && !string.IsNullOrEmpty(str))
            {
                this.WriteFuwuError(this.Page.Request.QueryString.ToString(), "已授权");
                AlipaySystemOauthTokenResponse oauthTokenResponse = AliOHHelper.GetOauthTokenResponse(str);
                this.WriteFuwuError(AliOHHelper.SerializeObject(oauthTokenResponse, true), "获取AccessToken");
                if (((oauthTokenResponse != null) && !oauthTokenResponse.IsError) && (oauthTokenResponse.AccessToken != null))
                {
                    string  alipayUserId = oauthTokenResponse.AlipayUserId;
                    string  openId       = "";
                    JObject obj2         = JsonConvert.DeserializeObject(oauthTokenResponse.Body) as JObject;
                    if (obj2["alipay_system_oauth_token_response"]["user_id"] != null)
                    {
                        openId = obj2["alipay_system_oauth_token_response"]["user_id"].ToString();
                    }
                    if (this.HasLogin(openId, "fuwu") || this.HasLogin(alipayUserId, "fuwu"))
                    {
                        MemberInfo openIdMember = MemberProcessor.GetOpenIdMember(openId, "fuwu");
                        if ((openIdMember == null) || (openIdMember.Status == Convert.ToInt32(UserStatus.DEL)))
                        {
                            this.Page.Response.Redirect(Globals.ApplicationPath + "/logout.aspx");
                        }
                        string alipayOpenid = openIdMember.AlipayOpenid;
                        if (((alipayUserId != "") && (alipayUserId != alipayOpenid)) || string.IsNullOrEmpty(alipayOpenid))
                        {
                            openIdMember.AlipayOpenid = alipayUserId;
                            MemberProcessor.SetAlipayInfos(openIdMember);
                        }
                        this.setLogin(openIdMember.UserId);
                        this.WriteFuwuError("已存在用户登入!", openId);
                    }
                    else
                    {
                        AlipayUserUserinfoShareResponse alipayUserUserinfo = AliOHHelper.GetAlipayUserUserinfo(oauthTokenResponse.AccessToken);
                        this.WriteFuwuError(AliOHHelper.SerializeObject(alipayUserUserinfo, true), "获取用户信息");
                        string str7     = "";
                        string realName = "";
                        string avatar   = "";
                        if ((alipayUserUserinfo != null) && !alipayUserUserinfo.IsError)
                        {
                            avatar = alipayUserUserinfo.Avatar;
                            if (alipayUserUserinfo.RealName != null)
                            {
                                realName = alipayUserUserinfo.RealName;
                            }
                            if (string.IsNullOrEmpty(alipayUserId))
                            {
                                alipayUserId = alipayUserUserinfo.UserId;
                            }
                            if (string.IsNullOrEmpty(openId))
                            {
                                JObject obj3 = JsonConvert.DeserializeObject(alipayUserUserinfo.Body) as JObject;
                                if (obj3["alipay_user_id"] != null)
                                {
                                    openId = obj3["alipay_user_id"].ToString();
                                }
                            }
                        }
                        str7 = "FW*" + openId.Substring(10);
                        string     generateId = Globals.GetGenerateId();
                        MemberInfo member     = new MemberInfo {
                            GradeId        = MemberProcessor.GetDefaultMemberGrade(),
                            UserName       = str7,
                            CreateDate     = DateTime.Now,
                            SessionId      = generateId,
                            SessionEndTime = DateTime.Now.AddYears(10),
                            UserHead       = avatar,
                            AlipayAvatar   = avatar,
                            AlipayLoginId  = str7,
                            AlipayOpenid   = alipayUserId,
                            AlipayUserId   = openId,
                            AlipayUsername = realName
                        };
                        HttpCookie cookie = HttpContext.Current.Request.Cookies["Vshop-ReferralId"];
                        if (cookie != null)
                        {
                            member.ReferralUserId = Convert.ToInt32(cookie.Value);
                        }
                        else
                        {
                            member.ReferralUserId = 0;
                        }
                        member.Password = HiCryptographer.Md5Encrypt("888888");
                        MemberProcessor.CreateMember(member);
                        MemberInfo info3 = MemberProcessor.GetMember(generateId);
                        this.setLogin(info3.UserId);
                    }
                }
                else
                {
                    this.Page.Response.Redirect(Globals.ApplicationPath + "/UserLogin.aspx?returnUrl=" + Globals.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri.ToString()));
                }
            }
            else if (!string.IsNullOrEmpty(str2))
            {
                this.WriteFuwuError(this.Page.Request.QueryString.ToString(), "拒绝授权");
                this.Page.Response.Redirect(Globals.ApplicationPath + "/UserLogin.aspx");
            }
            else
            {
                string msg = AliOHHelper.AlipayAuthUrl(HttpContext.Current.Request.Url.ToString().Replace(":" + HttpContext.Current.Request.Url.Port, ""), site.AlipayAppid, "auth_userinfo");
                this.WriteFuwuError(msg, "用户登入授权的路径");
                this.Page.Response.Redirect(msg);
            }
        }
예제 #23
0
        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."));
            }
        }
예제 #24
0
        private OAuthTokenResponse ConvertToOAuthTokenResponse(AlipaySystemOauthTokenResponse alipayTokenResponse)
        {
            var payload = JObject.Parse(JsonConvert.SerializeObject(alipayTokenResponse));

            return(OAuthTokenResponse.Success(payload));
        }
예제 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string code = "";
                if (Request.QueryString["auth_code"] != null && Request.QueryString["auth_code"] != "")
                {
                    code = Request.QueryString["auth_code"].ToString();
                    Util.Debuglog("code=" + code + ";state=" + Request.QueryString["state"], "获取参数.txt");
                    string[] param = Request.QueryString["state"].ToString().Split('|');
                    if (param.Length != 4)
                    {
                        //Response.Write("<span style='color:#FF0000;font-size:20px'>" + "参数不全请重试" + "</span>");
                    }
                    //9|14|43|334|0|1
                    string    money           = param[0]; //9
                    string    companyID       = param[1]; //14
                    string    mechineID       = param[2]; //43
                    string    productID       = param[3]; //334
                    string    dgOrderDetailID = param[4]; //0
                    string    type            = param[5]; //1
                    string    sftj            = param[6]; //1 是特价
                    string    sql2            = "select * from asm_company where id=" + companyID;
                    DataTable d1 = DbHelperSQL.Query(sql2).Tables[0];
                    if (d1.Rows.Count > 0)
                    {
                        appid     = d1.Rows[0]["appId"].ToString();
                        appsecret = d1.Rows[0]["wx_appsecret"].ToString();
                    }

                    AlipaySystemOauthTokenResponse Model = Get_token(code, companyID);
                    //OAuthUser OAuthUser_Model = Get_UserInfo(Model.access_token, Model.openid);
                    if (Model.UserId != null && Model.UserId != "")  //已获取得openid及其他信息
                    {
                        //headImg = OAuthUser_Model.headimgurl.ToString();//头像图片
                        //  name = OAuthUser_Model.nickname;//昵称
                        id = Model.UserId; //opendid
                                           // unionID = OAuthUser_Model.unionid;
                        string province = "";
                        string city     = "";
                        string country  = "";
                        string gender   = "";
                        Util.SetSession("_openID", id);
                        Util.Debuglog("id=" + id, "获取token.txt");//o1_mf1aL2bduKZnTzG1irrfvN0x8
                        string sql = "select * from asm_member where companyID= '" + companyID + "' and aliOpenID='" + id + "'";
                        Util.Debuglog("sql=" + sql, "零售支付用户注册.txt");
                        DataTable dt   = DbHelperSQL.Query(sql).Tables[0];
                        string    sql3 = "select * from asm_tqlist where companyID=" + companyID;
                        Util.Debuglog("sql3=" + sql3, "零售支付用户注册.txt");
                        DataTable d3 = DbHelperSQL.Query(sql3).Tables[0];
                        if (d3.Rows.Count > 0 && d3.Rows[0]["memberprice"].ToString() == "1" && dt.Rows.Count > 0)
                        {
                            //查询该产品是否限时特价

                            money = Util.getNewProductPrice(productID, mechineID, dt.Rows[0]["dj"].ToString());
                        }
                        else
                        {
                            string    sql1 = "select * from asm_product where productID=" + productID;
                            DataTable dt1  = DbHelperSQL.Query(sql1).Tables[0];
                            money = dt1.Rows[0]["price0"].ToString();
                        }
                        //判断限购次数



                        if (dt.Rows.Count <= 0)
                        {
                            string insert = "insert into asm_member(name,phone,province,city,country,AvailableMoney,sumConsume,sumRecharge,createDate,companyID,headurl,nickname,sex,unionID,aliOpenID,consumeCount)"
                                            + " values(N'" + name + "','','" + province + "','" + city + "','" + country + "',0,0,0,'" + DateTime.Now + "','" + companyID + "','" + headImg + "',N'" + name + "','" + gender + "','" + unionID + "','" + id + "',0)";
                            Util.Debuglog(insert, "零售支付用户注册.txt");
                            DbHelperSQL.ExecuteSql(insert);
                            //发送注册成为会员模板消息
                            //wxHelper wx = new wxHelper(companyID);
                            //string data = TemplateMessage.Member_ZC(id, OperUtil.getMessageID(companyID, "OPENTM203347141"), "恭喜您注册成为会员!", name, "恭喜您注册成为会员,您将享受到会员所有权利!");
                            //TemplateMessage.SendTemplateMsg(wx.IsExistAccess_Token(companyID), data);
                        }
                        else
                        {
                            ////更新
                            //string update = "update asm_member set aliOpenID='" + id + "' where unionID='" + unionID + "'";
                            //Util.Debuglog("更新" + update, "是否限购.txt");
                            //DbHelperSQL.ExecuteSql(update);
                            //限购判断
                            if (!Util.xgCount(productID, dt.Rows[0]["id"].ToString(), mechineID))
                            {
                                Util.Debuglog("限购" + unionID, "是否限购.txt");
                                string url13 = "https://wx.bingoseller.com/main/xg.aspx";
                                //限购不让购买
                                Response.Write("<script>window.location.href='" + url13 + "';</script>");
                                return;
                            }
                            if (dt.Rows.Count > 0 && double.Parse(dt.Rows[0]["AvailableMoney"].ToString()) >= double.Parse(money))
                            {
                                string url1 = "https://wx.bingoseller.com/main/wxorbalance.aspx?companyID=" + companyID + "&mechineID=" + mechineID + "&money=" + money + "&unionID=" + unionID + "&openID=" + id + "&productID=" + productID + "&dgOrderDetailID=" + dgOrderDetailID + "&type=" + type + "&sftj=" + sftj;
                                Util.Debuglog("url1=" + url1, "微信+余额.txt");
                                Response.Write("<script>window.location.href='" + url1 + "';</script>");
                                return;
                            }
                        }

                        //到时候复制一份wxorbalance   去掉余额支付就ok了
                        // aliUrl: "https://wx.bingoseller.com/main/getALiUserInfo.aspx?companyID="+<%=companyID%>+"&mechineID="+<%=mechineID%>+"&money="+<%=money%>+"&productID="+<%=productID%>+"&dgOrderDetailID="+<%=dgOrderDetailID%>+"&type="+<%=type%>+"&sftj="+<%=sftj%>,
                        string url12 = "/main/aliorbalance.aspx?companyID=" + companyID + "&mechineID=" + mechineID + "&money=" + money + "&aLiopenID=" + id + "&productID=" + productID + "&dgOrderDetailID=" + dgOrderDetailID + "&type=" + type + "&sftj=" + sftj;
                        Util.Debuglog("url12=" + url12, "微信+余额.txt");
                        Response.Write("<script>window.location.href='" + url12 + "';</script>");
                        return;
                    }
                }
            }
        }
예제 #26
0
        public void AlipayLoginAction(SiteSettings site)
        {
            if (string.IsNullOrEmpty(AlipayFuwuConfig.appId) && !AlipayFuwuConfig.CommSetConfig(site.AlipayAppid, this.Page.Server.MapPath("~/"), "GBK"))
            {
                this.WriteFuwuError(this.Page.Request.QueryString.ToString(), "服务窗口参数配置不准确!");
                this.Page.Response.Redirect(Globals.ApplicationPath + "/UserLogin.aspx");
            }
            string text  = this.Page.Request.QueryString["auth_code"];
            string value = this.Page.Request.QueryString["scope"];

            if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(text))
            {
                this.WriteFuwuError(this.Page.Request.QueryString.ToString(), "已授权");
                AlipaySystemOauthTokenResponse oauthTokenResponse = AliOHHelper.GetOauthTokenResponse(text);
                this.WriteFuwuError(AliOHHelper.SerializeObject(oauthTokenResponse, true), "获取AccessToken");
                if (oauthTokenResponse == null || oauthTokenResponse.IsError || oauthTokenResponse.AccessToken == null)
                {
                    this.Page.Response.Redirect(Globals.ApplicationPath + "/UserLogin.aspx?returnUrl=" + Globals.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri.ToString()));
                    return;
                }
                string  text2   = oauthTokenResponse.AlipayUserId;
                string  text3   = "";
                JObject jObject = JsonConvert.DeserializeObject(oauthTokenResponse.Body) as JObject;
                if (jObject["alipay_system_oauth_token_response"]["user_id"] != null)
                {
                    text3 = jObject["alipay_system_oauth_token_response"]["user_id"].ToString();
                }
                if (this.HasLogin(text3, "fuwu") || this.HasLogin(text2, "fuwu"))
                {
                    MemberInfo openIdMember = MemberProcessor.GetOpenIdMember(text3, "fuwu");
                    if (openIdMember == null || openIdMember.Status == Convert.ToInt32(UserStatus.DEL))
                    {
                        this.Page.Response.Redirect(Globals.ApplicationPath + "/logout.aspx");
                    }
                    string alipayOpenid = openIdMember.AlipayOpenid;
                    if ((text2 != "" && text2 != alipayOpenid) || string.IsNullOrEmpty(alipayOpenid))
                    {
                        openIdMember.AlipayOpenid = text2;
                        MemberProcessor.SetAlipayInfos(openIdMember);
                    }
                    this.setLogin(openIdMember.UserId);
                    this.WriteFuwuError("已存在用户登入!", text3);
                    return;
                }
                string accessToken = oauthTokenResponse.AccessToken;
                AlipayUserUserinfoShareResponse alipayUserUserinfo = AliOHHelper.GetAlipayUserUserinfo(accessToken);
                this.WriteFuwuError(AliOHHelper.SerializeObject(alipayUserUserinfo, true), "获取用户信息");
                string alipayUsername = "";
                string text4          = "";
                if (alipayUserUserinfo != null && !alipayUserUserinfo.IsError)
                {
                    text4 = alipayUserUserinfo.Avatar;
                    if (alipayUserUserinfo.RealName != null)
                    {
                        alipayUsername = alipayUserUserinfo.RealName;
                    }
                    if (string.IsNullOrEmpty(text2))
                    {
                        text2 = alipayUserUserinfo.UserId;
                    }
                    if (string.IsNullOrEmpty(text3))
                    {
                        JObject jObject2 = JsonConvert.DeserializeObject(alipayUserUserinfo.Body) as JObject;
                        if (jObject2["alipay_user_id"] != null)
                        {
                            text3 = jObject2["alipay_user_id"].ToString();
                        }
                    }
                }
                string     text5      = "FW*" + text3.Substring(10);
                string     generateId = Globals.GetGenerateId();
                MemberInfo memberInfo = new MemberInfo();
                memberInfo.GradeId        = MemberProcessor.GetDefaultMemberGrade();
                memberInfo.UserName       = text5;
                memberInfo.CreateDate     = DateTime.Now;
                memberInfo.SessionId      = generateId;
                memberInfo.SessionEndTime = DateTime.Now.AddYears(10);
                memberInfo.UserHead       = text4;
                memberInfo.AlipayAvatar   = text4;
                memberInfo.AlipayLoginId  = text5;
                memberInfo.AlipayOpenid   = text2;
                memberInfo.AlipayUserId   = text3;
                memberInfo.AlipayUsername = alipayUsername;
                HttpCookie httpCookie = HttpContext.Current.Request.Cookies["Vshop-ReferralId"];
                if (httpCookie != null)
                {
                    memberInfo.ReferralUserId = Convert.ToInt32(httpCookie.Value);
                }
                else
                {
                    memberInfo.ReferralUserId = 0;
                }
                memberInfo.Password = HiCryptographer.Md5Encrypt("888888");
                MemberProcessor.CreateMember(memberInfo);
                MemberInfo member = MemberProcessor.GetMember(generateId);
                this.setLogin(member.UserId);
                return;
            }
            else
            {
                if (!string.IsNullOrEmpty(value))
                {
                    this.WriteFuwuError(this.Page.Request.QueryString.ToString(), "拒绝授权");
                    this.Page.Response.Redirect(Globals.ApplicationPath + "/UserLogin.aspx");
                    return;
                }
                string text6 = AliOHHelper.AlipayAuthUrl(HttpContext.Current.Request.Url.ToString().Replace(":" + HttpContext.Current.Request.Url.Port, ""), site.AlipayAppid, "auth_userinfo");
                this.WriteFuwuError(text6, "用户登入授权的路径");
                this.Page.Response.Redirect(text6);
                return;
            }
        }