示例#1
0
        public async Task <Result <WeChatUserAccessToken> > GetMobilePlatformUserAccessTokenAsync(string code)
        {
            _options.RequireMobilePlatformSettings();

            return(await GetUserAccessTokenAsync(code, new WeChatAppIdSecret {
                AppId = _options.MobilePlatformAppId,
                AppSecret = _options.MobilePlatformAppSecret
            }));
        }
示例#2
0
        public string CreateMobilePlatformAutoLoginUrl(string redirectUrl, string scope = "snsapi_userinfo")
        {
            _options.RequireMobilePlatformSettings();

            return($"https://open.weixin.qq.com/connect/oauth2/authorize" +
                   $"?appid={_options.MobilePlatformAppId}" +
                   $"&redirect_uri={HttpUtility.UrlEncode(redirectUrl)}" +
                   $"&response_type=code" +
                   $"&scope={scope}" +
                   $"&state={Crypto.Encrypt(DateTime.Now.ToString("yyyy-M-d H:mm:ss"), iv: _options.MobilePlatformAppId!)}" +
                   $"#wechat_redirect");
        }
示例#3
0
        public async Task <Result <WeChatGeneralAccessToken> > GetGeneralAccessTokenAsync()
        {
            _options.RequireMobilePlatformSettings();

            return(await _cache.GetOrCreate <Task <Result <WeChatGeneralAccessToken> > >(_options.MobilePlatformAppId + nameof(GetGeneralAccessTokenAsync), async entry => {
                var url = _options.GeneralAccessTokenManagedCentral ?? "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
                url += url.Contains('?') ? '&' : '?';
                url += $"appid={_options.MobilePlatformAppId}&secret={_options.MobilePlatformAppSecret}";

                try {
                    var json = await DefaultHttpClient.Instance.GetStringAsync(url);
                    var d = JsonConvert.DeserializeObject <dynamic>(json);

                    var ok = d.errcode == null || (int)d.errcode == 0;
                    if (!ok)
                    {
                        entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(1));
                        return new Failure <WeChatGeneralAccessToken>((int)d.errcode + ": " + d.errmsg);
                    }

                    var timeSpan = d.expires_at != null
                                                ? ((DateTime)d.expires_at).Subtract(DateTime.Now)
                                                : TimeSpan.FromSeconds((int)d.expires_in);

                    entry.SetAbsoluteExpiration(timeSpan);

                    return new Success <WeChatGeneralAccessToken> {
                        Data = new WeChatGeneralAccessToken {
                            AccessToken = d.access_token,
                            Expires = DateTime.Now.Add(timeSpan)
                        }
                    };
                }
                catch (Exception e) {
                    return new Failure <WeChatGeneralAccessToken>(e.Message);
                }
            }));
        }