微信小程序二维码的生成方式
业务需求:
客户想要一个停车优惠券的功能,需要用户微信扫描后,自动跳转到小程序中,首先明确一点,这个操作是需要调微信接口的,下面我们来实现下吧
微信开发文档:
获取不限制的小程序码
//code为优惠券码,唯一值
public void CreateXcxQrCode(string code)
{
try
{
//首先建立文件夹
string strDirPath = System.AppDomain.CurrentDomain.BaseDirectory + "ParkingCouponQrCoderImg";
if (!Directory.Exists(strDirPath))
{
Directory.CreateDirectory(strDirPath);
}
//这里需要使用小程序的appid及appsecret ,用户获取access_token
string URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + _appid + "&secret=" + appsecret + "";
string Date2 = HttpGet(URL);
Newtonsoft.Json.Linq.JObject _jObject = Newtonsoft.Json.Linq.JObject.Parse(Date2);
string access_token = _jObject["access_token"].ToString();
string page = "pages/car/carindex";//跳转的小程序路径
string width = "280";//二维码大小
string _url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(_url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
//这里是参数
string scene = "index=0&code=" + code;
string options = "{\"scene\":\"" + scene + "\",\"page\":\"" + page + "\",\"width\":\"" + width + "\"}";
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(options);
request.ContentLength = payload.Length;
System.IO.Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
byte[] val = StreamToBytes(s);
string strdir_path= strDirPath +"\\"+code + ".png";
System.IO.File.WriteAllBytes(strdir_path, val);
s.Dispose();
writer.Dispose();
string path = string.Format("/ParkingCouponQrCoderImg/{0}.png", code);
//之后就是将path 更新进数据库了
}
catch (System.Exception ex)
{
throw;
}
} if (!Directory.Exists(strDirPath))
{
Directory.CreateDirectory(strDirPath);
}
public byte[] StreamToBytes(System.IO.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();
}