使用C# 與Xero OAuth 互動 整合

來源:互聯網
上載者:User
本文主要介紹和xero OAuth的整合過程,以後再與其他第三方的OAuth的整合過程也將類似。 另外由於xero官方的文檔非常有限,因此有必要進行總結一下。
Xero 是一個財務系統,可用於替代產品賬單模組的實現。
www.xero.com

瞭解OAuth :

http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

http://baike.baidu.com/view/6619164.htm


概括起來就是,對於SystemA使用者要訪問systemB的資源,sysB的使用者可以指定將SysB中的哪些部分(模組)暴露出來給SysA進行訪問,同時會給sysA一個token和認證。每次sysA訪問sysB時需要帶上token以及認證。

1. 安裝 nuget pkg :


2. 建立wapper 來封裝互動過程

前提:
1.需要已經安裝認證
2.已經得到了key/secret

public class XeroApiAdapter    {        private readonly IXeroApiParameter _parameter;        private const string PARTNER_URL = "https://api-partner.network.xero.com";        private const string BASE_URL = "https://api.xero.com";        public XeroCoreApi CoreApi { get; private set; }        private readonly X509Certificate2 _signingCertificate;        private readonly X509Certificate2 _partnerCertificate;        /// <summary>        ///         /// </summary>        /// <param name="parameter"></param>        public XeroApiAdapter(IXeroApiParameter parameter)        {            _signingCertificate = XeroOAuthSettings.Fetch.SigningCertificate.SelectedCertificate;            if (_signingCertificate == null)            {                throw new Exception("Signing certificate must be defined");            }            _partnerCertificate = XeroOAuthSettings.Fetch.PartnerCertificate.SelectedCertificate;            if (_partnerCertificate == null)            {                throw new Exception("partner certificate must be defined");            }            _parameter = parameter;            var user = new ApiUser { OrganisationId = parameter.NetworkId, Name = parameter.NetworkId };            CoreApi = new XeroCoreApi(PARTNER_URL,            new RuPartnerAuthethicator(PARTNER_URL, BASE_URL, XeroTokenServices.Do,                _signingCertificate, _partnerCertificate),            new Consumer(parameter.ConsumerKey, parameter.ConsumerSecret), user,            new DefaultMapper(), new DefaultMapper());        }        public PartnerMvcAuthenticator MvcAuthenticator(string callBack)        {            return new PartnerMvcAuthenticator(PARTNER_URL, BASE_URL, callBack, XeroTokenServices.Do,                _signingCertificate, _partnerCertificate,                new Consumer(_parameter.ConsumerKey, _parameter.ConsumerSecret),                XeroRequestTokenServices.Do);        }            }

RuPartnerAuthethicator.cs (主要用於over write xero de AuthorizeUser函數,預設會開啟瀏覽器):

public class RuPartnerAuthethicator : PartnerAuthenticator    {        public RuPartnerAuthethicator(string baseUri, string authorizeUri, ITokenStore store, string signingCertificatePath, string certificatePath, string password) : base(baseUri, authorizeUri, "", store, signingCertificatePath, certificatePath, password)        {        }        public RuPartnerAuthethicator(string baseUri, string authorizeUri, ITokenStore store, X509Certificate2 signingCertificate, X509Certificate2 certificate) : base(baseUri, authorizeUri, "", store, signingCertificate, certificate)        {        }        protected override string AuthorizeUser(IToken token)        {            throw new XeroRenewAccessTokenException("Please renew access token");        }    }

3. 實現IToken 介面,分為Request Token和 Access Token。 即請求token和訪問token,訪問token需要做持久化,請求token可存記憶體中。

 public class XeroTokenServices : MongoService, ITokenStore    {        public static XeroTokenServices Do        {            get            {                return new XeroTokenServices();            }        }        private XeroTokenServices()        {        }        private MongoCollection<MDXeroToken> XeroTokenStore        {            get            {                return Connection.GetMongoCollection<MDXeroToken>("XeroTokenStore");            }        }        public void Add(IToken token)        {            //Lets delete first as we are not sure if Xero have a delete            Delete(token);            XeroTokenStore.Save(new MDXeroToken(token));        }        public void Delete(IToken token)        {            XeroTokenStore.Remove(Query<MDXeroToken>.EQ(x => x.UserId, token.UserId));        }        public IToken Find(string user)        {            var token = XeroTokenStore.FindOne(Query<MDXeroToken>.EQ(x => x.UserId, user));                        return token;        }        public void ClearTokenForNetwork(string id)        {            XeroTokenStore.Remove(Query<MDXeroToken>.EQ(x => x.UserId, id));        }    }    public class XeroRequestTokenServices : MongoService, ITokenStore    {        public static XeroRequestTokenServices Do        {            get { return new XeroRequestTokenServices(); }        }        private XeroRequestTokenServices()        {        }        private MongoCollection<MDXeroToken> XeroTokenStore        {            get            {                return Connection.GetMongoCollection<MDXeroToken>("XeroRequestTokenStore");            }        }        public void Add(IToken token)        {            //Lets delete first as we are not sure if Xero have a delete            Delete(token);            XeroTokenStore.Save(new MDXeroToken(token));        }        public void Delete(IToken token)        {            XeroTokenStore.Remove(Query<MDXeroToken>.EQ(x => x.UserId, token.UserId));        }        public IToken Find(string user)        {            return XeroTokenStore.FindOne(Query<MDXeroToken>.EQ(x => x.UserId, user));        }        public void ClearTokenForNetwork(string id)        {            XeroTokenStore.Remove(Query<MDXeroToken>.EQ(x => x.UserId, id));        }    }

4. 指定callback 函數, 在xero配置callback domain

4.1 添加Application

4.2 配置call back domain , 產生key , secret

4.3 Call back 函數:

public ActionResult Authorize(string oauth_token, string oauth_verifier, string org, string redirect)        {            var network = NetworksManagment.Do.GetNetwork(Tenant.NetworkId);            var xeroApi = new XeroApiAdapter(new XeroApiParam(network));            var authenthicator = xeroApi.MvcAuthenticator("");            try            {                // - call XeroTokenServices.Add and store the token in MDXeroToken                var token = authenthicator.RetrieveAndStoreAccessToken(network.Id, oauth_token, oauth_verifier, org);                var organization = xeroApi.CoreApi.Organisation;                ...                TempData.AddNotification(NotifcationType.Success, "Xero connected successfully");            }            catch (Exception ex)            {                TempData.AddNotification("Error connecting to Xero", ex);            }            if (string.IsNullOrEmpty(redirect))            {                return RedirectToAction("Index");            }                        return Redirect(redirect);        }

xero 官方 git:
https://github.com/XeroAPI/Xero-Net

以上就是使用C# 與Xero OAuth 互動 整合 的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.