微信小程序获取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生成小程序码,并合自定义背景图生成推广小程序二维码
前言: 对于小程序大家可能都非常熟悉了,随着小程序的不断普及越来越多的公司都开始推广使用起来了.今天接到一个需求就是生成小程序码,并且于运营给的推广图片合并在一起做成一张漂亮美观的推广二维码,扫码这种 ...
随机推荐
- Python Web框架 bottle flask
Bottle Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块. 1 2 3 4 pip instal ...
- DDD漫想
领域专用语言 领域驱动设计(Domain Driver Design)开发中,最令我震撼的是领域专用语言(Domain specific language),领域专用语言专注于描述当前领域内的业务细节 ...
- 剑指offer二之替换空格
一.题目: 请实现一个函数,将一个字符串中的空格替换成“%20”.例如,当字符串为I love you.则经过替换之后的字符串为I%20love%20You. 二.解题方法: 方法1:采用String ...
- vector源码(参考STL源码--侯捷):空间分配导致迭代器失效
vector源码1(参考STL源码--侯捷) vector源码2(参考STL源码--侯捷) vector源码(参考STL源码--侯捷)-----空间分配导致迭代器失效 vector源码3(参考STL源 ...
- Apache Oltu 实现 OAuth2.0 服务端【授权码模式(Authorization Code)】
要实现OAuth服务端,就得先理解客户端的调用流程,服务提供商实现可能也有些区别,实现OAuth服务端的方式很多,具体可能看 http://oauth.net/code/ 各语言的实现有(我使用了Ap ...
- node mysql插入中文时报错
一开始以为是前端传参.数据类型的问题,于是就直接把sql语句中的参数直接改成字符串值,但发现还是报500错误. 所以,这就排除了前端的问题. 剩下的就是数据库了,发现我的表设置有问题.凡是有中文数据的 ...
- Chapter 2 Open Book——25
"My name is Edward Cullen," he continued. "I didn't have a chance to introduce myself ...
- C# 例子1
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- mongodb操作技巧
1.添加字段或更新值 db.getCollection('test').updateMany( {}, { $set:{ 'createTime':'2017-06-29 08:08', 'updat ...
- maven官方教程
What is Maven? At first glance Maven can appear to be many things, but in a nutshell Maven is an att ...