1、微信小程式獲取Access_token: access_token具體時效看官方文檔。 using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System. ...
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; } } } } }View Code
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); } } } }View Code
網路請求相關:
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; }View Code
/// <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(); }View Code
public static Stream HttpResponseStream(HttpWebResponse response) { try { return response.GetResponseStream(); } catch (Exception ex) { throw new Exception("獲取HttpWebResponse.GetResponseStream異常,"+ex); } }View Code
工具類:
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(); } }View Code
吐槽一下:官方文檔對這個介面的說明不夠完善,很多需要註意點沒有明確,群里也有小伙伴遇到各種問題,如:返回格式沒說明,錯誤原因不明確。
圖片樣式:
介面C生成的二維碼: 介面A生成的小程式碼: