博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
微信小程序获取Access_token和页面URL生成小程序码或二维码
阅读量:6906 次
发布时间:2019-06-27

本文共 9383 字,大约阅读时间需要 31 分钟。

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();        ///         /// 获取Access_token        ///         ///         ///         /// 
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\"}";        ///         /// 接口A: 生成小程序码, 适用于需要的码数量较少的业务场景         ///         /// 
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
{ {
"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); } ///
/// 接口C: 生成二维码, 适用于需要的码数量较少的业务场景 /// ///
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
{ {
"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
///         /// 获取到HttpWebResponse对象        ///         /// url        /// 参数        /// 请求头参数        /// 
public static HttpWebResponse DoPost_WebResponse(string url, Dictionary
dic = null, Dictionary
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    {        ///         /// Stream 转 byte[]        ///         ///         /// 
public static byte[] StreamToBytes(Stream stream) { List
bytes = new List
(); int temp = stream.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = stream.ReadByte(); } return bytes.ToArray(); } }
View Code

 

吐槽一下:官方文档对这个接口的说明不够完善,很多需要注意点没有明确,群里也有小伙伴遇到各种问题,如:返回格式没说明,错误原因不明确。

图片样式:

接口C生成的二维码:                                                                  接口A生成的小程序码:

                                                               

 

转载于:https://www.cnblogs.com/tongyi/p/9518550.html

你可能感兴趣的文章
第八天敏捷冲刺
查看>>
两两交换链表中的节点
查看>>
Fragment与Activity的接口回调
查看>>
VMware虚拟机 Ubuntu 实用技巧 (1) -- 安装VMware Tool
查看>>
抽象类
查看>>
PGXC两阶段提交与事务一致性(1)
查看>>
Mysql 死锁
查看>>
oracle自动内存共享管理测试。修改 oracle 11g SGA_MAX_SIZE。
查看>>
漫谈开发前奏之编译器
查看>>
Codeforces Round #403 (Div. 2)
查看>>
酷酷的单词
查看>>
ProgressDialog的使用及逻辑处理
查看>>
plsql programming 04 条件和顺序控制
查看>>
Java学习之泛型和异常
查看>>
subplot 设置不一样的图片大小和位置
查看>>
PCA(matlab)学习,与记录
查看>>
项目管理培训的一些总结
查看>>
Hibernate 配置属性
查看>>
如何用Beyond Compare设置比较文件夹对齐方式
查看>>
01-HTML基础与进阶-day6-录像280
查看>>