wxapp_access_token.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # -*- coding: utf-8 -*-
  2. import time
  3. from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
  4. from odoo import models, fields, api, exceptions
  5. class AccessToken(models.TransientModel):
  6. _name = 'wxapp.access_token'
  7. _description = u'assess token'
  8. # allow session to survive for 30min in case user is slow
  9. _transient_max_hours = 24
  10. token = fields.Char('token', index=True)
  11. session_key = fields.Char('session_key', required=True)
  12. open_id = fields.Char('open_id', required=True)
  13. @api.model
  14. def create(self, vals):
  15. sub_domain = vals.pop('sub_domain', '_error_')
  16. record = super(AccessToken, self).create(vals)
  17. record.write({'token': record.generate_token(sub_domain)})
  18. return record
  19. def generate_token(self, sub_domain):
  20. config = self.env['wxapp.config']
  21. secret_key = config.get_config('secret', sub_domain)
  22. app_id = config.get_config('app_id', sub_domain)
  23. if not secret_key or not app_id:
  24. raise exceptions.ValidationError('未设置 secret_key 或 appId')
  25. s = Serializer(secret_key=secret_key, salt=app_id, expires_in=AccessToken._transient_max_hours * 3600)
  26. timestamp = time.time()
  27. return s.dumps({'session_key': self.session_key, 'open_id': self.open_id, 'iat': timestamp})