def dispatch(self, request, *args, **kwargs): self.openid = self.request.session.get('openid') error_msg = "" if not self.openid: code = request.GET.get('code') state = request.GET.get('state') if code and state: try: account = WeixinAccounts.getByOriginalId(state) request.session['account_key'] = account.key oauth = WeChatOAuth( account.app_id, account.app_secret, ) user_info = oauth.fetch_access_token(code) self.openid = user_info.get('openid') request.session['openid'] = self.openid w_user, old_subscribe = getOrCreateWeixinUser( self.openid, account) # w_user, is_first = WeixinUser.objects.get_or_create(openid=self.openid) # if is_first: # w_user.save() except WeChatException, e: error_msg = e.message else: error_msg = u"code or state is None" if error_msg: return redirectToJumpPage(error_msg)
def wrapper(*args, **kwargs): from wechatpy.oauth import WeChatOAuth if callable(state): _state = state() else: _state = state or '' redirect_uri = current_app.config.get('WECHAT_OAUTH_URI') if not redirect_uri: redirect_uri = request.url wechat_oauth = WeChatOAuth(current_app.config['WECHAT_APPID'], current_app.config['WECHAT_SECRET'], redirect_uri, scope, _state) user = check_func() if request.args.get('code') and not user: try: res = wechat_oauth.fetch_access_token(request.args['code']) except WeChatOAuthException: return abort(403) else: if scope == 'snsapi_base': set_user(res) else: user_info = wechat_oauth.get_user_info() set_user(user_info) elif not user: return redirect(wechat_oauth.authorize_url) return method(*args, **kwargs)
def check_wechat_binding(app=None, redirect_url=None): app = app or frappe.form_dict.app code = frappe.form_dict.code app_id = frappe.get_value('Wechat App', app, 'app_id') secret = frappe.get_value('Wechat App', app, 'secret') auth = WeChatOAuth(app_id, secret, '') token = auth.fetch_access_token(code) openid = token["openid"] expires_in = token['expires_in'] user = frappe.get_value('Wechat Binding', {'app': app, 'openid': openid}, 'user') if not user: redirect = "/" #redirect_url or frappe.form_dict.redirect or ('wechat/home/' + app) url = "/wechat_login?app=" + app + "&openid=" + openid + "&redirect=" + redirect frappe.local.flags.redirect_location = url raise frappe.Redirect frappe.logger(__name__).info(_("check_wechat_binding {0} {1}").format(frappe.session.user, user)) if frappe.session.user != user: #frappe.local.login_manager.clear_cookies() frappe.local.cookie_manager.to_delete = [] frappe.local.login_manager.login_as(user) if redirect_url: #frappe.local.response["type"] = "redirect" #frappe.local.response["location"] = redirect_url frappe.local.flags.redirect_location = redirect_url frappe.local.response["home_page"] = redirect_url frappe.local.response["redirect_to"] = redirect_url raise frappe.Redirect else: return app
def create_wechat_menu(app_name): print('--------------------------------------------------------') app_id = frappe.get_value('Wechat App', app_name, 'app_id') secret = frappe.get_value('Wechat App', app_name, 'secret') domain = "http://" + (frappe.get_value('Wechat App', app_name, 'domain') or "mm.symgrid.com") # Top Menu top_menu_list = frappe.get_all("Wechat AppMenu", filters={'parent': app_name, 'group_index': 0}, fields=["menu", "alias", "`group`"], order_by="`group`") menu_buttons = [] for menu in top_menu_list: doc = frappe.get_doc("Wechat Menu", menu.menu) menu_button = { "type": doc.menu_type or "view", "name": menu.alias or doc.menu_name } if doc.route: url = domain + "/wechat/" + doc.route + "/" + app_name else: url = domain + "/wechat/home/" + app_name menu_button["url"] = WeChatOAuth(app_id, secret, url).authorize_url # Sub menu sub_menu_list = frappe.get_all("Wechat AppMenu", filters={'parent': app_name, '`group`': menu.group}, fields=["menu", "alias", "group_index"], order_by="group_index") for sub_menu in sub_menu_list: if sub_menu.group_index == 0: continue if "sub_button" not in menu_button: menu_button = { "name": menu_button['name'], "sub_button": [] } doc = frappe.get_doc("Wechat Menu", sub_menu.menu) m = { "type": doc.menu_type or "view", "name": sub_menu.alias or doc.menu_name } if doc.route: url = domain + "/wechat/" + doc.route + "/" + app_name else: url = domain + "/wechat/home/" + app_name m["url"] = WeChatOAuth(app_id, secret, url).authorize_url menu_button["sub_button"].append(m) menu_buttons.append(menu_button) menu = { "button": menu_buttons } print(json.dumps(menu)) client = WeChatClient(app_id, secret) client.menu.create(menu) print('--------------------------------------------------------')
def __init__(self, wechat, scope='snsapi_userinfo'): """ :param wechat: instance of `models.Wechat` :param scope: """ self.wechat = wechat self.oauth = WeChatOAuth(wechat.appid, wechat.secret, wechat.redirect_uri, scope)
def wauth(): code = request.args.get('code') print 'code==>', code oauth = WeChatOAuth(APPID, APPSECRET, 'http://sc-wc.xmetadata.com') print 'code==>' # print 'check_access_token==>', oauth.check_access_token(code) access_token = oauth.fetch_access_token(code) print access_token user_info = oauth.get_user_info(access_token) return jsonify(user_info)
def getOpenID(code, page=''): APP_ID = 'wx21c7501e68d463df' APP_SECRET = '82fcc8a8bb59b2318f1e97a6292a7ecc' baseurl = 'http://www.pengchengguoyi.cn/health/webchat/' REDIRECT_URI = baseurl + page #scope = 'snsapi_userinfo' weChatOAuth = WeChatOAuth(app_id=APP_ID, secret=APP_SECRET, redirect_uri=REDIRECT_URI) res = weChatOAuth.fetch_access_token(code=code) openId = res['openid'] print '------------open id =' + openId +'----------------' return openId
def refresh(self): client = WeChatOAuth(settings.WX_APPID, settings.WX_APPSECRET, settings.WX_REDIRECT_URI, scope=self.scope) token = client.refresh_token(self.refresh_token) self.refresh_token = token['refresh_token'] self.access_token = token['access_token'] self.expires_in = token['expires_in'] self.scope = token['scope'] self.save()
def get_user_info(self, code, state='login'): entry = wxenv(self.env) wxclient = entry.wxclient oauth = WeChatOAuth(wxclient.appid, wxclient.appsecret, redirect_uri='', scope='snsapi_base', state=state) access_token = oauth.fetch_access_token(code) user_info = oauth.get_user_info(access_token['openid'], access_token=access_token['access_token']) logging.info(user_info) return user_info
def initial(self, request, *args, **kwargs): code = request.GET.get('code') state = request.GET.get('state') self.openid = "" if code and state: account = WeixinAccounts.getByOriginalId(state) request.session['account_key'] = account.account_key oauth = WeChatOAuth( account.app_id, account.app_secret, ) res = oauth.fetch_access_token(code) self.openid = res.get('openid')
def getOpenID(code, page=''): APP_ID = 'wx21c7501e68d463df' APP_SECRET = '82fcc8a8bb59b2318f1e97a6292a7ecc' baseurl = 'http://www.pengchengguoyi.cn/health/webchat/' REDIRECT_URI = baseurl + page #scope = 'snsapi_userinfo' weChatOAuth = WeChatOAuth(app_id=APP_ID, secret=APP_SECRET, redirect_uri=REDIRECT_URI) res = weChatOAuth.fetch_access_token(code=code) openId = res['openid'] print '------------open id =' + openId + '----------------' return openId
def get_auth(request): '''获取微信授权''' back_url = 'http://' + request.get_host() + '/wechat/getauthcallback/' next_url = request.GET.get('next', '') oauth = WeChatOAuth(settings.WECHAT_APP_ID, settings.WECHAT_APP_SECRET, back_url, scope='snsapi_userinfo', state=next_url) return redirect(to=oauth.authorize_url)
def authorize(request): code = request.GET.get('code', '') # use state to track user id state = request.GET.get('state', '') config = SiteConf.get_solo() if not config.enable_wechat: return HttpResponseForbidden('没有开启微信登录') client = WeChatOAuth(config.wx_appid, config.wx_appsecret, config.wx_redirect_uri, scope='snsapi_userinfo', state=state) # auth flow if code: try: # may raise access_token = client.fetch_access_token(code) user_info = client.get_user_info() user, _ = User.objects.get_or_create(username='******' + access_token['openid']) # may raise IntegrityError 微信用户已经绑定了关系 at, _ = AccessToken.objects.get_or_create( user=user, openid=access_token['openid']) at.update_token(access_token) # update profile user.profile.update_profile(user_info) token = issue_token(user) return JsonResponse({ 'token': token['token'], 'user': UserSerializer(user).data }) except Exception as e: return JsonResponse({ 'status': 'failed', 'message': str(e) }, status=400) return JsonResponse({'url': client.authorize_url})
def get(self): code = self.get_argument('code') state = self.get_argument('state') wechat_conf = utils.config.get_section('wechat') app_id = wechat_conf['appid'] app_secret = wechat_conf['appsecret'] web_url = utils.config.get('global', 'url') oauth_client = WeChatOAuth(app_id, app_secret, '') oauth_client.fetch_access_token(code) user_info = oauth_client.get_user_info() user_model = self.model_config.first( UserModel, open_id=user_info['openid']) # type:UserModel if user_model: user_model.profile = user_info['headimgurl'] user_model.nickname = user_info['nickname'] self.model_config.commit() else: user_model = UserModel(nickname=user_info['nickname'], open_id=user_info['openid'], sex=user_info['sex'], province=user_info['province'], country=user_info['country'], city=user_info['city'], profile=user_info['headimgurl'], privilege=user_info['privilege'], union_id=user_info['unionid']) self.model_config.add(user_model) self.session['user_id'] = user_model.id self.session['open_id'] = user_model.open_id self.session.save() if self.session.get('current_url', ''): current_url = urllib.unquote_plus(self.session.get('current_url')) self.session['current_url'] = '' self.session.save() self.logger.info('current_url:%s' % current_url) self.redirect(current_url) else: self.logger.info('current_url: null') self.redirect(web_url)
class Oauth(object): def __init__(self, wechat, scope='snsapi_userinfo'): """ :param wechat: instance of `models.Wechat` :param scope: """ self.wechat = wechat self.oauth = WeChatOAuth(wechat.appid, wechat.secret, wechat.redirect_uri, scope) def fetch_access_token(self, code): return self.oauth.fetch_access_token(code) def get_user_info(self): return self.get_user_info() @property def authorize_url(self): return self.oauth.authorize_url def oauth_required(self, method): @functools.wraps(method) def warpper(request, *args, **kwargs): code = request.GET.get('code', None) if request.session.get("user_info"): return method(request, *args, **kwargs) if code: try: self.oauth.fetch_access_token(code) user_info = self.oauth.get_user_info() except Exception as e: print(e.errmsg, e.errcode) # 这里需要处理请求里包含的 code 无效的情况 HttpResponse("ERROR") else: request.session['user_info'] = user_info request.session.set_expiry(SESSION_EXPIRED_SECONDS) else: return HttpResponseRedirect(self.authorize_url) return method(request, *args, **kwargs) return warpper
def view_orders(): try: code = request.args.get('code') if not code: raise ValueError('code cant empty') current_app.logger.info('code %s' % code) appid = current_app.config['WECHAT_APPID'] secret = current_app.config['WECHAT_SECRET'] oauth = WeChatOAuth(app_id=appid, secret=secret, redirect_uri="",) oauth.fetch_access_token(code) open_id = oauth.open_id wechat_user = UserWechat.query.filter_by(wechat_openid=open_id).first() if wechat_user: u = User.query.get(wechat_user.uid) login_user(u) return redirect(url_for('orderview.list_u_orders')) session['wechat_open_id'] = open_id return redirect(url_for('userview.login')) except: return redirect(url_for('userview.login'))
def goRedirect(page): APP_ID = 'wx21c7501e68d463df' APP_SECRET = '82fcc8a8bb59b2318f1e97a6292a7ecc' baseurl = 'http://www.pengchengguoyi.cn/health/webchat/' #baseurl = 'http://127.0.0.1:8000/webchat/' REDIRECT_URI = baseurl + page #scope = 'snsapi_userinfo' weChatOAuth = WeChatOAuth(app_id=APP_ID, secret=APP_SECRET, redirect_uri=REDIRECT_URI) goUrl = weChatOAuth.authorize_url return goUrl
def authorize(request): code = request.GET.get('code', '') # use state to track user id state = request.GET.get('state', '') config = SiteConf.get_solo() if not config.enable_wechat: return HttpResponseForbidden('没有开启微信登录') client = WeChatOAuth(config.wx_appid, config.wx_appsecret, config.wx_redirect_uri, scope='snsapi_userinfo', state=state) # auth flow if code: try: access_token = client.fetch_access_token(code) user_info = client.get_user_info() # get or create access_token at, _ = AccessToken.objects.get_or_create( openid=access_token['openid']) if not at.user: at.user = User.objects.create(username='******' + access_token['openid'], is_active=True) at.update_token(access_token) user = at.user # update profile user.profile.update_profile(user_info) login(request, user) request.session.set_expiry(3600 * 24 * 7) # 7days return redirect('wechat:index') except Exception as e: return HttpResponseForbidden('发生错误 {0}'.format(str(e))) return redirect(client.authorize_url)
def wrapper(request, *args, **kwargs): code = request.GET.get('code', None) openid = request.session.get('openid', None) print("weixin_decorator", code, openid) if openid is None: if code is None: # 获取授权码code redirect_url = '%s://%s%s' % (request.scheme, request.get_host(), request.get_full_path()) webchatOAuth = WeChatOAuth(settings.WECHAT_APPID, settings.WECHAT_SECRET, redirect_url, 'snsapi_userinfo') authorize_url = webchatOAuth.authorize_url return HttpResponseRedirect(authorize_url) else: # 同意授权,通过授权码获取ticket,根据ticket拉取用户信息 webchatOAuth = WeChatOAuth(settings.WECHAT_APPID, settings.WECHAT_SECRET, '', 'snsapi_userinfo') res = webchatOAuth.fetch_access_token(code) if 'errcode' in res: return HttpResponse(json.dumps(res)) else: open_id = webchatOAuth.open_id userinfo = webchatOAuth.get_user_info() userinfo.pop('privilege') obj, created = UserInfo.objects.update_or_create(openid=open_id, defaults=userinfo) print('-------------', obj, created) request.session['openid'] = open_id request.session['nickname'] = obj.nickname request.session['headimgurl'] = obj.headimgurl request.session["created"] = created if not created: request.session["username"] = obj.name request.session["car_type"] = obj.car_type return func(request, *args, **kwargs) else: return func(request, *args, **kwargs)
def get_auth_callback(request): '''微信授权回调''' code = request.GET.get('code') next_url = request.GET.get('state') if not code: return HttpResponse('您拒绝了授权!') oauth = WeChatOAuth(settings.WECHAT_APP_ID, settings.WECHAT_APP_SECRET, '') # 通过code换取access_token try: oauth.fetch_access_token(code) except Exception as e: return HttpResponse('获取微信授权出错!') try: platform_user = AuthPlatformUser.objects.get(openid=oauth.open_id) except AuthPlatformUser.DoesNotExist: # 获取微信用户信息 res = oauth.get_user_info() # 保存微信授权信息 platform_user = AuthPlatformUser(nickname=res['nickname'], avatar=res['headimgurl'], platform='wechat') platform_user.openid = oauth.open_id platform_user.access_token = oauth.access_token platform_user.refresh_token = oauth.refresh_token platform_user.expiretime = timezone.now() + timedelta(seconds=7200) platform_user.save() else: # 更新token platform_user.access_token = oauth.access_token platform_user.refresh_token = oauth.refresh_token platform_user.expiretime = timezone.now() + timedelta(seconds=7200) platform_user.save() request.session['wechat_user'] = platform_user.id # 跳转至主页 return redirect(next_url if next_url else 'wechat:activity')
def get(self): code = self.get_argument('code') state = self.get_argument('state') wechat_conf = utils.config.get_section('wechat') app_id = wechat_conf['appid'] app_secret = wechat_conf['appsecret'] web_url = utils.config.get('global', 'url') oauth_client = WeChatOAuth(app_id, app_secret, '') oauth_client.fetch_access_token(code) user_info = oauth_client.get_user_info() self.session['open_id'] = user_info['openid'] user_model = self.model_config.first(UserModel, open_id=user_info['openid']) # type:UserModel if user_model: user_model.profile = user_info['headimgurl'] user_model.nickname = user_info['nickname'] self.model_config.commit() else: user_model = UserModel(nickname=user_info['nickname'], open_id=user_info['openid'], sex=user_info['sex'], province=user_info['province'], country=user_info['country'], city=user_info['city'], profile=user_info['headimgurl'], privilege=user_info['privilege'], union_id=user_info['unionid'] ) self.model_config.add(user_model) self.session.save() if self.session.get('current_url', ''): current_url = urllib.unquote_plus(self.session.get('current_url')) self.session['current_url'] = '' self.session.save() self.logger.info('current_url:%s' % current_url) self.redirect(current_url) else: self.logger.info('current_url: null') self.redirect(web_url)
def wrapper(*args, **kwargs): from wechatpy.oauth import WeChatOAuth if callable(state): _state = state() else: _state = state or '' redirect_uri = current_app.config.get('WECHAT_OAUTH_URI') if not redirect_uri: redirect_uri = request.url user_agent = request.headers.get('User-Agent').lower() if 'micromessenger' in user_agent: app_id = current_app.config['WECHAT_APPID'] secret = current_app.config['WECHAT_SECRET'] url_method = 'authorize_url' else: app_id = current_app.config['WECHAT_OPEN_APP_ID'] secret = current_app.config['WECHAT_OPEN_APP_SECRET'] url_method = 'qrconnect_url' wechat_oauth = WeChatOAuth(app_id, secret, redirect_uri, scope, _state) user = check_func() if request.args.get('code') and not user: try: res = wechat_oauth.fetch_access_token(request.args['code']) except WeChatOAuthException: return abort(403) else: if scope == 'snsapi_base': set_user(res) else: user_info = wechat_oauth.get_user_info() set_user(user_info) elif not user: return redirect(getattr(wechat_oauth, url_method)) return method(*args, **kwargs)
def wrapper(*args, **kwargs): from wechatpy.oauth import WeChatOAuth if callable(state): _state = state() else: _state = state or '' redirect_uri = current_app.config.get('WECHAT_OAUTH_URI') if not redirect_uri: redirect_uri = request.url user_agent = request.headers.get('User-Agent').lower() if 'micromessenger' in user_agent: app_id = current_app.config['WECHAT_APPID'] secret = current_app.config['WECHAT_SECRET'] url_method = 'authorize_url' else: app_id = current_app.config['WECHAT_OPEN_APP_ID'] secret = current_app.config['WECHAT_OPEN_APP_SECRET'] url_method = 'qrconnect_url' wechat_oauth = WeChatOAuth(app_id, secret, redirect_uri, scope, _state) user = check_func() if request.args.get('code') and not user: try: res = wechat_oauth.fetch_access_token(request.args['code']) except WeChatOAuthException: return abort(403) else: if scope == 'snsapi_base': set_user(res) else: user_info = wechat_oauth.get_user_info() set_user(user_info) elif not user: return redirect(getattr(wechat_oauth, url_method)) return method(*args, **kwargs)
def decorated_func(*args, **kwargs): scope = 'snsapi_userinfo' code = request.args.get('code', None) redirect_uri = current_app.config['REDIRECT_URI'] wechat_oauth = WeChatOAuth(current_app.config['APPID'], current_app.config['APPSECRET'], redirect_uri, scope) url = wechat_oauth.authorize_url # FIXME 第二次用code, 也可能是因为我的域名没有备案的问题详见Readme.md/todo, 错误14603 if code: current_app.logger.warning('code:' + code) try: user_access_token = wechat_oauth.fetch_access_token(code) user_info = wechat_oauth.get_user_info() except Exception as e: print(e.errmsg, e.errcode) abort(403) else: current_app.logger.warning('user_info:' + str(user_info)) # session['user_info'] = user_info else: return redirect(url) return decorated_func(*args, **kwargs)
def dispatch(self, request, *args, **kwargs): code = request.GET.get('code') state = request.GET.get('state') error_msg = "" if code and state: account = WeixinAccounts.getByOriginalId(state) request.session['account_key'] = account.account_key oauth = WeChatOAuth( account.app_id, account.app_secret, ) res = oauth.fetch_access_token(code) self.openid = res.get('openid') w_user, old_subscribe = getOrCreateWeixinUser(self.openid, account) if not w_user: error_msg = "error" if not w_user.user: error_msg = u"请先绑定网利宝账号" else: error_msg = u"code or state is None" if error_msg: return redirectToJumpPage(error_msg) return super(BaseWeixinTemplate, self).dispatch(request, *args, **kwargs)
def wechat_send(self): if self.docstatus != 1: return if self.status in ["Error", "Finished"]: return app_doc = frappe.get_doc("Wechat App", self.app) if app_doc.language: frappe.local.lang = app_doc.language else: frappe.local.lang = frappe.db.get_single_value('System Settings', 'language') src_doc = frappe.get_doc(self.document_type, self.document_id) if not src_doc: self.__set_error(("Cannot find doc {0} id {1}").format(self.document_type, self.document_id)) data = src_doc.run_method("wechat_tmsg_data") if not data: self.__set_error(("Cannot generate wechat template data for {0}").format(self.document_type)) url = src_doc.run_method("wechat_tmsg_url") if not url: self.__set_error(("Cannot generate wechat template url for {0}").format(self.document_type)) url = "http://" + app_doc.domain + "/wechat_redirect?" + urllib.urlencode({'wc_rurl': url, 'app': self.app}) template_id = frappe.get_value('Wechat App', self.app, self.__get_template_id()) if not template_id: self.__set_error(("Cannot find wechat template id for {0} from app {1}").format(self.document_type, self.app)) client = WeChatClient(app_doc.app_id, app_doc.secret) authorize_url = WeChatOAuth(app_doc.app_id, app_doc.secret, url).authorize_url users = self.get("to_users") count = 0 for user in users: done = self.__send_wechat_msg(client, user, template_id, authorize_url, data) if done: count = count + 1 if count > 0: self.set("status", "Partial") if count == len(users): self.set("status", "Finished") self.save()
def wrapper(request, *args, **kwargs): code = request.GET.get('code', None) openid = request.session.get('openid', None) print('weixin_decorator', code, openid) if openid is None: if code is None: # 获取授权码code redirect_url = '%s://%s%s' % (request.scheme, request.get_host(), request.get_full_path()) print('redirect_url=', redirect_url) webchatOAuth = WeChatOAuth(settings.WECHAT_APPID, settings.WECHAT_SECRET, redirect_url, 'snsapi_userinfo') authorize_url = webchatOAuth.authorize_url return HttpResponseRedirect(authorize_url) else: # 同意授权,通过授权码获取ticket,根据ticket拉取用户信息 webchatOAuth = WeChatOAuth(settings.WECHAT_APPID, settings.WECHAT_SECRET, '', 'snsapi_userinfo') res = webchatOAuth.fetch_access_token(code) if 'errcode' in res: return HttpResponse(json.dumps(res)) else: open_id = webchatOAuth.open_id userinfo = webchatOAuth.get_user_info() userinfo.pop('privilege') obj, created = WxUserinfo.objects.update_or_create( openid=open_id, defaults=userinfo) request.session['openid'] = open_id userinf = get_object_or_404(WxUserinfo, openid=open_id) request.session['nickname'] = userinf.nickname request.session['is_member'] = userinf.is_member request.session['headimgurl'] = userinf.headimgurl request.session[ 'role'] = userinf.member_role.id if userinf.member_role else 0 return func(request, *args, **kwargs) else: request.session['openid'] = openid userinf = get_object_or_404(WxUserinfo, openid=openid) request.session['nickname'] = userinf.nickname # request.session['is_member'] = userinf.is_member request.session['is_member'] = 1 request.session['headimgurl'] = userinf.headimgurl request.session[ 'role'] = userinf.member_role.id if userinf.member_role else 0 return func(request, *args, **kwargs)
def redirectUrl(request, item): case_id = request.GET.get('case_id', None) code = request.GET.get('code', None) openid = request.session.get('openid', None) print('code=', code) print('openid=', openid) print('case_id=', case_id) if openid is None: if code is None: # 获取授权码code redirect_url = '%s/redirect/%s' % (APP_URL, item) webchatOAuth = WeChatOAuth(APPID, APPSECRET, redirect_url, 'snsapi_userinfo') authorize_url = webchatOAuth.authorize_url print(authorize_url) return HttpResponseRedirect(authorize_url) else: # 同意授权,通过授权码获取ticket,根据ticket拉取用户信息 webchatOAuth = WeChatOAuth(APPID, APPSECRET, '', 'snsapi_userinfo') res = webchatOAuth.fetch_access_token(code) if 'errcode' in res: return HttpResponse(json.dumps(res)) else: open_id = webchatOAuth.open_id print(openid,'openid') count = Civil.objects.filter(openid=open_id, subscribe=1).count() if count == 0: userinfo = webchatOAuth.get_user_info() print(userinfo) userinfo.pop('privilege') Civil.objects.create(**userinfo) request.session['openid'] = open_id userinf = get_object_or_404(Civil, openid=open_id) request.session['nickname'] = userinf.nickname request.session['headimgurl'] = userinf.headimgurl redirect_url = getUrl(item) return HttpResponseRedirect(redirect_url) else: userinf = get_object_or_404(Civil, openid=openid) request.session['headimgurl'] = userinf.headimgurl redirect_url = getUrl(item) return HttpResponseRedirect(redirect_url)
def get_auth_callback(request): '''微信授权回调''' code = request.GET.get('code') next_url = request.GET.get('state') if not code: return HttpResponse('您拒绝了授权!') oauth = WeChatOAuth(settings.WECHAT_APP_ID, settings.WECHAT_APP_SECRET, '') # 通过code换取access_token try: oauth.fetch_access_token(code) except Exception as e: return HttpResponse('获取微信授权出错!') try: platform_user = AppPlatformUser.objects.get(openid=oauth.open_id) except AppPlatformUser.DoesNotExist: try: with transaction.atomic(): # 启用事务提交 # 获取微信用户信息 res = oauth.get_user_info() # 创建用户 user = AuthUser(password='') user.username = '******' + str(uuid.uuid1()).replace('-', '')[:20] user.nickname = res['nickname'] user.avatar = res['headimgurl'] user.save() # 保存user profile user_profile = AppUserProfile(user_id=user.id) user_profile.save() # 保存微信授权信息 platform_user = AppPlatformUser(user_id=user.id, nickname=user.nickname, avatar=user.avatar, platform='wechat') platform_user.openid = oauth.open_id platform_user.access_token = oauth.access_token platform_user.refresh_token = oauth.refresh_token platform_user.expiretime = timezone.now() + timedelta( seconds=7200) platform_user.save() except (Exception) as e: return HttpResponse('微信登录出错!') else: user = AuthUser.objects.get(id=platform_user.user_id) if user.username and user.mobile and user.password: # 更新token platform_user.access_token = oauth.access_token platform_user.refresh_token = oauth.refresh_token platform_user.expiretime = timezone.now() + timedelta(seconds=7200) platform_user.save() # 登录 auth.login(request, auth.authenticate(username=user.mobile)) # 跳转至主页 return redirect(next_url if next_url else 'wechat:main') request.session['user_id'] = user.id # 跳转至 完善注册页 # return redirect('wechat:register', **{'user_id': user.id}) return redirect('/wechat/register/{0}/?next={1}'.format(user.id, next_url))
def post(self, request, args, shop_code): login_type = args["login_type"] code = args.get("code", None) phone = args.get("phone", None) pwd = args.get("password", None) sms_code = args.get("sms_code", None) self._set_current_shop(request, shop_code) shop = self.current_shop # todo 微信登录还需要修改 # 若登录方式为微信 if login_type == UserLoginType.WX: if not code: return self.send_fail(error_text="微信登录缺少code") shop_appid = MP_APPID shop_appsecret = MP_APPSECRET wechat_oauth = WeChatOAuth( app_id=shop_appid, secret=shop_appsecret, redirect_uri="", scope="snsapi_userinfo", ) try: wechat_oauth.fetch_access_token(code) user_info = wechat_oauth.get_user_info() except: return self.send_fail(error_text='获取微信授权失败') """ user_info = { "openid": "oMZbfv3iy12L1q1XGWpkko_P_YPI", "nickname": "hpf", "sex": 1, "language": "zh_CN", "city": "武汉", "province": "湖北", "country": "中国", "headimgurl": "http://thirdwx.qlogo.cn/mmopen/vi_32/yctGCWkz1jI2ybfVe12KmrXIb9R89dfgnoribX9sG75hBPJQlsK30fnib9r4nKELHcpcXAibztiaHH3jz65f03ibOlg/132", "privilege": [], "unionid": "oIWUauOLaT50pWKUeNKhKP6W0WIU" } """ user_info["headimgurl"] = user_info["headimgurl"].replace( "http://", "https://") user = get_user_by_wx_unionid(user_info.get("unionid")) if not user: new_user_info = { "username": user_info.get('phone'), "phone": user_info.get('phone'), "sex": user_info.get('sex'), "nickname": user_info.get("nickname"), "realname": user_info.get("realname"), "head_image_url": user_info.get("headimgurl"), "wx_unionid": user_info.get("unionid"), "wx_openid": user_info.get("openid"), "wx_country": user_info.get("country"), "wx_province": user_info.get("province"), "wx_city": user_info.get("city"), } user_serializer = UserCreateSerializer(data=new_user_info) user = user_serializer.save() ret, user_openid = get_openid_by_user_id_and_appid( user.id, shop_appid) # 不存在则添加用户的openid if not ret: info = { 'user_id': user.id, 'mp_appid': shop_appid, 'wx_openid': user_info.get("openid"), } create_user_openid(**info) # 若登录方式为密码 elif login_type == UserLoginType.PWD: if not phone and not pwd: return self.send_fail(error_text="密码登录缺手机号或密码") success, user = get_user_by_phone_and_password( phone, pwd, login_type) if not success: return self.send_fail(error_text=user) # 若登陆方式为手机号 else: if not phone and not sms_code: return self.send_fail(error_text="密码登录缺手机号或验证码") redis_conn = get_redis_connection("verify_codes") real_sms_code = redis_conn.get("sms_%s" % phone) if not real_sms_code: return self.send_fail(error_text="验证码已过期") if str(real_sms_code.decode()) != sms_code: return self.send_error(status_code=status.HTTP_400_BAD_REQUEST, error_message={"detail": "短信验证码错误"}) success, user = get_user_by_phone(phone, login_type) if not success: return self.send_fail(error_text=user) # user不存在 if not user: return self.send_fail(error_text="该用户不存在") customer = get_customer_by_user_id_and_shop_id_interface( user.id, shop.id) # 新客户则创建客户信息 if not customer: create_customer(user.id, shop.id) token, refresh_token = self._set_current_user(user) response_data = jwt_response_payload_handler(token, refresh_token, user, request) return self.send_success(data=response_data)
def getWeChatOAuth(redirect_url): return WeChatOAuth(settings.AppID, settings.AppSecret, redirect_url)
class WeOAuth(object): # snsapi_base-不需授权; snsapi_userinfo-需授权 # state: 重定向后会带上此参数, 开发者可以填写a-zA-Z0-9的参数值,最多128字节 we_oauth = WeChatOAuth(app_id=settings.MP_APP_ID, secret=settings.MP_APP_SECRET, redirect_uri='', scope='snsapi_userinfo', state='1') @classmethod def get_user_info(cls, code): """ 使用code通过微信OAUTH2接口, 获取openid. # http://www.cnblogs.com/txw1958/p/weixin76-user-info.html { 'province': '广东', 'openid': 'ovj3E0l9vffwBuqz_PNu25yL_is4', 'headimgurl': 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM7AianZsHE6LefhQuSmwibx4KZ9LYkRmIibrFKmSbAVjlpBg/0', 'language': 'zh_CN', 'city': '广州', 'country': '中国', 'sex': 1, 'privilege': [], 'nickname': '测试账号' } """ if not settings.ENV.is_production(): # 返回例子 user_info = { 'province': '广东', 'openid': 'ovj3E0l9vffwBuqz_PNu25yL_is4', 'headimgurl': 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM7AianZsHE6LefhQuSmwibx4KZ9LYkRmIibrFKmSbAVjlpBg/0', 'language': 'zh_CN', 'city': '广州', 'country': '中国', 'sex': 1, 'privilege': [], 'nickname': '开发环境测试号' } pass user_info['openid'] = code return user_info['openid'], user_info['nickname'], user_info[ 'headimgurl'] try: openid_access_token = cls.we_oauth.fetch_access_token(code) except WeChatOAuthException as e: sentry_sdk.capture_exception(e) return None, None, None # fetch_access_token 函数返回: # { # 'access_token': 'vX1lcBkeRY6WZUylVyZA9XPeoA92_15iBAXHHRtBD1dtbAtWe9e3i-DyHR9PBtP6L', # 'openid': 'ovj3E0l9vffwBuqz_PNu25yL_is4', # 'expires_in': 7200, # 'refresh_token': 'LSaCEeS8m-18_njiAN8Jm11V4QIeWxwOSsjEV9cM1ra5zkL', # 'scope': 'snsapi_userinfo' # } user_info = cls.we_oauth.get_user_info( openid=openid_access_token['openid'], access_token=openid_access_token['access_token']) openid = user_info['openid'] nickname = user_info['nickname'] avatar = user_info['headimgurl'] return openid, nickname, avatar
''' ApiKey = "Kp1b4lH5z3n0DqGxu2IcQsV6F7PUWvmZ" MchID = "1491203572" NotifyUrl = "http://wechat.onmytarget.cn/payback" client = WeChatClient(AppId, AppSecret) jsApiClient = WeChatJSAPI(client=client) mediaApiClient = WeChatMedia(client=client) payClient = WeChatPay(appid=AppId, api_key=ApiKey, mch_id=MchID, mch_cert=os.path.join(settings.BASE_DIR, 'carcert', 'apiclient_cert.pem'), mch_key=os.path.join(settings.BASE_DIR, 'carcert', 'apiclient_key.pem')) oauthClient = WeChatOAuth(app_id=AppId, secret=AppSecret, redirect_uri=DOMAIN) def get_wechat_config(request): """ 获取微信config字符串 :param request: :return: """ timestamp = to_text(int(time.time())) nonce_str = random_string(32) jsapi_ticket = jsApiClient.get_jsapi_ticket() url = DOMAIN + request.get_full_path() signature = jsApiClient.get_jsapi_signature(nonce_str, jsapi_ticket, timestamp, url) config_dict = Context({
def redict(request): # 本地模拟时候假设已经拿到数据 id = "wx06e40e988b339f37" secret = "85a43e84aec7ea073877fab4349ee226" wechatouath = WeChatOAuth(id, secret, "redirect_uri=http://tangzongyu.com/redict", scope=u'snsapi_userinfo') code = request.GET.get('code') wechatouath.fetch_access_token(code) wechatouath.check_access_token() json_data = wechatouath.get_user_info() openid = json_data['openid'] nickname = json_data['nickname'] sex = json_data['sex'] province = json_data['province'] city = json_data['city'] country = json_data['country'] headimgurl = json_data['headimgurl'] # openid = 'oYMTS0jjf2rhak6v6AxjC_nKl5hQ' # nickname = 'testuser' # sex = 1 # province = '浙江' # city = '温州' # country = '中国' # headimgurl = 'http://wx.qlogo.cn/mmopen/dDqE5bg9gbZXkq2EOaHsnHRwN1xLiawElO4oKKfMvZYeFcf2U7yTvxHhIzkWCydiaVWh7xic5waUlw6daLtAxMEQCjRIKiaXWYjJ/0' try: wechat_user = WeChatUser.objects.get(openid=openid) user = authenticate(username=openid, password="******" + openid) if user is not None: if user.is_active: login(request, user) # response = HttpResponseRedirect('/homepage',status=200) # response.set_cookie() return render(request, 'index.html') else: return HttpResponse('登录失败') else: return HttpResponse('登录失败') except: wechat_user = WeChatUser.objects.create(openid=openid, sex=sex, nickname=nickname, city=city, province=province, country=country, headimgurl=headimgurl) wechat_user.save() user = User.objects.create_user(username=openid, email='email', password="******" + openid) user.save() # 添加用户权限: admin_permission = Admin_Permission.objects.create(user=user) admin_permission.save() login_user = authenticate(username=openid, password="******" + openid) if login_user is not None: if login_user.is_active: login(request, login_user) return render(request, 'index.html') else: return HttpResponse('登录失败') else: return HttpResponse('登录失败')