微信jssdk基本使用

对于如何使用jssdk并没有,太大难度,对于不熟悉的人来说,最大的坑在它配置的过程中。

       使用jssdk需要注意以下几点:

       1.需要在微信公众平台设置js接口安全域名。需要注意的是此处你需要设置的是域名,使用ip是不行的。同时这个设置每个月只可以修改3次,大家要确定后再修改。

2.后台需要通过appid,appsecret先获取到access_token,之后通过access_token才可以获得ticket。同时最好通过redis保存ticket。微信对此有说明。

3.如果需要使用媒体下载接口,即http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+media_id;

你还需要缓存access_token。

以下是具体交互步骤,后台采用golang搭建请求。

后台方法:

func GetTicket() []byte {
	url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
		"&appid=" + config.WxAppId +
		"&secret=" + config.WxAppSecret
	token := WxGet(url)
	if token == nil{
		fmt.Println("获取token错误")
	}
	var wxToken dao.WXToken
	json.Unmarshal(token,&wxToken)
	fmt.Println(wxToken.AccessToken)
	//保存微信accesstoken
	if wxToken.AccessToken != "" {
		redispool.RedisSETString("wx_access_token",wxToken.AccessToken,7200)
	}
	ticketUrl := "https://api.weixin.qq.com/cgi-bin/ticket/getticket?" +
		"access_token=" + wxToken.AccessToken + "&type=jsapi"
	ticket := WxGet(ticketUrl)
	if ticket == nil{
		fmt.Println("获取ticket错误")
	}
	fmt.Println("ticker:",ticket)
	var wxTicket dao.WXTicket
	json.Unmarshal(ticket,&wxTicket)
	fmt.Println("wxTicket:",wxTicket)
	return ticket
}

func WxGet(u string) []byte {
	resp, err := http.Get(u)
	defer resp.Body.Close()
	if err != nil {
		fmt.Println(err)
		return nil
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	fmt.Println("body",string(body))
	return body
}

前台方法:

$.get("/ticket",function(data,status){
            console.log("Data: " + data.ticket + "\nStatus: " + status);
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000;
            console.log("time:",timestamp);
            var u = uuid();
            console.log("uuid:",u);
            console.log("ticket:",data.ticket);
            var l = location.href.split('#')[0]
            var stringTemp = "jsapi_ticket=" + data.ticket +
                    "&noncestr=" + u +
                    "×tamp=" + timestamp +
                    "&url=" + l;
            var s = hex_sha1(stringTemp);
            console.log("sign:",s)
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: '', // 必填,公众号的唯一标识
                timestamp: timestamp, // 必填,生成签名的时间戳
                nonceStr: u, // 必填,生成签名的随机串
                signature: s,// 必填,签名,见附录1
                jsApiList: ["startRecord","stopRecord","onVoiceRecordEnd","playVoice","pauseVoice","stopVoice"
                    ,"onVoicePlayEnd","uploadVoice","downloadVoice","chooseImage","previewImage","uploadImage","downloadImage"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
        });

在生成sign的url最好使用 location.href.split('#')[0]来获得你的网址,同时你的网址需要和js安全域名一致。

       

发布了48 篇原创文章 · 获赞 17 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/aixinaxc/article/details/78776221
今日推荐