生成JS-SDK权限验证的签名

获取signature(签名)首先要获得

1、#获得jsapi_ticket

2、#获取当前页面的url

 

#获取当前页面的url
  url="{}://{}{}".format(self.request.protocol,self.request.host,self.request.uri)

 

3、#获取timestamp(时间戳)

#获取timestamp(时间戳)
  timestamp = int(time.time())

4、#获取noncestr(随机字符串)

#获取noncestr(随机字符串)
  nonceStr = self.createNonceStr()(见下函数)

5、# 这里参数的顺序要按照 key 值 ASCII 码升序排序
string = "jsapi_ticket={}&noncestr={}&timestamp={}&url={}".format(jsapiTicket,nonceStr,timestamp,url)

6、#得到signature(用sha1加密)
signature = hashlib.sha1(string).hexdigest();

1、获得jsapi_ticket要先获取access_token(不再细说)

然后

def getJsApiTicket(self):
     #获得jsapi_ticket
  #获得jsapi_ticket之后,就可以生成JS-SDK权限验证的签名了
import urllib2
  # jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
  #cookie('ticket',null);

  #获取access_token
self.accesstokens()
  # 如果是企业号用以下 URL 获取 ticket
  # $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
  #获取jsapi_ticket
"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={}&type=jsapi".format(accessToken)

  req = urllib2.Request(url)
  res_data = urllib2.urlopen(req)
  res = res_data.read()
  res=json_decode(res)

  return str(res['ticket'])

4、#获取noncestr(随机字符串)

def createNonceStr(self,length = 16):
#获取noncestr(随机字符串)
    import random
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    str = "";
for i in range(0,16):
        str += chars[random.randint(0, len(chars)-1):random.randint(0, len(chars)-1)+1]
# for ($i = 0; $i < $length; $i++) {
    #   $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    # }
    return str;

 

后台总代码整理为:

 

def index(self):
"""
    知识中心
    :return:
    """
    id = self.get_argument('id','')
    getSignPackage=self.getSignPackage()
self.assign('getSignPackage',getSignPackage)
self.display('knowledge/index.html')

 

def getSignPackage(self) :
import hashlib
#获得jsapi_ticket
    jsapiTicket = self.getJsApiTicket()


# 注意 URL 一定要动态获取,不能 hardcode.
    # protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    # $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    #获取当前页面的url
    url="{}://{}{}".format(self.request.protocol,self.request.host,self.request.uri)

#获取timestamp(时间戳)
    timestamp = int(time.time())
#获取noncestr(随机字符串)
    nonceStr = self.createNonceStr()

# 这里参数的顺序要按照 key 值 ASCII 码升序排序
    string = "jsapi_ticket={}&noncestr={}×tamp={}&url={}".format(jsapiTicket,nonceStr,timestamp,url)
#得到signature
    signature = hashlib.sha1(string).hexdigest();
    wxinfo = self.getwx()
    signPackage = {
"appId":wxinfo['appid'],
"nonceStr":nonceStr,
"timestamp":timestamp,
"url":url,
"signature":signature,
"rawString":string
    }


return signPackage;


def createNonceStr(self,length = 16):
#获取noncestr(随机字符串)
    import random
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    str = "";
for i in range(0,16):
        str += chars[random.randint(0, len(chars)-1):random.randint(0, len(chars)-1)+1]
# for ($i = 0; $i < $length; $i++) {
    #   $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    # }
    return str;


def getJsApiTicket(self):
#获得jsapi_ticket
    #获得jsapi_ticket之后,就可以生成JS-SDK权限验证的签名了
    import urllib2
# jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    #cookie('ticket',null);

    #获取access_token
    accessToken = self.accesstokens()
# 如果是企业号用以下 URL 获取 ticket
    # $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
    #获取jsapi_ticket
    url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={}&type=jsapi".format(accessToken)

    req = urllib2.Request(url)
    res_data = urllib2.urlopen(req)
    res = res_data.read()
    res=json_decode(res)

