tool.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #coding=utf-8
  2. from django.conf import settings
  3. from django.contrib.auth import get_user_model
  4. from util.wx.wechat import WeChat
  5. from util.wx.WXBizDataCrypt import WXBizDataCrypt
  6. from apps.exceptions import CustomError
  7. from apps.activity.models import Activity
  8. from apps.WechatApplet.models import WechatApplet
  9. from apps.customer.models import Customer, CustomerWechat
  10. User = get_user_model()
  11. class WechatHandel(object):
  12. @staticmethod
  13. def login(code, appid, activity_id):
  14. app = WechatApplet.getByAppid(appid)
  15. # 还有过期的活动还显示不?
  16. if activity_id:
  17. activity = Activity.objects.filter(id=activity_id, enabled=True, delete=False).first()
  18. if not activity:
  19. activity = Activity.objects.filter().order_by('-create_time').first()
  20. else:
  21. activity = Activity.objects.filter().order_by('-create_time').first()
  22. res = WeChat.code2Session(appid, app.secret, code)
  23. instance = CustomerWechat.objects.filter(openid=res['openid'], branch=activity.branch).first()
  24. if not instance:
  25. instance = CustomerWechat.objects.create(
  26. branch=activity.branch,
  27. openid=res['openid'],
  28. session_key=res['session_key']
  29. )
  30. else:
  31. instance.session_key = res['session_key']
  32. instance.save()
  33. return instance, activity.id
  34. @staticmethod
  35. def bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id):
  36. app = WechatApplet.getByAppid(appid)
  37. activity = Activity.objects.filter(id=activity_id, enabled=True, delete=False).first()
  38. if not activity:
  39. raise CustomError(u'未找到相应的活动')
  40. customer_wechat = CustomerWechat.objects.filter(openid=openid, branch=activity.branch).first()
  41. if not customer_wechat:
  42. raise CustomError(u'未找到相应的微信客户!')
  43. pc = WXBizDataCrypt(appid, customer_wechat.session_key)
  44. phon_data = pc.decrypt(phoneEncryptedData, phoneIv)
  45. tel = phon_data['purePhoneNumber']
  46. if customer_wechat.customer:
  47. if customer_wechat.customer.user.username != tel:
  48. raise CustomError(u'微信绑定的手机号与系统记录的不符!')
  49. else:
  50. return customer_wechat.customer
  51. user = User.objects.filter(username=tel).first()
  52. if not user:
  53. user = User.objects.create_user(User.CUSTOMER, tel, password=tel, **{'name': tel, 'tel': tel})
  54. customer = Customer.objects.filter(branch=customer_wechat.branch, user=user).first()
  55. if not customer:
  56. customer = Customer.objects.create(branch=customer_wechat.branch, user=user, name=tel, tel=tel)
  57. customer_wechat.customer = customer
  58. customer_wechat.save()
  59. return customer