def _get_jsapi_ticket(): """ 返回jsapi_ticket,如果缓存的时间戳超过7000秒(微信过期7200),就重新去获取 :return: jsapi_ticket """ wechat = WechatBasic(appid=APP_ID, appsecret=APP_SECRET) jsapi_ticket_expires_at =\ WechatStore.objects.get_or_create(key='jsapi_ticket_expires_at')[0] jsapi_ticket = WechatStore.objects.get_or_create(key='jsapi_ticket')[0] if (not jsapi_ticket_expires_at.value or\ not jsapi_ticket.value or\ int(time.time()) > (int(jsapi_ticket_expires_at.value)-200)): # 多算200秒 # 获取新jsapi_ticket res = wechat.grant_jsapi_ticket() jsapi_ticket_expires_at.value = res.get('expires_in', None) jsapi_ticket_expires_at.save() jsapi_ticket.value = res.get('ticket', None) jsapi_ticket.save() # 有点low的wechat_sdk,只要jsapi_ticket更新,就连access_token一起更新 # 所以下面需要同时再更新一下access_token的值 access_token_expires_at =\ WechatStore.objects.get_or_create(key='access_token_expires_at')[0] access_token = WechatStore.objects.get_or_create(key='access_token')[0] token_res = wechat.get_access_token() access_token_expires_at.value = token_res.get('expires_in',\ None) access_token_expires_at.save() access_token.value = token_res.get('access_token', None) access_token.save() return jsapi_ticket.value
def createMenu(request): wechat = WechatBasic(appid='wxacfdb1da76aa7763', appsecret='0f0f71dbff7dbde3e3b07897ddd8f78b') wechat.create_menu( { 'button':[ { 'type': 'view', 'name': '家家订餐', 'url': 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxacfdb1da76aa7763&redirect_uri=http%3A%2F%2Fxiangeqwd.9xi.com%2FDiningServer%2Findex%2F&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect' }, { 'type': 'view', 'name': '送餐信息', 'url': 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxacfdb1da76aa7763&redirect_uri=http%3A%2F%2Fxiangeqwd.9xi.com%2FDiningServer%2FlistMyDetailInfoPage%2F&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect' }, { 'type': 'view', 'name': '我的订单', 'url': 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxacfdb1da76aa7763&redirect_uri=http%3A%2F%2Fxiangeqwd.9xi.com%2FDiningServer%2FgetOrdersByType%2F&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect' }, ] } )
def receive_message(request): """ 收取微信消息 """ signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echostr = request.GET.get('echostr') wechat = WechatBasic(token=WECHAT_TOKEN) """ 用于在微信配置响应服务器时的验证 {u'nonce': [u'280474307'], u'timestamp': [u'1438015570'],\ u'echostr': [u'3904558954066704850'],\ u'signature': [u'cfbd4c33549370f85424415310449f44e962c5d7']} """ if wechat.check_signature(signature=signature, timestamp=timestamp,\ nonce=nonce): if request.method == 'GET': if echostr: return Response(int(echostr)) elif request.method == 'POST': body = request.body try: wechat.parse_data(body) message = wechat.get_message() response = _reply_message(message, wechat) return Response(response) except Exception, e: logger.error(e)
def getToken(request): token = 'xiangeqwd' wechat = WechatBasic(token=token) if wechat.check_signature(signature=request.GET.get('signature',''), timestamp=request.GET.get('timestamp',''), nonce=request.GET.get('nonce','')): # return HttpResponse(request.GET.get('echostr', 'error')) print('request method in getToken:',request.method) if request.method == 'GET': response = request.GET.get('echostr', 'error') else: xml2dict = wechat.parse_data(request.body) for k,v in xml2dict.items(): print(k,v) if xml2dict['Event'] == 'LOCATION' or 'VIEW': # if 'FromUserName' not in xml2dict or not xml2dict['FromUserName']: # xml2dict['FromUserName'] = request.META.get('REMOTE_ADDR') if 'Latitude' not in xml2dict.keys() or 'Longitude' not in xml2dict.keys(): latitude = float(22.5414180756) longitude = float(114.0480804443) else: latitude = float(xml2dict['Latitude']) longitude = float(xml2dict['Longitude']) # if not TblUser.objects.filter(openid=xml2dict['FromUserName']): # user = TblUser.objects.create( # id=uuid4(), # add_time=time.strftime(SERVER_TIME_FORMAT, time.localtime(time.time())), # openid=xml2dict['FromUserName'] # ) if TblUser.objects.filter(openid=xml2dict['FromUserName']).count() == 0: tbl_user = TblUser( id=uuid4(), add_time=time.strftime(SERVER_TIME_FORMAT, time.localtime(time.time())), openid=xml2dict['FromUserName'], latitude=latitude, longitude=longitude, default=user_service.SET_DEFAULT, access=user_service.ALLOW) tbl_user.save() # else: # TblUser.objects.filter(openid=xml2dict['FromUserName']).update( # latitude=latitude, # longitude=longitude) request.session['openid'] = xml2dict['FromUserName'] # message = wechat.get_message() # response = wechat.response_text(u'消息类型: {}'.format(message.type)) response = 'success' else: return HttpResponseBadRequest('Verify Failed') return HttpResponse(response)
def create_jsapi_signature(timestamp, nonceStr, url): """ 创建jsapi_signature """ jsapi_ticket = _get_jsapi_ticket() wechat = WechatBasic(appid=APP_ID, appsecret=APP_SECRET,\ jsapi_ticket=jsapi_ticket) signature = wechat.generate_jsapi_signature(timestamp, nonceStr, url,\ jsapi_ticket) return signature
def weixinapi(request): wechat = WechatBasic(token=TOKEN) if 'echostr' in request.GET: result = wechat.check_signature(signature=request.GET['signature'], timestamp=request.GET['timestamp'], nonce=request.GET['nonce']) if result: return HttpResponse(request.GET['echostr']) else: return HttpResponse() message = request.body response = process_msg(wechat, message) return HttpResponse(response)
def wechat_auth(request): try: wechat = WechatBasic(appid="wx85ddc4617e4400b0", appsecret="237dc3cc551b6bac043f660cbab093ca", token="feynman") signature = request.GET['signature'] timestamp = request.GET['timestamp'] nonce = request.GET['nonce'] if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): if request.method == 'GET': return HttpResponse(request.GET.get('echostr', ''), content_type="text/plain") else: wechat.parse_data(request.body) return HttpResponse(wechat_kernel(wechat, request), content_type="application/xml") else: return HttpResponse("Valid Auth") except Exception, e: print e.message return HttpResponse(e.message)
def update_menu(): """ 目前仅用作在pyhton shell中调用 """ wechat = WechatBasic(appid=APP_ID, appsecret=APP_SECRET) # logger.info(wechat.get_menu()) # 删除当前菜单 # wechat.delete_menu() # 创建菜单 wechat.create_menu({ 'button': [ { 'type': 'view', 'name': u'排队', 'url': get_auth_url_without_confirm('#/queue'), }, { 'type': 'view', 'name': u'点菜', 'url': get_auth_url_without_confirm('#/menu'), }, # { # 'type': 'view', # 'name': u'图片', # 'url': get_auth_url_without_confirm('#/photo/index'), # }, # { # 'name': '菜单', # 'sub_button': [ # { # 'type': 'view', # 'name': '视频', # 'url': 'http://v.qq.com/' # }, # { # 'type': 'click', # 'name': '赞一下我们', # 'key': 'V1001_GOOD' # } # ] # } ] })
def update_menu(): """ 目前仅用作在pyhton shell中调用 """ wechat = WechatBasic(appid=APP_ID, appsecret=APP_SECRET) # logger.info(wechat.get_menu()) # 删除当前菜单 # wechat.delete_menu() # 创建菜单 wechat.create_menu({ 'button':[ { 'type': 'view', 'name': u'排队', 'url': get_auth_url_without_confirm('#/queue'), }, { 'type': 'view', 'name': u'点菜', 'url': get_auth_url_without_confirm('#/menu'), }, # { # 'type': 'view', # 'name': u'图片', # 'url': get_auth_url_without_confirm('#/photo/index'), # }, # { # 'name': '菜单', # 'sub_button': [ # { # 'type': 'view', # 'name': '视频', # 'url': 'http://v.qq.com/' # }, # { # 'type': 'click', # 'name': '赞一下我们', # 'key': 'V1001_GOOD' # } # ] # } ]})
def get_access_token(): """ 返回access_token,如果超过过期时间(微信默认7200秒),就重新去获取 """ wechat = WechatBasic(appid=APP_ID, appsecret=APP_SECRET) access_token_expires_at =\ WechatStore.objects.get_or_create(key='access_token_expires_at')[0] access_token = WechatStore.objects.get_or_create(key='access_token')[0] if (not access_token_expires_at.value or\ not access_token.value or\ int(time.time()) > (int(access_token_expires_at.value)-200)): # 多算200秒 # 获取新access_token res = wechat.grant_token() access_token_expires_at.value = res['expires_in'] access_token_expires_at.save() access_token.value = res['access_token'] access_token.save() return access_token.value
from django_redis import get_redis_connection from django.contrib.auth.decorators import login_required from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from wechat_sdk.basic import WechatBasic from wechat_sdk.messages import TextMessage from lib.weixin import WeixinAPI from lib.weixin.pay import NativeLink_pub, UnifiedOrder_pub, Notify_pub from app.core.models import WeixinCustomer, Customer, CustomerOrder, CoreLog from app.wechat.models import WeixinLog from app.core.models import Customer from lib.pushcrew import pushcrew_notice wechat_instance = WechatBasic(token=settings.MP_WX_TOKEN, appid=settings.MP_WX_APPID, appsecret=settings.MP_WX_APPSECRET) @csrf_exempt def wechat(request): # 检验合法性 从 request 中提取基本信息 (signature, timestamp, nonce, xml) import sys import traceback try: signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') openid = request.GET.get('openid') if not wechat_instance.check_signature(
def weixin(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') xml = request.body wechat_instance = WechatBasic(token='custom_service', appid=weixin_appid, appsecret=weixin_secret) if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': return HttpResponse(request.GET.get('echostr')) try: wechat_instance.parse_data(data=xml) except ParseError: return HttpResponseBadRequest('Invalid XML Data') message = wechat_instance.get_message() # try: if message.type == 'text': # response = wechat_instance.response_text(u'文字') if do_commands_table.has_key(message.content): response = do_commands_table[message.content](wechat_instance, request) else: response = wechat_instance.response_text(message.content) elif message.type == 'image': content = message.media_id response = wechat_instance.response_text(u'图片') elif message.type == 'voice': response = wechat_instance.response_text(u'声音') elif message.type == 'video' or message.type == 'shortvideo': response = wechat_instance.response_text(u'视频') elif message.type == 'location': response = wechat_instance.response_text(u'地理位置') elif message.type == 'link': response = wechat_instance.response_text(u'链接') elif message.type == 'event': response = wechat_instance.response_text(u'事件') elif message.type == 'click' or message.type == 'view': if do_commands_table.has_key(message.key): response = do_commands_table[message.key](wechat_instance, request) else: response = wechat_instance.response_text(message.key) else: response = wechat_instance.response_text(u'未知' + message.type) # except: # response = wechat_instance.response_text(u'服务器错误') return HttpResponse(response)
def send_article_message(openid, articles): """ 给微信用户发送链接类的客服消息 """ wechat = WechatBasic(appid=APP_ID, appsecret=APP_SECRET) wechat.send_article_message(openid, articles)
if max_host_count is None: max_host_count = 3 auto_reply = None if auto_reply_mode and tuling_key is not None and tuling_url is not None: auto_reply = TulingAutoReply(tuling_key, tuling_url) else: auto_reply = DefaultAutoReply() mongo = MongoUtil(db_ip='localhost', db_name=mongo_db_name) wx_conf = WechatConf(token=wx_token, appid=wx_appid, appsecret=wx_secrert, encrypt_mode=wx_mode) wechat = WechatBasic(conf=wx_conf) with open("menu.json") as f: menu_str = f.read() js = json.loads(menu_str) wechat.delete_menu() wechat.create_menu(js) from handle import * web_handlers = [ (r'/', common.Index), (r'/wx', wx.WX), (r"/(favicon\.ico)", tornado.web.StaticFileHandler, { "path": os.path.join(os.path.dirname(__file__), "static") }),
from warframe import warframe from life import life from accountbook import AccountBook from wsmud import wsmud import time import random import re from random import choice import datetime WECHAT_TOKEN = "J29djw0OwplP" # APP_ID = 你的app id # APP_SECRET = 你的app secret # 实例化 WechatBasic wechat_instance = WechatBasic(token=WECHAT_TOKEN) @csrf_exempt def index(request): if request.method == 'GET': # 检验合法性 # 从 request 中提取基本信息 (signature, timestamp, nonce, xml) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed')
if mongo_db_name is None: mongo_db_name = 'green' if max_host_count is None: max_host_count = 3 auto_reply = None if auto_reply_mode and tuling_key is not None and tuling_url is not None: auto_reply = TulingAutoReply(tuling_key, tuling_url) # tuling reply else: auto_reply = DefaultAutoReply() # reply none mongo = MongoUtil(db_ip='localhost', db_name=mongo_db_name) wx_conf = WechatConf(token=wx_token, appid=wx_appid, appsecret=wx_secrert, encrypt_mode=wx_mode) wechat = WechatBasic(conf=wx_conf) with open("menu.json") as f: menu_str = f.read() js = json.loads(menu_str) wechat.delete_menu() wechat.create_menu(js) from handle import * web_handlers = [ (r'/', common.Index), (r'/wx', wx.WX), (r"/(favicon\.ico)", tornado.web.StaticFileHandler, {"path": os.path.join(os.path.dirname(__file__), "static")}),
def weixin(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') xml = request.body wechat_instance = WechatBasic(token='custom_service', appid=weixin_appid, appsecret=weixin_secret) if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': return HttpResponse(request.GET.get('echostr')) try: wechat_instance.parse_data(data=xml) except ParseError: return HttpResponseBadRequest('Invalid XML Data') message = wechat_instance.get_message() # try: if message.type == 'text': # response = wechat_instance.response_text(u'文字') if do_commands_table.has_key(message.content): response = do_commands_table[message.content](wechat_instance, request) else: response = wechat_instance.response_text(message.content) elif message.type == 'image': content = message.media_id response = wechat_instance.response_text(u'图片') elif message.type == 'voice': response = wechat_instance.response_text(u'声音') elif message.type == 'video' or message.type == 'shortvideo': response = wechat_instance.response_text(u'视频') elif message.type == 'location': response = wechat_instance.response_text(u'地理位置') elif message.type == 'link': response = wechat_instance.response_text(u'链接') elif message.type == 'event': response = wechat_instance.response_text(u'事件') elif message.type == 'click' or message.type == 'view': if do_commands_table.has_key(message.key): response = do_commands_table[message.key](wechat_instance, request) else: response = wechat_instance.response_text(message.key) else: response = wechat_instance.response_text(u'未知' + message.type) # except: # response = wechat_instance.response_text(u'服务器错误') return HttpResponse(response)
dInfo['Temp'] = temp dInfo['Humi'] = humi handle.deviceUpdateInfo(mac, res[0][1], 'Temp={0},Humi={1},Light={2}'.format(dInfo['Temp'], dInfo['Humi'], dInfo['Light'])) handle.close() return make_response('light='+dInfo['Light']) else: return make_response('Wrong Request Method!') #实例化全局的图灵机器人 tl = Tl123() #与微信对应的 token数组 access_token = 'hellozerotech' # 实例化 wechat,这是个全局变量 wechat = WechatBasic(token=access_token) #全局的消息响应 responeCase = {} #动态生成的装饰器,即使用函数封装的装饰器 #用于传入与type相同类型的 参数, 并调用 def responeMessage(type): #装饰器 def decorator(func): #利用装饰器,把类型和函数,通过字典联系起来,便于编程 responeCase[type] = func def warapper(instance): if(type is instance.__class__): return func(instance) else: return "Error" return warapper
def weixin_init(request): wechat = WechatBasic(appid=settings.WECHAT_APPID, appsecret=settings.WECHAT_APPSECRET) ret = wechat.create_menu(MENU) return HttpResponse(ret)
# -*- coding:utf8 -*- from wechat_sdk.basic import WechatBasic from wechat_sdk.messages import ( TextMessage, VoiceMessage, ImageMessage, VideoMessage, LinkMessage, LocationMessage, EventMessage ) import sys reload(sys) sys.setdefaultencoding('utf-8') #应用程序启动 if __name__ == '__main__': wechat = WechatBasic(appid='wxbc6e508bcdd18484', appsecret='4a769c618b870a86e002dd0b1c15deb6') result = wechat.create_menu({ 'button':[ { 'type': 'click', 'name': u'绑定设备', 'key': 'V1001_TODAY_MUSIC' }, { 'type': 'click', 'name': u'开/关', 'key': 'V1001_TODAY_SINGER' } ]}) print result
MENU = '''欢迎关注1lock,这是一个用微信控制的门锁: 请微信扫描门锁上的二维码^_^ ------------- 了解更多: https://github.com/qomo/welock ''' MYSQL_DB = sae.const.MYSQL_DB MYSQL_USER = sae.const.MYSQL_USER MYSQL_PASS = sae.const.MYSQL_PASS MYSQL_HOST_M = sae.const.MYSQL_HOST MYSQL_HOST_S = sae.const.MYSQL_HOST_S MYSQL_PORT = sae.const.MYSQL_PORT wechat = WechatBasic(token=TOKEN, appid=APPID, appsecret=APPSECRET) class ArduinoHandler(tornado.web.RequestHandler): """响应Arduino的查询和更新锁状态""" def get(self): self.lockticket = self.get_argument('lockticket') self.lockadmin = self.get_argument('lockadmin') self.state = self.get_argument('updata') lock = Lock(self.lockticket, self.lockadmin) if self.state == '2': if lock.islocked(): self.write("1") else: self.write("0") elif self.state == '0':
# author: HuYong # coding=utf-8 from django.http import HttpResponseBadRequest from django.shortcuts import HttpResponse from django.views.decorators.csrf import csrf_exempt from wechat_sdk.basic import WechatBasic from wechat_sdk.messages import TextMessage, EventMessage from models.models import User WECHAT_TOKEN = 'token' AppID = 'wxce660ee67e094937' AppSecret = '10108b4f9ec7bb9b76f4699087f620e6' wechat_instance = WechatBasic(token=WECHAT_TOKEN, appid=AppID, appsecret=AppSecret) @csrf_exempt def index(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') return HttpResponse(request.GET.get('echostr', ''), content_type="text/plain") # POST
# coding=utf-8 from django.shortcuts import render from django.shortcuts import HttpResponse from wechat.config import * from wechat_sdk.basic import WechatBasic from django.views.decorators.csrf import csrf_exempt wechat = WechatBasic(token=WEIXIN_TOKEN, appid=WEIXIN_APPID, appsecret=WEIXIN_APPSECRET) @csrf_exempt def main(request): if request.method == "GET": signature = request.GET.get("signature", None) timestamp = request.GET.get("timestamp", None) nonce = request.GET.get("nonce", None) echostr = request.GET.get("echostr", None) # 对签名进行校验, 微信服务器联通业务服务器 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse(echostr) else: return HttpResponse("weixin index") elif request.method == "POST": # 微信服务器发送过来的xml包体 body_text = request.body # xml包体解析成dict,实例化Message类 wechat.parse_data(body_text)