1、微信小程序获取Access_token:
access_token具体时效看官方文档。
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using TT.Utilities; namespace DjwzApi.Com { public class WeChatApi { public static string AppID = TT.Utilities.Config.ConfigureAppConfig.GetAppSettingsKeyValue("AppID"); public static string AppSecret = TT.Utilities.Config.ConfigureAppConfig.GetAppSettingsKeyValue("AppSecret"); private static string Access_token = ""; private static DateTime Expires_in_time = DateTime.Now; static object lockObj = new object(); /// <summary> /// 获取Access_token /// </summary> /// <param name="AppID"></param> /// <param name="AppSecret"></param> /// <returns></returns> public static string GetAccess_token(string AppID = null, string AppSecret = null) { lock (lockObj) { if (string.IsNullOrEmpty(Access_token) || ((DateTime.Now - Expires_in_time).TotalSeconds >= -30)) { lock (lockObj) { Access_token = ""; Expires_in_time = DateTime.Now; AppID = AppID ?? WeChatApi.AppID; AppSecret = AppSecret ?? WeChatApi.AppSecret; string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}"; url = string.Format(url, AppID, AppSecret); var json = ""; try { json = TT.Utilities.Web.HttpClientUti.DoGet(url); } catch (Exception ex) { System.Threading.Tasks.Task.Factory.StartNew(() => utils.LogHelper.WriteLog(ex.Message)); throw new Exception("获取微信端access_token失败," + ex.Message); } //{"access_token":"12_TrAgGuiF64W8XPRXyFRFUK7SjzZptoa3ogS4mGKp-W-ni6dG_OoMNMbm_7q9lhYcx85xh-SNe3BUC_6Lg1H6FDMU7fUsKoG4NwN5EA-NVOCVUZg0OIdTvOmgHMgCxJQ1vWP__VvId4AJ2Bm_QYPdABAFNE","expires_in":7200} dynamic obj = new { access_token = "", expires_in = 0, errcode = 0, errmsg = "" }; obj = TT.Utilities.Json.JsonHelper.DeserializeAnonymousType(json, obj); if (obj.errcode == 0) { Expires_in_time = DateTime.Now.AddSeconds(obj.expires_in); Access_token = obj.access_token; } return Access_token; } } else { return Access_token; } } } } }
2、获取二维码
这里实现了官网文档中提到的 接口A和接口C
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace DjwzApi.Com { public class WxQrcode { private const string line_color = "{"r":"0","g":"0","b":"0"}"; /// <summary> /// 接口A: 生成小程序码, 适用于需要的码数量较少的业务场景 /// </summary> /// <returns></returns> public static string QrcodeA(string path, int width = 430, bool auto_color = false, string line_color = line_color, bool is_hyaline = false) { string url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={0}"; var ACCESS_TOKEN = WeChatApi.GetAccess_token(); url = string.Format(url, ACCESS_TOKEN); var arg = new Dictionary<string, string> { {"path",path}, {"width",width.ToString()}, //{"auto_color","false"}, //{"line_color",line_color}, //{"is_hyaline",is_hyaline.ToString()}, }; var response = TT.Utilities.Web.HttpRequest.DoPost_WebResponse(url, arg, null, 90, TT.Utilities.Web.HttpContentTypes.HttpContentTypeEnum.JSON); return SaveImg(response); } /// <summary> /// 接口C: 生成二维码, 适用于需要的码数量较少的业务场景 /// </summary> /// <returns></returns> public static string QrcodeC(string path, int width = 430) { string url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={0}"; var ACCESS_TOKEN = WeChatApi.GetAccess_token(); url = string.Format(url, ACCESS_TOKEN); var arg = new Dictionary<string, string> { {"path",path}, {"width",width.ToString()} }; var response = TT.Utilities.Web.HttpRequest.DoPost_WebResponse(url, arg, null, 90, TT.Utilities.Web.HttpContentTypes.HttpContentTypeEnum.JSON); return SaveImg(response); } static string SaveImg(HttpWebResponse response) { if (response.ContentType.ToLower() == "image/jpeg") { var re = TT.Utilities.Web.HttpResponse.HttpResponseStream(response); var bytes = TT.Utilities.StreamUti.ConveertHelper.StreamToBytes(re); string imgName = "ewm" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg"; //文件存储相对于当前应用目录的虚拟目录 string basePath = "/image/"; //获取相对于应用的基目录,创建目录 string imgPath = System.AppDomain.CurrentDomain.BaseDirectory + basePath; //通过此对象获取文件名 //StringHelper.CreateDirectory(imgPath); System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath(basePath + imgName), bytes);//讲byte[]存储为图片 return "/image/" + imgName; } else { //{"errcode":47001,"errmsg":"data format error hint: [Mz435a00280720]"} return TT.Utilities.Web.HttpResponse.HttpResponseString(response); } } } }
网络请求相关:
public static HttpWebRequest CreateHttpWebRequest(string url, int timeoutSecond = 90) { HttpWebRequest request; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { //ServicePointManager.DefaultConnectionLimit = 1000; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Proxy = null; request.ProtocolVersion = HttpVersion.Version11; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); request.Accept = "*/*"; request.KeepAlive = false; request.Timeout = timeoutSecond * 1000; return request; }
/// <summary> /// 获取到HttpWebResponse对象 /// </summary> /// <param name="url">url</param> /// <param name="dic">参数</param> /// <param name="headerDic">请求头参数</param> /// <returns></returns> public static HttpWebResponse DoPost_WebResponse(string url, Dictionary<string, string> dic = null, Dictionary<string, string> headerDic = null, int timeoutSecond = 90 , HttpContentTypes.HttpContentTypeEnum contentType = HttpContentTypes.HttpContentTypeEnum.JSON) { HttpWebRequest request = CreateHttpWebRequest(url, timeoutSecond); request.Method = "POST"; request.ContentType = HttpContentTypes.GetContentType(contentType); if (headerDic != null && headerDic.Count > 0) { foreach (var item in headerDic) { request.Headers.Add(item.Key, item.Value); } } if (dic != null && dic.Count > 0) { var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dic); byte[] buffer = Encoding.UTF8.GetBytes(jsonStr); request.ContentLength = buffer.Length; try { request.GetRequestStream().Write(buffer, 0, buffer.Length); } catch (WebException ex) { throw ex; } } else { request.ContentLength = 0; } return (HttpWebResponse)request.GetResponse(); }
public static Stream HttpResponseStream(HttpWebResponse response) { try { return response.GetResponseStream(); } catch (Exception ex) { throw new Exception("获取HttpWebResponse.GetResponseStream异常,"+ex); } }
工具类:
public class ConveertHelper { /// <summary> /// Stream 转 byte[] /// </summary> /// <param name="stream"></param> /// <returns></returns> public static byte[] StreamToBytes(Stream stream) { List<byte> bytes = new List<byte>(); int temp = stream.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = stream.ReadByte(); } return bytes.ToArray(); } }
吐槽一下:官方文档对这个接口的说明不够完善,很多需要注意点没有明确,群里也有小伙伴遇到各种问题,如:返回格式没说明,错误原因不明确。
图片样式:
接口C生成的二维码: 接口A生成的小程序码: