コード例 #1
0
ファイル: test_basic.py プロジェクト: 14F/wechat-python-sdk
    def test_generate_jsapi_signature(self):
        noncestr = 'Wm3WZYTPz0wzccnW'
        jsapi_ticket = 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg'  # NOQA
        timestamp = 1414587457
        url = 'http://mp.weixin.qq.com?params=value'

        # 测试无 appid 和 appsecret 初始化
        wechat = WechatBasic()
        with self.assertRaises(NeedParamError):
            wechat.generate_jsapi_signature(timestamp=timestamp, noncestr=noncestr, url=url)

        # 测试有 appid 和 appsecret 初始化
        wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret)
        with HTTMock(wechat_api_mock):
            signature = wechat.generate_jsapi_signature(timestamp=timestamp, noncestr=noncestr, url=url, jsapi_ticket=jsapi_ticket)
            self.assertEqual(signature, '0f9de62fce790f9a083d5c99e95740ceb90c27ed')
コード例 #2
0
ファイル: WeixinUtils.py プロジェクト: GEOAL1/zebraService
class WeixinMananger:
    def __init__(self, appid="wxc2b14fc7557dc863", appsecret="67c0097d1bf2f7804f9eb2375f3d2039",
                 redisIp="127.0.0.1", redisPort=6379):
        self.redis = redis.StrictRedis(host=redisIp)
        self.appid = appid;
        self.appsecret = appsecret;
        self.wechat = WechatBasic(appid=appid, appsecret=appsecret);

    def __getRedisWXAccessToken(self):
        return self.redis.get("wx_access_token")

    def __getRedisWXJsApiToken(self):
        return self.redis.get("wx_jsapi_token")

    def getAccessToken(self):
        token = self.__getRedisWXAccessToken()
        if token is None:
            token = self.wechat.grant_token()
            if token != None:
                timeout = token["expires_in"]
                self.redis.setex("wx_access_token", timeout, token["access_token"])
                return token["access_token"]
            else:
                return None;
        else:
            return token

    def getJsApiToken(self):
        ticket = self.__getRedisWXJsApiToken()
        if ticket is None:
            print self.getAccessToken()
            ticket = self.wechat.grant_jsapi_ticket()
            if (ticket != None):
                timeout = ticket["expires_in"];
                self.redis.setex("wx_jsapi_token", timeout, ticket["ticket"])
                return ticket["ticket"]
            else:
                return None
        else:
            return ticket

    def getJsJDK(self, srcUrl):
        timestamp = int(time.time())
        noncestr = str(time.time())
        url = srcUrl
        jsApiToken = self.getJsApiToken();
        data = {};
        data["timestamp"] = timestamp
        data["nonceStr"] = noncestr
        data["appId"] = self.appid
        data["signature"] = self.wechat.generate_jsapi_signature(timestamp, noncestr, url, jsApiToken)
        data["jsApiList"] = ["openLocation", "getLocation", "scanQRCode", "showMenuItems"]
        data["debug"] = True
        return data
コード例 #3
0
    def test_generate_jsapi_signature(self):
        noncestr = 'Wm3WZYTPz0wzccnW'
        jsapi_ticket = 'sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg'  # NOQA
        timestamp = 1414587457
        url = 'http://mp.weixin.qq.com?params=value'

        # 测试无 appid 和 appsecret 初始化
        wechat = WechatBasic()
        with self.assertRaises(NeedParamError):
            wechat.generate_jsapi_signature(timestamp=timestamp,
                                            noncestr=noncestr,
                                            url=url)

        # 测试有 appid 和 appsecret 初始化
        wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret)
        with HTTMock(wechat_api_mock):
            signature = wechat.generate_jsapi_signature(
                timestamp=timestamp,
                noncestr=noncestr,
                url=url,
                jsapi_ticket=jsapi_ticket)
            self.assertEqual(signature,
                             '0f9de62fce790f9a083d5c99e95740ceb90c27ed')
コード例 #4
0
def generate_jsapi_signature(url):

    ticket, expired_at = get_jsapi_ticket()

    b = WechatBasic(
        appid=settings.app_id, appsecret=settings.secret, jsapi_ticket=ticket, jsapi_ticket_expires_at=expired_at
    )

    timestamp = int(round(time.time()))
    nonce = random.randint(10000000, 99999999)
    print "generate signature at:", datetime.datetime.now()
    signature = b.generate_jsapi_signature(timestamp, nonce, url, jsapi_ticket=ticket)

    return {"appId": settings.app_id, "timestamp": timestamp, "nonceStr": nonce, "signature": signature}
コード例 #5
0
def _GetSagin(url):
    JSTimestamp = int(time.time())
    JSnoncestr = random.randint(100000, 9999999)
    EnURL = WECHAT_URL + url
    KLBWechatBasic = WechatBasic(token=WECHAT_TOKEN, appid=WECHAT_APPID, appsecret=WECHAT_APPSECRET)
    JScardSign = KLBWechatBasic.generate_jsapi_signature(JSTimestamp, JSnoncestr, EnURL, jsapi_ticket=None)

    JSCode = {
        "appid": WECHAT_APPID,
        "timestamp": JSTimestamp,
        "nonceStr": JSnoncestr,
        "signature": JScardSign

    }
    return JSCode