return str(res['ticket'])
前台总代码整理:
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
        <script type="text/javascript">
//通过config接口注入权限验证配置
            wx.config({
debug: false,
appId: '${getSignPackage["appId"]}',
timestamp:'${getSignPackage["timestamp"]}',
nonceStr: '${getSignPackage["nonceStr"]}',
signature: '${getSignPackage["signature"]}',
jsApiList: [
'onMenuShareAppMessage',
'onMenuShareTimeline',
'onMenuShareQQ',
'onMenuShareWeibo'
                  // 所有要调用的 API 都要加到这个列表中
                ]
            });
            wx.ready(function () {
// 1 判断当前版本是否支持指定 JS 接口,支持批量判断
                wx.checkJsApi({
jsApiList: [
'onMenuShareAppMessage'
                    ],
success: function (res) {
//alert(JSON.stringify(res));
                    }
                });
//获取“分享给朋友”按钮点击状态及自定义分享内容接口
                wx.onMenuShareAppMessage({
title: '${replypt_list["title"]}',
desc: '${replypt_list["title"]}',
link: '${getSignPackage["url"]}',
imgUrl: '${handler.settings["PHOTO_URL"]}${replypt_list["cover"]}',
trigger: function (res) {
// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
                    },
success: function (res) {
$.ajax({
url: '/shop/knowledge/addIntager',
data: { name: "${replypt_list['id']}"},
type: 'post',
cache:false,
success: function(data){
                            },
error: function(xhr, type){
alert('Ajax error!')
                            }
                        })
                    },
cancel: function (res) {
                    },
fail: function (res) {
                    }
                });
//获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
                wx.onMenuShareTimeline({
title: '${replypt_list["title"]}',
desc: '${replypt_list["title"]}',
link: '${getSignPackage["url"]}',
imgUrl: '${handler.settings["PHOTO_URL"]}${replypt_list["cover"]}',
trigger: function (res) {
// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回

                    },
success: function (res) {
$.ajax({
url: '/shop/knowledge/addIntager',
data: { name: "${replypt_list['id']}"},
type: 'post',
cache:false,
success: function(data){
alert(str('aa'))
                            },
error: function(xhr, type){
alert('Ajax error!')
                            }
                        })
                    },
cancel: function (res) {

                    },
fail: function (res) {

                    }
                });
//获取“分享到QQ”按钮点击状态及自定义分享内容接口
                wx.onMenuShareQQ({
title: '${replypt_list["title"]}',
desc: '${replypt_list["title"]}',
link: '${getSignPackage["url"]}',
imgUrl: '${handler.settings["PHOTO_URL"]}${replypt_list["cover"]}',
trigger: function (res) {

                    },
complete: function (res) {

                    },
success: function (res) {
$.ajax({
url: '/shop/knowledge/addIntager',
data: { name: "${replypt_list['id']}"},
type: 'post',
cache:false,
success: function(data){
                            },
error: function(xhr, type){
alert('Ajax error!')
                            }
                        })
                    },
cancel: function (res) {

                    },
fail: function (res) {

                    }
                });

                wx.onMenuShareWeibo({
title: '${replypt_list["title"]}',
desc: '${replypt_list["title"]}',
link: '${getSignPackage["url"]}',
imgUrl: '${handler.settings["PHOTO_URL"]}${replypt_list["cover"]}',
trigger: function (res) {

                    },
complete: function (res) {

                    },
success: function (res) {
$.ajax({
url: '/shop/knowledge/addIntager',
data: { name: "${replypt_list['id']}"},
type: 'post',
cache:false,
success: function(data){
                            },
error: function(xhr, type){                                alert('Ajax error!')                            }                        })                    },                    cancel: function (res) {                    },                    fail: function (res) {                    }                });            });        // 2. 分享接口        // 2.1 监听“分享给朋友”,按钮点击、自定义分享内容及分享结果接口        </script>