asp.net生成微信小程序二維碼

asp.net生成微信小程序二維碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

/// <summary>
///微信小程序
/// </summary>
public class wxapp
{
    //pages/login/login?key=
    /// <summary>
    /// 獲取access_token        
    /// </summary>        
    /// <returns></returns>        
    public static string GetAccessToken(string AppID, string AppSecret)
    {
        string token = string.Empty;
        try
        {
            string url = "http://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppID + "&secret=" + AppSecret;
            WebClient wc = new WebClient();
            string result = wc.DownloadString(url);
            if (!string.IsNullOrWhiteSpace(result))
            {
                var jObject = JObject.Parse(result);
                token = jObject["access_token"].ToString();
            }
            return token;
        }
        catch (Exception ex)
        {
            return "";
        }
    }

    /// <summary>
    /// 獲取小程序二維碼
    /// </summary>
    /// <param name="AppID">小程序AppID</param>
    /// <param name="AppSecret">小程序AppSecret</param>
    /// <param name="page">小程序頁面,格式:pages/index/index?id=1</param>
    /// <param name="dir">二維碼保存目錄,格式:/upload/</param>
    /// <returns>二維碼網址</returns>
    public static string Getqrcode(string AppID, string AppSecret, string page, string dir)
    {
        //只能生成10萬個
        //https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
        //var page = "pages/index/index?id=1";
        string token = GetAccessToken(AppID, AppSecret);
        if (!string.IsNullOrEmpty(token))
        {
            try
            {
                //var url = string.Format("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={0}", token);
                var url = string.Format("https://api.weixin.qq.com/wxa/getwxacode?access_token={0}", token);         
                var DataJson = "{";
                //DataJson += string.Format("\"width\":\"{0}\",", "430");//大小,最小280px,最大1280px,默認430
                DataJson += string.Format("\"path\":\"{0}\"", page);//小程序地址,根路徑前不要填加'/',最大128字節
                DataJson += "}";
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(DataJson);
                request.ContentLength = payload.Length;
                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 stream;
                stream = response.GetResponseStream();

                List<byte> bytes = new List<byte>();
                int temp = stream.ReadByte();
                while (temp != -1)
                {
                    bytes.Add((byte)temp);
                    temp = stream.ReadByte();
                }
                byte[] result = bytes.ToArray();

                String dirPath = HttpContext.Current.Server.MapPath(dir);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
                string filePath = dirPath + fileName;
                FileStream fs = new FileStream(filePath, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(result, 0, result.Length);
                bw.Close();
                fs.Close();
                return dir + fileName;
            }
            catch { }
        }
        return string.Empty;
    }
    public static string Getqrcode2(string AppID, string AppSecret, string page, string dir)
    {
        //只能生成10萬個
        //https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html
        //var page = "pages/index/index?id=1";
        string token = GetAccessToken(AppID, AppSecret);
        if (!string.IsNullOrEmpty(token))
        {
            //try
            //{
                var url = string.Format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={0}", token);
                var DataJson = "{";
                //DataJson += string.Format("\"width\":\"{0}\",", "430");//大小,最小280px,最大1280px,默認430
                DataJson += string.Format("\"scene\":\"{0}\",", "key=a-b-cv");
                DataJson += string.Format("\"check_path\":\"{0}\",", "false");
                DataJson += string.Format("\"page\":\"{0}\"", page);//小程序地址,根路徑前不要填加'/',最大128字節
                
                DataJson += "}";
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(DataJson);
                request.ContentLength = payload.Length;
                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 stream;
                stream = response.GetResponseStream();

                List<byte> bytes = new List<byte>();
                int temp = stream.ReadByte();
                while (temp != -1)
                {
                    bytes.Add((byte)temp);
                    temp = stream.ReadByte();
                }
                byte[] result = bytes.ToArray();

                String dirPath = HttpContext.Current.Server.MapPath(dir);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
                string filePath = dirPath + fileName;
                FileStream fs = new FileStream(filePath, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(result, 0, result.Length);
                bw.Close();
                fs.Close();
                return dir + fileName;
            //}
            //catch { }
        }
        return string.Empty;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章