コード例 #6
0
ファイル: auth.py プロジェクト: daixm/wechat-admin
def generate_jsapi_signature(url):

    ticket, expired_at = get_jsapi_ticket()

    b = WechatBasic(
        appid=settings.APP_ID,
        appsecret=settings.SECRET,
        jsapi_ticket=ticket,
        jsapi_ticket_expires_at=expired_at)

    timestamp = int(round(time.time()))
    nonce = random.randint(10000000, 99999999)
    print 'generate signature at:', datetime.datetime.now()
    signature = b.generate_jsapi_signature(
        timestamp, nonce, url, jsapi_ticket=ticket)

    return {
        'appId': settings.APP_ID,
        'timestamp': timestamp,
        'nonceStr': nonce,
        'signature': signature,
    }
コード例 #7
0
def generate_jsapi_signature(url):

    ticket, expired_at = get_jsapi_ticket()

    b = WechatBasic(appid=settings.APP_ID,
                    appsecret=settings.SECRET,
                    jsapi_ticket=ticket,
                    jsapi_ticket_expires_at=expired_at)

    timestamp = int(round(time.time()))
    nonce = random.randint(10000000, 99999999)
    print 'generate signature at:', datetime.datetime.now()
    signature = b.generate_jsapi_signature(timestamp,
                                           nonce,
                                           url,
                                           jsapi_ticket=ticket)

    return {
        'appId': settings.APP_ID,
        'timestamp': timestamp,
        'nonceStr': nonce,
        'signature': signature,
    }
コード例 #8
0
def Pricing(request, action="1"):
    Code = KLBCode()
    openid = request.REQUEST.get("openid", "")
    # ReWechat = _GetWechatInfo(req=request)

    # if ReWechat=="" or len(ReWechat)<1:
    #     return HttpResponsePermanentRedirect("http://web.kalaibao.com/wechat/WechatLogin/?action=Pricing&time=%s"%time.time())
    db = {"t": time.time()}
    KLBWechatBasic = WechatBasic(token=WECHAT_TOKEN, appid=WECHAT_APPID, appsecret=WECHAT_APPSECRET)

    JSURL = WECHAT_URL + request.get_full_path()
    JSTimestamp = int(time.time())
    JSnoncestr = random.randint(100000, 9999999)

    JScardSign = KLBWechatBasic.generate_jsapi_signature(JSTimestamp, JSnoncestr, JSURL, jsapi_ticket=None)

    JSCode = {

        "timestamp": JSTimestamp,
        "nonceStr": JSnoncestr,
        "signature": JScardSign

    }
    JSCode.update({"appId": WECHAT_APPID, "openid": openid})
    db.update(JSCode)
    # db.update(ReWechat)

    #判断是否能拿到openID
    try:
        openid = Code.decode(openid)
        WechatUserInfo = wechat.objects.get(openid=openid)
        RecommendURL = "%s/wechat/WechatLogin/?action=Recommend&toid=%s" % (WECHAT_URL, WechatUserInfo.id)
    except:
        RecommendURL = "%s/wechat/WechatLogin/?action=Pricing&toid=" % (WECHAT_URL)
    ID = ['9','16','41','53','60','76','17']
    try:
        i = random.randint(0,len(ID))
        CarIN = bxcarvin.objects.get(id=ID[i])
    except:
        CarIN = bxcarvin.objects.get(id=ID[0])
    db.update({"CarInfo":CarIN})
    db.update({"RecommendURL":RecommendURL})
    if action == "1":
        return render_to_response('wechat/pricing.html', db, context_instance=RequestContext(request))
    if action == "2":
        return render_to_response('wechat/CarInfo.html', db, context_instance=RequestContext(request))
    if action == "3":
        return render_to_response('wechat/showList.html', db, context_instance=RequestContext(request))
    if action == "4":
        return render_to_response('wechat/detail.html', db, context_instance=RequestContext(request))
    if action == "5":
        DBAction = BXDBAction()
        ENCODE = FengChaoCrypt()

        id = request.REQUEST.get("id", "")
        key = request.REQUEST.get("key", "")
        bxgs = request.REQUEST.get("bxgs", "")
        CarInfo = {}

        if id <> "" and id <> None:
            try:
                CarInfo = bxcarvin.objects.get(id=id)
            except:
                CarInfo = {}
        if key <> "" and key <> None:
            try:
                vin = ENCODE.AESdecrypt(key)
                CarInfo = bxcarvin.objects.get(vin=vin)
            except:
                vin = key
                CarInfo = bxcarvin.objects.get(vin=vin)
        PayInfo = DBAction.SelectPayInfo(vin=ENCODE.AESencrypt(CarInfo.vin))
        print(CarInfo.vin)
        db = {"CarInfo": CarInfo, "bxgs": bxgs, "PayInfo": PayInfo}
        return render_to_response('wechat/UserInfo.html', db, context_instance=RequestContext(request))

    if action == "6":
        return render_to_response('wechat/Bxgsweb.html', db, context_instance=RequestContext(request))
    if action == '7':
        DBAction = BXDBAction()
        ENCODE = FengChaoCrypt()

        id = request.REQUEST.get("id", "")
        key = request.REQUEST.get("key", "")
        bxgs = request.REQUEST.get("bxgs", "")
        CarInfo = {}

        if id <> "" and id <> None:
            try:
                CarInfo = bxcarvin.objects.get(id=id)
            except:
                CarInfo = {}
        if key <> "" and key <> None:
            try:
                vin = ENCODE.AESdecrypt(key)
                CarInfo = bxcarvin.objects.get(vin=vin)
            except:
                vin = key
                CarInfo = bxcarvin.objects.get(vin=vin)
        PayInfo = DBAction.SelectPayInfo(vin=ENCODE.AESencrypt(CarInfo.vin))
        db = {"CarInfo": CarInfo, "bxgs": bxgs, "PayInfo": PayInfo}
        return render_to_response("wechat/FuDongBiz.html",db,context_instance=RequestContext(request))
    if action == '8':
        DBAction = BXDBAction()
        ENCODE = FengChaoCrypt()

        id = request.REQUEST.get("id", "")
        key = request.REQUEST.get("key", "")
        bxgs = request.REQUEST.get("bxgs", "")
        CarInfo = {}

        if id <> "" and id <> None:
            try:
                CarInfo = bxcarvin.objects.get(id=id)
            except:
                CarInfo = {}
        if key <> "" and key <> None:
            try:
                vin = ENCODE.AESdecrypt(key)
                CarInfo = bxcarvin.objects.get(vin=vin)
            except:
                vin = key
                CarInfo = bxcarvin.objects.get(vin=vin)
        PayInfo = DBAction.SelectPayInfo(vin=ENCODE.AESencrypt(CarInfo.vin))
        db = {"CarInfo": CarInfo, "bxgs": bxgs, "PayInfo": PayInfo}
        return render_to_response("wechat/FuDongforce.html",db,context_instance=RequestContext(request))
    else:
        return render_to_response('wechat/pricing.html', db, context_instance=RequestContext(request))
