测试号申请和Token获取

测试号申请

访问地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

我们要做公众号开发,首先需要注册一个公众平台测试账号,大家可以访问上面的地址注册测试账号。测试号申请门槛不高,只需要有一个微信号就可以。

公众号分为:服务号和订阅号。 服务号功能更多,限制相对少一些,服务号是独立账号。 订阅号在微信APP内会被集中收纳在一起。

申请这两类正式账号,如果需要微信认证,费用大概300元一年。 企业、事业单位可以申请服务号。一般个人可以申请订阅号。

测试号信息
appID wx****************
appsecret 42a55************9265

因为微信公众号开发,是调用微信服务器提供的各种接口,使用post、get等方式来获取数据。 数据的交互使用的是json或者xml文档,所以我们先封装好这些帮助类。

帮助类

缓存类:用来存储一些不经常刷新的数据,可以使用该类来缓存

public class CacheHelper
{
    private static MemoryCache cache = MemoryCache.Default;
    /// <summary>
    /// 设置缓存(绝对过期时间),默认两个小时
    /// </summary>
    /// <param name="key"></param>
    /// <param name="obj"></param>
    /// <param name="seconds"></param>
    public static void Set(string key, object obj, int seconds = 7200)
    {
        var policy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTime.Now.AddSeconds(seconds)
        };

        cache.Set(key, obj, policy);
    }

    /// <summary>
    /// 获取缓存,不存在返回null
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public static T Get<T>(string key) where T : class
    {
        try
        {
            return (T)cache[key];
        }
        catch (Exception)
        {
            return null;
        }
    }

    /// <summary>
    /// 取缓存项,如果不存在则返回空
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public static T GetCacheItem<T>(String key)
    {
        try
        {
            return (T)cache[key];
        }
        catch
        {
            return default(T);
        }
    }

    /// <summary>
    /// 移除指定键的缓存项
    /// </summary>
    /// <param name="key"></param>
    public static void RemoveCacheItem(string key)
    {
        try
        {
            cache.Remove(key);
        }
        catch
        {
        }
    }

    /// <summary>
    /// 是否包含指定键的缓存项
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static bool Contains(string key)
    {
        return cache.Contains(key);
    }
}
Code language: PHP (php)

SHA1加密类:用来让微信服务器和我们的服务器进行验证的方法

public static class EnCodeHelper
{
    /// <summary>
    /// 基于Sha1的自定义加密字符串方法:输入一个字符串,返回一个由40个字符组成的十六进制的哈希散列(字符串)。
    /// </summary>
    /// <param name="str">要加密的字符串</param>
    /// <returns>加密后的十六进制的哈希散列(字符串)</returns>
    public static string ToSha1(this string str)
    {
        var buffer = Encoding.UTF8.GetBytes(str);
        var data = SHA1.Create().ComputeHash(buffer);

        var sb = new StringBuilder();
        foreach (var t in data)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString();
    }
}
Code language: PHP (php)

HTTP请求:这个不用多说了,用来和微信服务器打交道的请求接口

public class HttpHelper
{
    /// <summary>
    /// 获取地址的html文档
    /// </summary>
    /// <param name="Url">URL地址</param>
    /// <returns></returns>
    public static string HttpGet(string Url, Encoding encoding = null)
    {
        string sRslt = null;
        WebRequest oWebRqst = null;
        WebResponse oWebRps = null;
        StreamReader oStreamRd = null;
        try
        {
            oWebRqst = WebRequest.Create(Url);
            oWebRqst.Timeout = 5000;
            oWebRps = oWebRqst.GetResponse();
            if (encoding == null)
            {
                encoding = Encoding.GetEncoding("UTF-8");
            }
            oStreamRd = new StreamReader(oWebRps.GetResponseStream(), encoding);
            sRslt = oStreamRd.ReadToEnd();
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            if (oStreamRd != null)
            {
                oStreamRd.Close();
            }
            if (oWebRps != null)
            {
                oWebRps.Close();
            }
        }
        return sRslt;
    }
}
Code language: PHP (php)

