微信小程式 帶引數二維碼 C# asp.net 服務端程式
第一步 獲取access_token:
文件如下:
http請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET程式碼如下:
string result = HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx***********d&secret=a*******************4");
public static string HttpGet(string Url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
其中****改成自己的。具體到微信公眾平臺小程式裡設定開發設定裡找。
第二步 獲取推廣二維碼
文件:
https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN
POST 引數說明
引數 | 預設值 | 說明 |
---|---|---|
path | 不能為空,最大長度 128 位元組 | |
width | 430 | 二維碼的寬度 |
public static void PostMoths(string access_token)
{
string _url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + access_token;
string strURL = _url;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
JsonData _data = new JsonData();
_data["path"] = "pages/index?query=1";
_data["width"] = "430";
string _jso = _data.ToJson();
//string paraUrlCoded = param;
byte[] payload;
//payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
payload = System.Text.Encoding.UTF8.GetBytes(_jso);
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 s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
byte[] tt = StreamToBytes(s);
//將流儲存在c盤test.png檔案下
System.IO.File.WriteAllBytes(@"d:\test.png", tt);
}
///將資料流轉為byte[]
public static byte[] StreamToBytes(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();
}
最後儲存在d盤的圖片就是推廣二維碼,可以講伺服器連線地址發給微信小程式,供微信小程式呼叫。