您的位置:首页 > 移动开发 > 微信开发

C#微信网页开发---JSSDK使用 通过config接口注入权限验证配置

2018-03-19 23:00 2679 查看

 1:   我们来看,下面的这个是开发需要配置的东西,我们通过开发文档来一个一个的配置

wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,公众号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名
jsApiList: [] // 必填,需要使用的JS接口列表
});
签名算法见文末的附录1,所有JS接口列表见文末的附录2
这个地方AppID,时间戳,随机字符串和js接口列表都很好得到,唯一比较难的就是签名
2:获取签名
    (1):获取签名的第一步,需要获得jsapi_ticket
    这个地方需要使用到access_token,access_token获取方法:http://blog.csdn.net/weixin_39462109/article/details/79438922

private static void  Getjsapi_ticket()
{
string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi",Access_token);
string backStr=Common.Get_Request(url);
//string backStr = "{ \"errcode\":0,\"errmsg\":\"ok\",\"ticket\":\"kgt8ON7yVITDhtdwci0qeZWDYY9llY5RrKsWxKD--zOUIRYqJ1XwMo305bwZhG22b5hOl-TZ-gZAXCbMMHwvCw\",\"expires_in\":7200}";
string str_ticket = backStr.Split(',')[2].Split(':')[1];
Jsapi_ticket= str_ticket.Substring(1,str_ticket.Length-2);
}
/// <summary>
/// 发送Get请求,并且得到返回结果
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string Get_Request(string url)
{
System.Net.WebRequest wrq = System.Net.WebRequest.Create(url);
wrq.Method = "GET";
System.Net.WebResponse wrp = wrq.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
return sr.ReadToEnd();
}
3:创建一个WX_Web_Config类,类中封装签名方法
      public class WX_Web_Config
{
private bool debug;
private string appId;
private string timestamp;
private string nonceStr;
private string signature;
private List<string> jsApiList=new List<string>();
private string url;

public WX_Web_Config(bool debug, string appId, string timestamp, string nonceStr, string url)
{
this.debug = debug;
this.appId = appId;
this.timestamp = timestamp;
this.nonceStr = nonceStr;
this.url = url;
this.signature = GetSignature();
}

/// <summary>
/// 是否开启调试模式
/// </summary>
public bool Debug
{
get
{
return debug;
}

set
{
debug = value;
}
}

/// <summary>
/// 必填,公众号的唯一标识
/// </summary>
public string AppId
{
get
{
return appId;
}

set
{
appId = value;
}
}

/// <summary>
/// 必填,生成签名的时间戳
/// </summary>
public string Timestamp
{
get
{
return timestamp;
}

set
{
timestamp = value;
}
}

/// <summary>
/// 必填,生成签名的随机串
/// </summary>
public string NonceStr
{
get
{
return nonceStr;
}

set
{
nonceStr = value;
}
}

/// <summary>
/// 必填,签名
/// </summary>
public string Signature
{
get
{
return signature;
}

set
{
signature = value;
}
}
/// <summary>
/// 必填,需要使用的JS接口列表
/// </summary>
public List<string> JsApiList
{
get
{
return jsApiList;
}

set
{
jsApiList = value;
}
}

public string Url
{
get
{
return url;
}

set
{
url = value;
}
}

/// <summary>
/// 得到签名
/// </summary>
/// <returns></returns>
private string GetSignature()
{
Hashtable hs = new Hashtable();
hs.Add("jsapi_ticket", MvcApplication.Jsapi_ticket);//获取的
hs.Add("noncestr", NonceStr);
hs.Add("timestamp", Timestamp);
hs.Add("url", Url);
//得到string1
string string1= formatParameters(hs);
//对string1进行sha1签名
Signature = HashCode(string1);
return Signature;
}

/// <summary>
/// 参数名ASCII码从小到大排序(字典序)
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
private string formatParameters(Hashtable parameters)
{
StringBuilder sb = new StringBuilder();
ArrayList akeys = new ArrayList(parameters.Keys);
akeys.Sort();
foreach (string k in akeys)
{
string v = (string)parameters[k];//防止参数不是字符串
sb.Append(k.ToLower() + "=" + v + "&");
}
//去掉最后一个&
if (sb.Length > 0)
{
sb.Remove(sb.Length - 1, 1);
}
return sb.ToString();
}

/// <summary>
/// 进行sha1签名
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string HashCode(string str)
{
string rethash = "";
try
{

System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
byte[] combined = encoder.GetBytes(str);
hash.ComputeHash(combined);
rethash = Convert.ToBase64String(hash.Hash);
}
catch (Exception ex)
{
string strerr = "Error in HashCode : " + ex.Message;
}
return rethash;
}

}4:创建一个枚举,用来存储所有的js接口名称
  public enum WX_Web_Js_Interface
{
onMenuShareTimeline,

onMenuShareAppMessage,

onMenuShareQQ,

onMenuShareWeibo,

onMenuShareQZone,

startRecord,

stopRecord,

onVoiceRecordEnd,

playVoice,

pauseVoice,

stopVoice,

onVoicePlayEnd,

uploadVoice,

downloadVoice,

chooseImage,

previewImage,

uploadImage,

downloadImage,

translateVoice,

getNetworkType,

openLocation,

getLocation,

hideOptionMenu,

showOptionMenu,

hideMenuItems,

showMenuItems,

hideAllNonBaseMenuItem,

showAllNonBaseMenuItem,

closeWindow,

scanQRCode,

chooseWXPay,

openProductSpecificView,

addCard,

chooseCard,

openCard

}6:在加载页面的时候调用WX_Web_Config构造函数namespace 微信开发2018.Controllers
{
public class WebController : Controller
{
// GET: Web
public ActionRe
a9a8
sult Index()
{
WX_Web_Config config = new WX_Web_Config(true,WebConfigurationManager.AppSettings.Get("AppID"),DateTime.Now.ToLongDateString(),"tangjie", "http://116.21.25.73/Web/Index");
config.JsApiList.Add(WX_Web_Js_Interface.addCard.ToString());
config.JsApiList.Add(WX_Web_Js_Interface.chooseCard.ToString());
return View(config);
}
}
}7:前端界面显示 @model 微信开发2018.WxCode.WX_Web.WX_Web_Config
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/Menu_LayoutPage.cshtml";
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
}
<h2>加载JSSDK</h2>
<script type="text/javascript">
wx.config({
debug:true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '@Model.AppId', // 必填,公众号的唯一标识
timestamp:'@Model.Timestamp' , // 必填,生成签名的时间戳
nonceStr:'@Model.NonceStr', // 必填,生成签名的随机串
signature:' @Model.Signature',// 必填,签名
jsApiList: @Html.Raw(Json.Encode(Model.JsApiList)), // 必填,需要使用的JS接口列表
});

wx.ready(function(){
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
console.log("配置成功了");
});
wx.error(function(res){
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
console.log("配置失败了");
console.log(res);
});

</script>

8:结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: