Exemplo n.º 1
0
        public IHttpActionResult ForceUpdate()
        {
            var componentSvc = new ComponentTokenService();
            var beforeUpdate = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(componentSvc.GetToken()));
            var afterUpdate  = componentSvc.ForceRefresh();
            var result       = new { before = beforeUpdate, after = afterUpdate };

            return(Ok(result));
        }
Exemplo n.º 2
0
        public ActionResult UserAuth(string code, string state, string appid, string returnUrl, string scope)
        {
            try
            {
                if (string.IsNullOrEmpty(appid))
                {
                    return(Content("无效的请求"));
                }

                if (string.IsNullOrEmpty(returnUrl))
                {
                    return(Content("Error: can't find url parameter <b>returnUrl</b>"));
                }

                if (returnUrl.Contains("%") == false)
                {
                    returnUrl = HttpUtility.UrlEncode(returnUrl).Replace("+", "%20");
                }

                //TODO: verify if returnUrl domain is legal or not.

                string componentAppId = ConfigurationManager.AppSettings["AppId"];

                string wxAuthRedirectUri = ConfigurationManager.AppSettings["UserAuthRedirectUri"] + "?returnUrl=" + returnUrl;
                string wxAuthUrlFmt      =
                    "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state={2}&component_appid={3}#wechat_redirect";

                bool silentAuth = !string.IsNullOrEmpty(scope) && scope.ToLower() == "snsapi_base";
                //state is null indicates it's first time to get here.
                if (string.IsNullOrEmpty(state))
                {
                    //TODO: silent user auth here.
                    if (silentAuth)
                    {
                        wxAuthUrlFmt =
                            "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}&component_appid={3}#wechat_redirect";
                        wxAuthRedirectUri += "&scope=snsapi_base";
                    }

                    //throw new Exception("wx based on "+ wxAuthRedirectUri);
                    //第一次进入,跳转到微信授权页
                    string wxAuthUrl = string.Format(wxAuthUrlFmt, appid, HttpUtility.UrlEncode(wxAuthRedirectUri).Replace("+", "%20"),
                                                     "wxAuth1stStep", componentAppId);

                    return(Redirect(wxAuthUrl));
                }

                if (string.IsNullOrEmpty(code))
                {
                    // user reject the auth
                    return(Content("用户未授权,无法继续。"));
                }
                var cts = new ComponentTokenService();
                //通过code换取access_token
                var    componentToken      = cts.GetToken();
                string wxAccessTokenUrlFmt =
                    "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={0}&code={1}&grant_type=authorization_code&component_appid={2}&component_access_token={3}";
                string wxAccessTokenUrl = string.Format(wxAccessTokenUrlFmt, appid, code, componentAppId,
                                                        componentToken.ComponentAccessToken);

                string accessTokenJsonStr = string.Empty;

                HttpClient client = new HttpClient();

                accessTokenJsonStr =
                    client.GetStringAsync(wxAccessTokenUrl)
                    .Result;         //Senparc.CO2NET.HttpUtility.RequestUtility.HttpGet(wxAccessTokenUrl, null);

                var accessTokenJsonObj = JObject.Parse(accessTokenJsonStr);
                var accessCode         = accessTokenJsonObj.GetValue("access_token");
                var openid             = accessTokenJsonObj.GetValue("openid");
                if (openid == null)
                {
                    //log & retry
                    string logmsg = "RETRY: \r\n openid is null \r\n Token Url: " + wxAccessTokenUrl + " \r\n Token info \r\n " +
                                    JsonConvert.SerializeObject(componentToken) + " \r\n accessTokenJsonStr \r\n" +
                                    accessTokenJsonStr;


                    cts.ForceRefresh();
                    componentToken = cts.GetToken();

                    wxAccessTokenUrl = string.Format(wxAccessTokenUrlFmt, appid, code, componentAppId,
                                                     componentToken.ComponentAccessToken);

                    logmsg += "\r\n after update the token url is " + wxAccessTokenUrl;
                    Log(logmsg);

                    //RETRY:
                    accessTokenJsonStr =
                        client.GetStringAsync(wxAccessTokenUrl)
                        .Result;     //Senparc.CO2NET.HttpUtility.RequestUtility.HttpGet(wxAccessTokenUrl, null);

                    accessTokenJsonObj = JObject.Parse(accessTokenJsonStr);
                    accessCode         = accessTokenJsonObj.GetValue("access_token");
                    openid             = accessTokenJsonObj.GetValue("openid");
                }

                if (!silentAuth)
                {
                    //获取用户的基本信息
                    string wxUserInfoUrlFmt =
                        "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
                    string wxUserInfoUrl = string.Format(wxUserInfoUrlFmt, accessCode, openid);

                    string userInfoJsonStr = client.GetStringAsync(wxUserInfoUrl).Result; //Senparc.CO2NET.HttpUtility.RequestUtility.HttpGet(wxUserInfoUrl, null);
                    var    userInfoJsonObj = JObject.Parse(userInfoJsonStr);

                    string openIdStr = openid.ToString();

                    string decodeReturnUrl = HttpUtility.UrlDecode(returnUrl);
                    //append infos
                    string redirectUrl = appendUserInfo(decodeReturnUrl, userInfoJsonObj);

                    return(Redirect(redirectUrl));
                }
                else
                {
                    string decodeReturnUrl        = HttpUtility.UrlDecode(returnUrl);
                    bool   alreadyHasUrlParameter = decodeReturnUrl.Contains("?");
                    if (!alreadyHasUrlParameter)
                    {
                        decodeReturnUrl += "?openid=" + openid;
                    }
                    else
                    {
                        decodeReturnUrl += "&openid=" + openid;
                    }
                    return(Redirect(decodeReturnUrl));
                }
            }
            catch (Exception e)
            {
                string msg = e.ToString();
                Log(msg);

                return(Content("请刷新重试"));
            }
        }