基于senparc实现的微信AccessToken接口全局统一获取

在senparc中实现了AccessToken的全局获取方式,因微信项目涉及跨语言、跨团队,外包方式的合作,需要通过接口方式供合作方调用,现将使用webapi实现的接口分享给大家:

1、自定义一个对外统一的AccessToken

    /// <summary>
/// 自定义一个对外统一的AccessToken
/// </summary>
[Serializable]
public class MPAccessTokenInfo
{
/// <summary>
/// 获取到的凭证
/// </summary>
public string AccessToken { get; set; } /// <summary>
/// 凭证到什么时间过期
/// </summary>
public DateTime AccessTokenExpireTime { get; set; }
}

2、接口方法

//-----------------------------------------------------------------------
// <copyright file="WechatOpenController.cs" company="FenSiShengHuo, Ltd.">
// Copyright (c) 2018 , All rights reserved.
// </copyright>
//----------------------------------------------------------------------- using Senparc.Weixin.Open.Containers;
using System;
using System.Web.Http; namespace DotNet.WeChat.API.Controllers
{
using DotNet.Utilities;
using DotNet.WeChat.API.Common;
using Senparc.Weixin.Containers;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.Open.ComponentAPIs; /// <summary>
/// WechatOpenController
///
/// 修改纪录
///
/// 2018-07-27 版本:1.0 JiShiYu 创建文件。
///
/// <author>
/// <name>JiShiYu</name>
/// <date>2018-07-27</date>
/// </author>
/// </summary> public class WechatController : ApiController
{
/// <summary>
/// 获取微信调用的Token 公众号的方式
/// </summary>
/// <returns></returns>
public JsonResult<MPAccessTokenInfo> GetMPAccessToken()
{
JsonResult<MPAccessTokenInfo> result = new JsonResult<MPAccessTokenInfo>();
result.Status = false;
result.StatusMessage = "没有获取到";
try
{
var accessTokenResult = AccessTokenContainer.GetAccessTokenResult(GlobalSetting.WeixinAppId);
var accessTokenBag = BaseContainer<AccessTokenBag>.TryGetItem(GlobalSetting.WeixinAppId);
MPAccessTokenInfo info = new MPAccessTokenInfo();
info.AccessToken = accessTokenResult.access_token;
info.AccessTokenExpireTime = accessTokenBag.AccessTokenExpireTime;
result.Status = true;
result.Data = info;
result.StatusMessage = "成功获取";
}
catch (Exception ex)
{
NLogHelper.Warn(ex, "WechatOpenController : ApiController GetAccessToken");
result.Status = false;
result.StatusMessage = "异常:" + ex.Message;
} return result;
} }
}

3、接口返回值

{
"Status": true,
"ResultValue": "",
"StatusCode": "OK",
"StatusMessage": "成功获取",
"RecordCount": 0,
"Data": {
"AccessToken": "12_wGwcOStoi9XzRjjCzcwMgubNythtfRGqAn1ntj19I4rR_Rze5vvk5FQyd2ELUmDkFYR47lzkKdnzYzQV1Iqdj0D7tGTguqesXBTHOlLeiUmjMrbGRN_vAG26QFEilArzXBcRMCCcob2_FNr1EEZaAHARRM",
"AccessTokenExpireTime": "2018-07-29 21:21:05"
}
}

返回值中AccessTokenExpireTime表示当前的AccessToken在什么时候过期,第三方调用时可以据此设置缓存,避免每次都调用接口获取,减少接口交互次数。

上一篇:Retrofit学习入门


下一篇:浅析Python装饰器