<reponame>gaosong666/taobao
from urllib.parse import urlencode

import requests
from itsdangerous import BadData
from itsdangerous import BadSignature
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from rest_framework.utils import json

from mall import settings


def generate_save_token(openid):
    # serializer = Serializer(settings.SECRET_KEY, 300)
    # data = {'openid': openid}
    # token = serializer.dumps(data)
    # token = token.decode()
    # try:
    #     data = serializer.loads(token)
    # except BadData:
    #     return None
    # return data
    # return data

    # return data['openid']
    # 1.创建序列化器
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=60 * 60)
    # 2. 对数据进行处理
    token = s.dumps({
        'openid': openid
    })
    # 3.返回
    return token.decode()

def check_save_user_token(access_token):
    # serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    # try:
    #     data = serializer.loads(access_token)
    # except BadData:
    #     return None
    #
    # return data['openid']
    # 1. 创建序列化器
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=60 * 60)
    # 2. 对数据进行 loads操作
    try:
        data = s.loads(access_token)
        """
        data 就是当时设置的 字典
        {
            'openid':openid
        }
        """
    except BadSignature:
        return None
    # 3.返回 openid
    return data['openid']


class OAuthWeibo(object):
    """ 微博认证辅助工具类 """
    def __init__(self,client_id = None, client_secret = None, redirect_uri = None, state=None):
        self.client_id = client_id or settings.WEIBO_CLIENT_ID
        self.redirect_uri = redirect_uri or settings.WEIBO_REDIRECT_URI
        self.client_secret=client_secret or settings.WEIBO_CLIENT_SECRET
        self.state = state

    def get_weibo_url(self):
        """
        获取微博的验证页面链接
        :return:
        """
        data_dict = {
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'state':self.state
        }
        # print(data_dict)
        # 构造微博登录链接
        weibo_url = 'https://api.weibo.com/oauth2/authorize?' + urlencode(data_dict)
        return weibo_url

    def get_access_token(self, code):
        """
        获取微博的accesstoken值
        https://api.weibo.com/oauth2/access_token
        ?client_id=YOUR_CLIENT_ID
        &client_secret=YOUR_CLIENT_SECRET
        &grant_type=authorization_code
        &redirect_uri=YOUR_REGISTERED_REDIRECT_URI
        &code=CODE

        :param code:
        :return:
        """
        # 构造参数
        data_dict = {
            "client_id":self.client_id,
            "client_secret":self.client_secret,
            "grant_type":"authorization_code",
            "redirect_uri":self.redirect_uri,
            "code":code
        }

        # 发送请求
        url = "https://api.weibo.com/oauth2/access_token"
        try:
            response = requests.post(url=url,data=data_dict)

            # 提取数据
            # {
            #     "access_token": "<PASSWORD>",
            #     "remind_in": 3600,
            #     "expires_in": 3600
            # }
            data = response.text
            data_dict = json.loads(data)
            access_token = data_dict["access_token"]
            print(data_dict)
        except:
            raise Exception('微博请求失败')
        return access_token

from urllib.parse import urlencode

import requests
from itsdangerous import BadData
from itsdangerous import BadSignature
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from rest_framework.utils import json

from mall import settings


def generate_save_token(openid):
    # serializer = Serializer(settings.SECRET_KEY, 300)
    # data = {'openid': openid}
    # token = serializer.dumps(data)
    # token = token.decode()
    # try:
    #     data = serializer.loads(token)
    # except BadData:
    #     return None
    # return data
    # return data

    # return data['openid']
    # 1.创建序列化器
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=60 * 60)
    # 2. 对数据进行处理
    token = s.dumps({
        'openid': openid
    })
    # 3.返回
    return token.decode()

def check_save_user_token(access_token):
    # serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    # try:
    #     data = serializer.loads(access_token)
    # except BadData:
    #     return None
    #
    # return data['openid']
    # 1. 创建序列化器
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=60 * 60)
    # 2. 对数据进行 loads操作
    try:
        data = s.loads(access_token)
        """
        data 就是当时设置的 字典
        {
            'openid':openid
        }
        """
    except BadSignature:
        return None
    # 3.返回 openid
    return data['openid']


class OAuthWeibo(object):
    """ 微博认证辅助工具类 """
    def __init__(self,client_id = None, client_secret = None, redirect_uri = None, state=None):
        self.client_id = client_id or settings.WEIBO_CLIENT_ID
        self.redirect_uri = redirect_uri or settings.WEIBO_REDIRECT_URI
        self.client_secret=client_secret or settings.WEIBO_CLIENT_SECRET
        self.state = state

    def get_weibo_url(self):
        """
        获取微博的验证页面链接
        :return:
        """
        data_dict = {
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'state':self.state
        }
        # print(data_dict)
        # 构造微博登录链接
        weibo_url = 'https://api.weibo.com/oauth2/authorize?' + urlencode(data_dict)
        return weibo_url

    def get_access_token(self, code):
        """
        获取微博的accesstoken值
        https://api.weibo.com/oauth2/access_token
        ?client_id=YOUR_CLIENT_ID
        &client_secret=YOUR_CLIENT_SECRET
        &grant_type=authorization_code
        &redirect_uri=YOUR_REGISTERED_REDIRECT_URI
        &code=CODE

        :param code:
        :return:
        """
        # 构造参数
        data_dict = {
            "client_id":self.client_id,
            "client_secret":self.client_secret,
            "grant_type":"authorization_code",
            "redirect_uri":self.redirect_uri,
            "code":code
        }

        # 发送请求
        url = "https://api.weibo.com/oauth2/access_token"
        try:
            response = requests.post(url=url,data=data_dict)

            # 提取数据
            # {
            #     "access_token": "<PASSWORD>",
            #     "remind_in": 3600,
            #     "expires_in": 3600
            # }
            data = response.text
            data_dict = json.loads(data)
            access_token = data_dict["access_token"]
            print(data_dict)
        except:
            raise Exception('微博请求失败')
        return access_token
# serializer = Serializer(settings.SECRET_KEY, 300) # data = {'openid': openid} # token = serializer.dumps(data) # token = token.decode() # try: #     data = serializer.loads(token) # except BadData: #     return None # return data # return data # return data['openid'] # 1.创建序列化器 # 2. 对数据进行处理 # 3.返回 # serializer = Serializer(settings.SECRET_KEY, expires_in=3600) # try: #     data = serializer.loads(access_token) # except BadData: #     return None # # return data['openid'] # 1. 创建序列化器 # 2. 对数据进行 loads操作 data 就是当时设置的 字典         {             'openid':openid         } # 3.返回 openid 微博认证辅助工具类 获取微博的验证页面链接         :return: # print(data_dict) # 构造微博登录链接 获取微博的accesstoken值         https://api.weibo.com/oauth2/access_token         ?client_id=YOUR_CLIENT_ID         &client_secret=YOUR_CLIENT_SECRET         &grant_type=authorization_code         &redirect_uri=YOUR_REGISTERED_REDIRECT_URI         &code=CODE          :param code:         :return: # 构造参数 # 发送请求 # 提取数据 # { #     "access_token": "<PASSWORD>", #     "remind_in": 3600, #     "expires_in": 3600 # }