微信小程序获取Access_token和页面URL生成小程序码或二维码
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 >= -))
{
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 = , errcode = , errmsg = "" };
obj = TT.Utilities.Json.JsonHelper.DeserializeAnonymousType(json, obj);
if (obj.errcode == )
{
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 = , 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, , TT.Utilities.Web.HttpContentTypes.HttpContentTypeEnum.JSON); return SaveImg(response);
} /// <summary>
/// 接口C: 生成二维码, 适用于需要的码数量较少的业务场景
/// </summary>
/// <returns></returns>
public static string QrcodeC(string path, int width = )
{
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, , 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 = )
{
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 * ;
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 =
, HttpContentTypes.HttpContentTypeEnum contentType = HttpContentTypes.HttpContentTypeEnum.JSON)
{
HttpWebRequest request = CreateHttpWebRequest(url, timeoutSecond);
request.Method = "POST";
request.ContentType = HttpContentTypes.GetContentType(contentType); if (headerDic != null && headerDic.Count > )
{
foreach (var item in headerDic)
{
request.Headers.Add(item.Key, item.Value);
}
}
if (dic != null && dic.Count > )
{
var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
byte[] buffer = Encoding.UTF8.GetBytes(jsonStr);
request.ContentLength = buffer.Length;
try
{
request.GetRequestStream().Write(buffer, , buffer.Length);
}
catch (WebException ex)
{
throw ex;
}
}
else
{
request.ContentLength = ;
}
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 != -)
{
bytes.Add((byte)temp);
temp = stream.ReadByte();
}
return bytes.ToArray();
}
}
吐槽一下:官方文档对这个接口的说明不够完善,很多需要注意点没有明确,群里也有小伙伴遇到各种问题,如:返回格式没说明,错误原因不明确。
图片样式:
接口C生成的二维码: 接口A生成的小程序码:
微信小程序获取Access_token和页面URL生成小程序码或二维码的更多相关文章
- 关于.NET HttpClient方式获取微信小程序码(二维码)
随着微信小程序的火热应用,市面上有关小程序开发的需求也多了起来.近来分析了一项生成有关生成微信小程序码的需求——要求扫码跳转到小程序指定页面(带参数):看了下小程序官方文档文档,结合网上的例子,未看到 ...
- C#微信公众号接口开发,灵活利用网页授权、带参数二维码、模板消息,提升用户体验之完成用户绑定个人微信及验证码获取
一.前言 当下微信公众号几乎已经是每个公司必备的,但是大部分微信公众账号用户体验都欠佳,特别是涉及到用户绑定等,需要用户进行复杂的操作才可以和网站绑定,或者很多公司直接不绑定,而是每次都让用户填写账号 ...
- Delphi Mercadopago支付【支持支持获取账户信息和余额、创建商店,商店查询、创建二维码、二维码查询、创建订单、订单查询、订单退款等功能】
作者QQ:(648437169) 点击下载➨Delphi Mercadopago支付 [Delphi Mercadopago支付]支持 支持支持获取账户信息和余额.创建商店,商店查询.创建二维码.二维 ...
- 二维码及二维码接合短URL的应用
二维码 1.什么是二维码? 二维条形码,最早发明于日本,它是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的,在代码编制上巧妙地利用构成计算机内部逻辑基础的“0 ...
- 微信小程序开发——获取小程序带参二维码全流程
前言: 想要获取微信小程序带参数二维码,如这种: 官方文档只说了获取小程序码和二维码的三种接口及调用(参考链接:https://developers.weixin.qq.com/miniprogram ...
- 微信小程序二维码识别
目前市场上二维码识别的软件或者网站越来越多,可是真正方便,无广告的却少之很少. 于是,自己突发奇想做了一个微信二维码识别的小程序. 包含功能: 1.识别二维码 ①普通二维码 ②条形码 ③只是复制解析出 ...
- 微信小程序与内嵌webview之间来回跳转的几点总结,以及二维码的使用
截止到发稿小程序支持的功能,后续如果小程序更新在完善文稿. 1. 小程序可以内嵌组件跳转到h5页面,前提是在小程序后台配置相应的业务域名.新打开的h5页面会替代小程序组件内的其它组件,即为h5不能与小 ...
- 微信小程序扫描普通二维码打开小程序的方法
很久没有写博客了,之前换了一份工作,很久没有做Android开发了,现在转做前端开发了,记录一下遇到的问题及解决的方法. 最近做微信小程序开发,遇到一个需求,后台管理系统生成的问卷和投票会有一个二维码 ...
- .NET生成小程序码,并合自定义背景图生成推广小程序二维码
前言: 对于小程序大家可能都非常熟悉了,随着小程序的不断普及越来越多的公司都开始推广使用起来了.今天接到一个需求就是生成小程序码,并且于运营给的推广图片合并在一起做成一张漂亮美观的推广二维码,扫码这种 ...
随机推荐
- Java 死锁优化
死锁示例1 public class SyncThread implements Runnable{ private Object obj1; private Object obj2; public ...
- 大叔来说说Markdown的使用
强调和高亮背景 中国是伟大的民族! Highlight 中国是`伟大`的民族! ==Highlight== 链接 大叔博客园 [大叔博客园](http://www.cnblogs.com/lori & ...
- docker 使用时一些问题点
1.run 参数 --privileged,默认是关闭的,使用该参数,container 内的 root 拥有真正的 root 权限,否则,container 内的 root 只是外部的一个普通用户权 ...
- sql的存储过程实例--动态根据表数据复制一个表的数据到另一个表
动态根据表数据复制一个表的数据到另一个表 把track表的记录 根据mac_id后两位数字,复制到对应track_? 的表中 如:mac_id=12345678910,则后两位10 对应表为track ...
- markdown简单入门
1.斜体和加粗: 使用下划线"_"或"*"括起来 _内容_ or *内容* 1个_ 或 * 都是斜体,2个则是加粗: 3个既斜体 又加粗,4个以上则没什么变化 ...
- Linux内核升级导致无法启动,Kernel panic - not syncing Unable to mount root fs on unknown block(0,0)
问题原因:内核的某次升级,导致系统无法启动. 首先进入recovery模式:引导界面选择-->Ubuntu高级-->出现的选项中选择能够启动的recovery模式(几个内核版本分别试一下) ...
- 资深程序员的Metal入门教程总结
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由落影发表于云+社区专栏 正文 本文介绍Metal和Metal Shader Language,以及Metal和OpenGL ES的差异 ...
- Apache运维中常用功能配置笔记梳理
Apache 是一款使用量排名第一的 web 服务器,LAMP 中的 A 指的就是它.由于其开源.稳定.安全等特性而被广泛使用.下边记录了使用 Apache 以来经常用到的功能,做此梳理,作为日常运维 ...
- 第一章 Java Web工作原理
一:在本章我们将学到如下的内容 >HTTP协议原理 >服务器端Web编程原理 >Servlet与Web容器 >Java Web应用程序的组成 >Tomcat介绍 一:1. ...
- Java 8 新特性-菜鸟教程 (1) -Java 8 Lambda 表达式
Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性. Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中). 使用 Lambda 表达式可以使代码变的更加 ...