用Python处理Facebook取消授权回调
我正在构建一个Django应用程序,它使用Facebook登录。我想知道用户何时删除我相应的Facebook应用程序,而Facebook则以。还有一些关于如何在中使用PHP解析请求的说明用Python处理Facebook取消授权回调,python,django,facebook-login,Python,Django,Facebook Login,我正在构建一个Django应用程序,它使用Facebook登录。我想知道用户何时删除我相应的Facebook应用程序,而Facebook则以。还有一些关于如何在中使用PHP解析请求的说明 然而,将其翻译成Python似乎不像我想象的那么容易,因为在解码发布的base64编码字符串时,我会遇到“填充错误”,这对我来说很奇怪。问题似乎是必须手动将某个填充添加到发布的数据中。以下是一个工作示例: class DeauthorizeView(View): def post(self, requ
然而,将其翻译成Python似乎不像我想象的那么容易,因为在解码发布的base64编码字符串时,我会遇到“填充错误”,这对我来说很奇怪。问题似乎是必须手动将某个填充添加到发布的数据中。以下是一个工作示例:
class DeauthorizeView(View):
def post(self, request, *args, **kwargs):
try:
signed_request = request.POST['signed_request']
encoded_sig, payload = signed_request.split('.')
except (ValueError, KeyError):
return HttpResponse(status=400, content='Invalid request')
try:
# Reference for request decoding: https://developers.facebook.com/docs/games/gamesonfacebook/login#parsingsr
# For some reason, the request needs to be padded in order to be decoded. See https://stackoverflow.com/a/6102526/2628463
decoded_payload = base64.urlsafe_b64decode(payload + "==").decode('utf-8')
decoded_payload = json.loads(decoded_payload)
if type(decoded_payload) is not dict or 'user_id' not in decoded_payload.keys():
return HttpResponse(status=400, content='Invalid payload data')
except (ValueError, json.JSONDecodeError):
return HttpResponse(status=400, content='Could not decode payload')
try:
secret = SocialApp.objects.get(id=1).secret
sig = base64.urlsafe_b64decode(encoded_sig + "==")
expected_sig = hmac.new(bytes(secret, 'utf-8'), bytes(payload, 'utf-8'), hashlib.sha256)
except:
return HttpResponse(status=400, content='Could not decode signature')
if not hmac.compare_digest(expected_sig.digest(), sig):
return HttpResponse(status=400, content='Invalid request')
user_id = decoded_payload['user_id']
try:
social_account = SocialAccount.objects.get(uid=user_id)
except SocialAccount.DoesNotExist:
return HttpResponse(status=200)
# Own custom logic here
return HttpResponse(status=200)