コード例 #9
0
ファイル: wx.py プロジェクト: bluedazzle/ooil
class WeChatService(object):
    def __init__(self, app_id=None, app_secret=None):
        self.redis = redis.StrictRedis(host='localhost', port=6379, db=2)
        self.app_id = app_id
        self.app_secret = app_secret
        if not app_id:
            self.wechat_admin = Area.objects.all().order_by('id')[0]
            self.wechat = WechatBasic(appid=self.wechat_admin.wx_app_id,
                                      appsecret=self.wechat_admin.wx_secret,
                                      token='123')
            self.app_id = self.wechat_admin.app_id
            self.app_secret = self.wechat_admin.app_secret
        else:
        self.wechat_admin = None
        self.wechat = WechatBasic(appid=app_id, appsecret=app_secret, token='123')

        self.get_token()

    def get_token(self):
        key = 'access_token_{0}'.format(self.app_id)
        token = self.redis.get(key)
        if not token:
            res = self.wechat.grant_token()
            token = res.get('access_token')
            self.redis.set(key, token, 3500)
        return token

    def get_js_ticket(self):
        key = 'js_ticket_{0}'.format(self.app_id)
        ticket = self.redis.get(key)
        if not ticket or ticket == 'None':
            res = self.wechat.get_jsapi_ticket()
            ticket = res.get('jsapi_ticket')
            self.redis.set(key, ticket, 3500)
        return ticket

    def get_random_str(self):
        return string.join(
            random.sample('ZYXWVUTSRQPONMLKJIHGFEDCBA1234567890zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba',
                          32)).replace(" ", "")

    def get_js_signature(self, url):
        timestamp = int(time.time())
        nostr = self.get_random_str()
        ticket = self.get_js_ticket()
        signature = self.wechat.generate_jsapi_signature(timestamp, nostr, url, ticket)
        return {'timestamp': timestamp, 'ticket': ticket, 'noncestr': nostr, 'url': url, 'signature': signature}

    def send_message(self, open_id, message):
        token = self.get_token()
        req_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}'.format(token)
        message = message.decode('utf-8')
        data = {'touser': open_id,
                'msgtype': 'text',
                'text': {'content': str('测试')}}
        result = requests.post(req_url, data=simplejson.dumps(data))
        return json.loads(result.content)


if __name__ == '__main__':
    ws = WeChatService('wx53a0bb66744d6ff8', '72714e74ea52de8a0917111bb7b4b324')
    print ws.get_js_signature('http://www.rapospectre.com')