JSON帮助类:用来序列化和反序列化的

public class JsonHelper
{
    public static T DeserializeJson<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
}
Code language: PHP (php)

定义一个专门用来存储API接口的类

public static class WeiXinAPI
{
    public static string Token = "[https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}](https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1})";

    public static string UserList = "[https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}](https://api.weixin.qq.com/cgi-bin/user/get?access_token={0})";
}
Code language: PHP (php)

定义一个专门用来存储缓存键的类

public class CacheKeys
{
    public static string Token = "Get_Token";
}
Code language: PHP (php)

WPF项目的搭建

创建一个WPF项目

<Window x:Class="WeiXin.MainWindow"
        xmlns="[http://schemas.microsoft.com/winfx/2006/xaml/presentation](http://schemas.microsoft.com/winfx/2006/xaml/presentation)"
        xmlns:x="[http://schemas.microsoft.com/winfx/2006/xaml](http://schemas.microsoft.com/winfx/2006/xaml)"
        xmlns:d="[http://schemas.microsoft.com/expression/blend/2008](http://schemas.microsoft.com/expression/blend/2008)"
        xmlns:mc="[http://schemas.openxmlformats.org/markup-compatibility/2006](http://schemas.openxmlformats.org/markup-compatibility/2006)"
        xmlns:local="clr-namespace:WeiXin"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="150"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="50"/>
                <RowDefinition Height="50"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <StackPanel Grid.Row="1">
                <Button Content="获取用户列表" Width="150" HorizontalAlignment="Left" Height="50" Click="Button_Click"/>
            </StackPanel>
        </Grid>
        <DataGrid Grid.Row="1">
        </DataGrid>
    </Grid>
</Window>
Code language: HTML, XML (xml)

获取Token-使用缓存来保存两小时失效

我们调用微信的这些API接口,需要有一个令牌,就是token。这个token我们只需要获取一次,两个小时之内都有效。两个小时后我们只需要再重新获取一次就可以。 我们获取token需要appid和appsecret,这两个相当于账号和密码。 大家可以参考 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

使用Appsetting来记录

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="appID" value="wx51e*****6"/>
    <add key="appSecret" value="42a5****9265"/>
  </appSettings>
  <startup>
       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
</configuration>
Code language: HTML, XML (xml)
public class TokenHelper
{
    public static AccessToken GetTokenInfo()
    {
        if (CacheHelper.Contains(CacheKeys.Token))
        {
            var token = CacheHelper.Get<AccessToken>(CacheKeys.Token);
            if (token!=null)
            {
                return token;
            }
        }

        string appID = ConfigurationManager.AppSettings["appID"];
        string appSecret = ConfigurationManager.AppSettings["appSecret"];
        if (string.IsNullOrEmpty(appID)||string.IsNullOrEmpty(appSecret))
        {
            return new AccessToken() { errmsg = "请先配置AppSetting",errcode = -100 };
        }
        string url = string.Format(WeiXinAPI.Token, appID, appSecret);

        string json = string.Empty;
        try
        {
            json = HttpHelper.HttpGet(url);
        }
        catch (Exception)
        {
            throw;
        }
        AccessToken obj = JsonHelper.DeserializeJson<AccessToken>(json);
        CacheHelper.Set(CacheKeys.Token,obj);
        return obj;
    }
}
Code language: PHP (php)
/// <summary>
/// [https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html](https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html)
/// </summary>
public class AccessToken
{
    public string access_token { set; get; }
    public int expires_in { set; get; }
    public int errcode { set; get; }
    public string errmsg { set; get; }
}
Code language: JavaScript (javascript)

调用

private void Button_Click(object sender, RoutedEventArgs e)
{
    AccessToken accessToken = TokenHelper.GetTokenInfo();
}
Code language: JavaScript (javascript)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注