def get(self, request, *args, **kwargs): """ 接受微信跳转页面传过来的code票据 """ form = AuthCallbackForm(request.data) if not form.is_valid(): return Response(status=status.HTTP_200_OK) cld = form.cleaned_data result = self.verify_random_str(cld) if isinstance(result, Exception): return Response(status=status.HTTP_200_OK) serializer = RandomStringSerializer(result) try: serializer.update(result, {'status': 1}) except: pass # 获取access token access_token_params = wx_auth_settings.WX_AUTH_PARAMS['get_access_token'] access_token_params['code'] = cld['code'] access_token_url = wx_auth_settings.WX_AUTH_URLS['get_access_token'] result = send_http_request(access_token_url, access_token_params) if isinstance(result, Exception) or not getattr(result, 'text'): return Response(status=status.HTTP_200_OK) # 存储token response_dict = json.loads(result.text) if 'access_token' not in response_dict: return Response(status=status.HTTP_200_OK) response_dict['state'] = cld['state'] serializer = AccessTokenSerializer(data=response_dict) if serializer.is_valid(): serializer.save() else: return Response(status=status.HTTP_200_OK) # 获取微信userinfo userinfo_params = wx_auth_settings.WX_AUTH_PARAMS['get_userinfo'] userinfo_params['openid'] = response_dict['openid'] userinfo_params['access_token'] = response_dict['access_token'] userinfo_url = wx_auth_settings.WX_AUTH_URLS['get_userinfo'] result = send_http_request(userinfo_url, userinfo_params) if isinstance(result, Exception) or not getattr(result, 'text'): return Response(status=status.HTTP_200_OK) # 存储数据到用户表 userinfo_response_dict = json.loads(result.text) if 'openid' not in userinfo_response_dict: return Response(status=status.HTTP_200_OK) serializer = WXUserSerializer(data=userinfo_response_dict) if serializer.is_valid(): serializer.save() else: return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_200_OK)
def send_identifying_code_to_phone(params, receive_phones, template): """ 使用阿里云的短信服务发送短信 """ from horizon.http_requests import send_http_request import urllib url = 'http://sms.market.alicloudapi.com/singleSendSms' AppCode = '2e8a1a8a3e22486b9be6ac46c3d2c6ec ' if isinstance(params, (str, unicode)): params_query = params elif isinstance(params, dict): params_query = urllib.quote(json.dumps(params)) else: return TypeError('params must be unicode or dictionary') if not isinstance(receive_phones, (tuple, list)): return TypeError('receive phones type must be list or tuple') query = { 'ParamString': params_query, 'RecNum': ','.join(receive_phones), 'TemplateCode': template } return send_http_request( url, query, add_header={'Authorization:': 'APPCODE %s' % AppCode})
def send_identifying_code_to_phone(params, receive_phones, template_name=None): """ 使用阿里云的短信服务发送短信 """ from horizon.http_requests import send_http_request import urllib url = 'http://sms.market.alicloudapi.com/singleSendSms' AppCode = '2e8a1a8a3e22486b9be6ac46c3d2c6ec' sign_names = ('吟食', ) template_dict = {'register': 'SMS_71365776'} if not template_name: template = template_dict['register'] else: if template_name not in template_dict.keys(): return ValueError('Params template incorrect') template = template_dict[template_name] if isinstance(params, (str, unicode)): params_query = params elif isinstance(params, dict): params_query = urllib.quote(json.dumps(params)) else: return TypeError('params must be unicode or dictionary') if not isinstance(receive_phones, (tuple, list)): return TypeError('receive phones type must be list or tuple') query = { 'RecNum': ','.join(receive_phones), 'TemplateCode': template, 'SignName': sign_names[0] } query_str = '%s&ParamString=%s' % (urllib.urlencode(query), params_query) return send_http_request( url, query_str, add_header={'Authorization': 'APPCODE %s' % AppCode})
def login_to_tt(self, data): login_info_dict = { # 手机号、验证码登录 'phone_identifying_code': { 'login_info': APP_REQUEST_URLS['login_mobile'], 'login_params': APP_REQUEST_PARAMS['login_mobile'] }, # 手机号、密码登录 'phone_password': { 'login_info': APP_REQUEST_URLS['login_mobile_password'], 'login_params': APP_REQUEST_PARAMS['login_mobile_password'] }, # 邮箱、密码登录 'email_password': { 'login_info': APP_REQUEST_URLS['login_email'], 'login_params': APP_REQUEST_PARAMS['login_email'] } } params_info_dict = { 'phone_identifying_code': ('mobile', 'code'), 'phone_password': ('mobile', 'password'), 'email_password': ('email', 'password'), } account = data['phone'] if data['login_type'].startswith( 'phone') else data['email'] login_info = login_info_dict[data['login_type']] # 向TT发送登录请求 call_url = RequestPublicParams.get_perfect_url_with_query_string( phone=self.phone, call_url=login_info['login_info']['url']) params = copy.copy(login_info['login_params']) params[params_info_dict[data['login_type']] [0]] = make_perfect_tt_security_string(account) params[params_info_dict[data['login_type']] [1]] = make_perfect_tt_security_string(data['password']) header = HttpHeaderAction.make_tt_http_header(account=account) result = send_http_request(access_url=call_url, access_params=params, method=login_info['login_info']['method'], headers=header, verify=False) return result
def send_mobile_message(mobile='', verifying_code=''): """ 发送手机短信验证码 :param mobile: 手机号 :param verifying_code: 验证码 :return: True """ client_id = '150805950' client_secret = '1A6D984B13D56EC82858F2C345583472' params_dict = { 'client_id': client_id, 'sign': hmac.new(client_secret.encode('utf8'), client_id.encode('utf8'), 'sha1').hexdigest(), 'content': '验证码:%s, 您正在入驻精灵魔镜,请于5分钟内完成验证, 若非本人操作, 请忽略此短信。' % verifying_code, 'type': 1, 'mobile': mobile if mobile.startswith('86') else '86%s' % mobile } sms_url = 'http://xopen.ksmobile.com/sms/data' return http_requests.send_http_request(sms_url, params_dict, method='post')
def send_message_to_phone(params, receive_phones, template_name=None): """ 使用阿里云的短信服务发送短信 """ url = 'http://sms.market.alicloudapi.com/singleSendSms' AppCode = '2e8a1a8a3e22486b9be6ac46c3d2c6ec' sign_names = ('吟食', ) template_dict = {'register': 'SMS_91765097', 'recharge': 'SMS_102170028'} params_key_dict = {'register': 'code', 'recharge': 'count'} if not template_name: template = template_dict['register'] else: if template_name not in template_dict.keys(): return ValueError('Params template incorrect') template = template_dict[template_name] if isinstance(params, (str, unicode, int, float)): if isinstance(params, (float, int)): params_dict = {params_key_dict[template_name]: '%.2f' % params} else: params_dict = {params_key_dict[template_name]: params} params_query = urllib.quote(json.dumps(params_dict)) elif isinstance(params, dict): params_query = urllib.quote(json.dumps(params)) else: return TypeError('params must be unicode or dictionary') if isinstance(receive_phones, (str, unicode)): receive_phones = [receive_phones] else: if not isinstance(receive_phones, (tuple, list)): return TypeError('receive phones type must be list or tuple') query = { 'RecNum': ','.join(receive_phones), 'TemplateCode': template, 'SignName': sign_names[0] } query_str = '%s&ParamString=%s' % (urllib.urlencode(query), params_query) return send_http_request( url, query_str, add_header={'Authorization': 'APPCODE %s' % AppCode})
def send_phone_message_for_5_platform(identifying_code, receive_phones): """ 使用ippy(华信科技)的短信平台发送短信 """ gateway = 'https://dx.ipyy.net/smsJson.aspx' if isinstance(receive_phones, (list, tuple)): receive_phones = ','.join(receive_phones) # 从数据库中获取 account = 'CD00088' # 从数据库中获取 password = '******' content = u'您的验证码是%s,15分钟内有效【影联客】' % identifying_code params_dict = { 'account': account, 'action': 'send', 'content': content.encode('utf8'), 'mobile': receive_phones, 'password': hashlib.md5(password).hexdigest().upper(), 'userid': '' } return send_http_request(gateway, params_dict)
def comment_to_tt(self, data): comment_url_info = APP_REQUEST_URLS['comment'] comment_params = APP_REQUEST_PARAMS['comment'] # 向TT发送登录请求 call_url = RequestPublicParams.get_perfect_url_with_query_string( phone=None, call_url=comment_url_info['url']) params = copy.copy(comment_params) params['comment_duration'] = params['comment_duration']() params['content'] = data['content'] params['group_id'] = data['group_id'] params['item_id'] = data['group_id'] params['staytime_ms'] = params['staytime_ms']() params['text'] = data['content'] header = HttpHeaderAction.make_tt_http_header( tt_user_id=data['tt_user_id']) result = send_http_request(access_url=call_url, access_params=params, method=comment_url_info['method'], headers=header, verify=False) return result
def post(self, request, *args, **kwargs): """ 接受微信跳转页面传过来的code票据 """ form = AuthCallbackForm(request.data) if not form.is_valid(): return Response({'Detail': form.errors}, status=status.HTTP_400_BAD_REQUEST) cld = form.cleaned_data result = self.verify_random_str(cld) if isinstance(result, Exception): return Response({'Detail': result.args}, status=status.HTTP_400_BAD_REQUEST) # serializer = RandomStringSerializer(result) # try: # serializer.update(result, {'status': 1}) # except: # pass # 获取access token access_token_params = wx_auth_settings.WX_AUTH_PARAMS[ 'get_access_token'] access_token_params['code'] = cld['code'] access_token_url = wx_auth_settings.WX_AUTH_URLS['get_access_token'] response = send_http_request(access_token_url, access_token_params) if isinstance(response, Exception) or not getattr(response, 'text'): return Response({'Detail': response.args}, status=status.HTTP_400_BAD_REQUEST) # 存储token response_dict = json.loads(response.text) if 'access_token' not in response_dict: return Response({'Detail': 'Get access token failed'}, status=status.HTTP_400_BAD_REQUEST) response_dict['state'] = cld['state'] serializer = AccessTokenSerializer(data=response_dict) if serializer.is_valid(): serializer.save() else: return Response({'Detail': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) # 获取微信userinfo userinfo_params = wx_auth_settings.WX_AUTH_PARAMS['get_userinfo'] userinfo_params['openid'] = response_dict['openid'] userinfo_params['access_token'] = response_dict['access_token'] userinfo_url = wx_auth_settings.WX_AUTH_URLS['get_userinfo'] response = send_http_request(userinfo_url, userinfo_params) if isinstance(response, Exception) or not getattr(response, 'text'): return Response({'Detail': response.args}, status=status.HTTP_400_BAD_REQUEST) # 存储数据到用户表 userinfo_response_dict = json.loads(response.text) if 'openid' not in userinfo_response_dict: return Response({'Detail': 'Get User Info failed'}, status=status.HTTP_400_BAD_REQUEST) # 检查用户是否存在 _user = self.get_user_by_open_id(userinfo_response_dict['openid']) if isinstance(_user, Exception): # 新用户 serializer = WXUserSerializer(data=userinfo_response_dict) if not serializer.is_valid(): return Response({'Detail': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) _user = serializer.save() # _user = self.get_user_by_open_id(userinfo_response_dict['openid']) # is_binding = False _token = Oauth2AccessToken().get_token(_user) if isinstance(_token, Exception): return Response({'Detail': _token.args}, status=status.HTTP_400_BAD_REQUEST) # _token.update(**{'is_binding': is_binding}) # 更新微信授权登录随机码状态 serializer = RandomStringSerializer(result) random_init_data = { 'status': 1, 'access_token_data': json.dumps(_token) } try: serializer.update(result, random_init_data) except: pass # 标记用户已经登录 self.mark_user_login(_user) return Response(_token, status=status.HTTP_200_OK)