tool.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.customer.models import Customer, CustomerWechat
  9. User = get_user_model()
  10. class WechatHandel(object):
  11. @staticmethod
  12. def login(code, appid, activity_id):
  13. WeChat.checkAppid(appid)
  14. if activity_id:
  15. activity = Activity.objects.filter(id=activity_id, enabled=True, delete=False).first()
  16. if not activity:
  17. activity = Activity.objects.filter().order_by('-create_time').first()
  18. else:
  19. activity = Activity.objects.filter().order_by('-create_time').first()
  20. res = WeChat.code2Session(appid, settings.SECRET, code)
  21. instance = CustomerWechat.objects.filter(openid=res['openid'], branch=activity.branch).first()
  22. if not instance:
  23. instance = CustomerWechat.objects.create(
  24. branch=activity.branch,
  25. openid=res['openid'],
  26. session_key=res['session_key']
  27. )
  28. else:
  29. instance.session_key = res['session_key']
  30. instance.save()
  31. return instance, activity.id
  32. @staticmethod
  33. def bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id):
  34. WeChat.checkAppid(appid)
  35. activity = Activity.objects.filter(id=activity_id, enabled=True, delete=False).first()
  36. if not activity:
  37. raise CustomError(u'未找到相应的活动')
  38. customer_wechat = CustomerWechat.objects.filter(openid=openid, branch=activity.branch).first()
  39. if not customer_wechat:
  40. raise CustomError(u'未找到相应的微信客户!')
  41. pc = WXBizDataCrypt(settings.APPID, customer_wechat.session_key)
  42. phon_data = pc.decrypt(phoneEncryptedData, phoneIv)
  43. tel = phon_data['purePhoneNumber']
  44. if customer_wechat.customer:
  45. if customer_wechat.customer.user.username != tel:
  46. raise CustomError(u'微信绑定的手机号与系统记录的不符!')
  47. else:
  48. return customer_wechat.customer
  49. user = User.objects.filter(username=tel).first()
  50. if not user:
  51. user = User.objects.create_user(User.CUSTOMER, tel, password=tel, **{'name': tel, 'tel': tel})
  52. customer = Customer.objects.filter(branch=customer_wechat.branch, user=user).first()
  53. if not customer:
  54. customer = Customer.objects.create(branch=customer_wechat.branch, user=user, name=tel, tel=tel)
  55. customer_wechat.customer = customer
  56. customer_wechat.save()
  57. return customer