- first get the timestamp of the local computer;
String timestamp = ((DateTime.Now.ToUniversalTime().Ticks – 621355968000000000) / 10000000).ToString();
- Randomly obtain 16 -bit string;
Example:string noncestr = CreateNoncestr();
public static String CreateNoncestr()
{
String chars = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;
String res = “”;
Random rd = new Random();
for (int i = 0; i < 16; i++)
{
res += chars[rd.Next(chars.Length – 1)];
}
return res;
}
- Next to get the return value of the WeChat QR code:
string para = “https://api.weixin.qq.com/cgi-bin/ticket/getticket?timestamp=” + timestamp + “&noncestr=” + noncestr + “&jsapi_ticket=” + ticket + “&url=” + url;
string par = jd_dictsort(para.Split(‘?’).GetValue(1).ToString());
string signa = par.Substring(1, par.Length – 1);
string signature = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(signa, “sha1”);//MD5##
- Return to the token class
1、OAuth_Ticket Ticket_Model = Get_ticket(ac_token);
string ticket = Ticket_Model.ticket;
2、protected OAuth_Ticket Get_ticket(string ac_token)
{
string Str = GetJson(“https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=” + ac_token + “&type=jsapi”);
OAuth_Ticket OAuth_Ticket_Model = JsonHelper.ParseFromJson<OAuth_Ticket>(Str);
return OAuth_Ticket_Model;
}
3、
//Get the token of WeChat backward;
OAuth_Token Model = Get_token(); //Get token
string ac_token = Model.access_token;
protected OAuth_Token Get_token()
{
appid = “”;
appsecret = “”;
//Get WeChat backward Openid and Access token
string Str = GetJson(“https://api.weixin.qq.com/cgi-bin/token?appid=” + appid + “&secret=” + appsecret + “&grant_type=client_credential”);
//WeChat returned data in JSON format, transforming json format into objects
OAuth_Token Oauth_Token_Model = JsonHelper.ParseFromJson<OAuth_Token>(Str);
return Oauth_Token_Model;
}
//Visit WeChat URL and return to WeChat information
protected string GetJson(string url)
{
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Encoding = Encoding.UTF8;
string returnText = wc.DownloadString(url);
if (returnText.Contains(“errcode”))
{
//Error may occur
}
return returnText;
}
/// <summary>
/// Convert json format data into objects
/// </summary>
public class JsonHelper
{
/// <summary>
/// Generate json format
/// </summary>
/// <typeparam name=”T“></typeparam>
/// <param name=”obj“></param>
/// <returns></returns>
public static string GetJson<T>(T obj)
{
DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, obj);
string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson;
}
}
/// <summary>
/// Get JSON’s Model
/// </summary>
/// <typeparam name=”T“></typeparam>
/// <param name=”szJson“></param>
/// <returns></returns>
public static T ParseFromJson<T>(string szJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}
- Read the current link:
string url = Request.Url.ToString();
- The “timestamp”、“noncestr”、“signature“and the Appid of the WeChat public account;
/*
* Note:
* 1. All JS interfaces can only be applied under the domain name binding of the public account. Public account developers need to log in to the WeChat public platform into the “functional settings” of “public account settings” to fill in the “JS interface security domain name”.
* 2. If you find that you cannot share the custom content on Android, please download the latest coverage and installation on the official website. Android custom sharing interface needs to be upgraded to version 6.0.2.58.
* 3. Complete JS-SDK document address: http://mp.weixin.qq.com/wiki/7/aaa137b55FB2E0456BF8DDDDDD613F.HTML
*
* If you have any questions, please pass the following channel feedback:
* mailbox address:[email protected]
* Email theme: [WeChat JS-SDK feedback] Specific problems
* Email content description: To describe the problem with concise language, and explain the scene where you encounter the problem, you can attach a screenshot picture, and the WeChat team will handle your feedback as soon as possible.
*/
wx.config({
debug: false,
appId: “”,
timestamp: document.getElementById(“timestamp_no”).innerHTML,
nonceStr: document.getElementById(“nonceStr_no”).innerHTML,
signature: document.getElementById(“signature_no”).innerHTML,
jsApiList: [
‘checkJsApi’,
‘onMenuShareTimeline’,
‘onMenuShareAppMessage’,
‘onMenuShareQQ’,
‘onMenuShareWeibo’,
‘hideMenuItems’,
‘showMenuItems’,
‘hideAllNonBaseMenuItem’,
‘showAllNonBaseMenuItem’,
‘translateVoice’,
‘startRecord’,
‘stopRecord’,
‘onRecordEnd’,
‘playVoice’,
‘pauseVoice’,
‘stopVoice’,
‘uploadVoice’,
‘downloadVoice’,
‘chooseImage’,
‘previewImage’,
‘uploadImage’,
‘downloadImage’,
‘getNetworkType’,
‘openLocation’,
‘getLocation’,
‘hideOptionMenu’,
‘showOptionMenu’,
‘closeWindow’,
‘scanQRCode’,
‘chooseWXPay’,
‘openProductSpecificView’,
‘addCard’,
‘chooseCard’,
‘openCard’
]
});
information returned after getting the code
Document.querySelector(‘#scanQRCode0’).onclick = function () {
wx.scanQRCode({
needResult: 1, // Definitely 0, the scanning result is processed by WeChat, and 1 will return directly to the scanning result.
scanType: [“qrCode”, “barCode”], // can specify the scanning two -dimensional code or one dimension, both default
success: function (res) {
var boxres = res.resultStr; // When the NeedResult is 1, the result of scanning the code returns
var boxid = boxres.split(‘,’)[0];
var $group = document.querySelectorAll(‘.form-group input’);
$group[$group.length – 1].value = boxid;
}
});
};
Note: The return is displayed in the text of “.form-found input”;
document.querySelectorAll(‘’);can only read the class style
document.querySelector(‘#scanQRCode1’).onclick = function () {
wx.scanQRCode({
needResult: 1,
desc: ‘scanQRCode desc’,
success: function (res) {
// alert(JSON.stringify(res));
// alert(res.resultStr);
var express_numall = res.resultStr;
var express_num = express_numall.split(‘,’)[0];
window.location.href = “XXXXX.XXXX?code=” + express_num;
}
});
};
Note: Return to the new page with scanning value.