1 接收微信 服務器get 請求發過來的參數
@csrf_exempt
def weixin_main(request):
# get 請求是驗證
if request.method == "GET":
# 接收微信服務器get請求發過來的參數
signature = request.GET.get('signature', None)
timestamp = request.GET.get('timestamp', None)
nonce = request.GET.get('nonce', None)
echostr = request.GET.get('echostr', None)
# 服務器配置中的token
token = 'gongchang'
# 把參數放到list中排序後合成一個字符串,再用sha1加密得到新的字符串與微信發來的signature對比,如果相同就返回echostr給服務器,校驗通過
hashlist = [token, timestamp, nonce]
hashlist.sort()
hashstr = ''.join([s for s in hashlist])
hashstr = hashlib.sha1(hashstr).hexdigest()
if hashstr == signature:
return HttpResponse(echostr)
else:
return HttpResponse("field")
elif request.method == "POST":
webData = request.body
xmlData = ET.fromstring(webData)
msg_type = xmlData.find('MsgType').text
to_user_name = xmlData.find('ToUserName').text
from_user_name = xmlData.find('FromUserName').text
creat_time = xmlData.find('CreateTime').text
info = Config.objects.get(config_name='shovel_free')
data = info.config_value
data = json.loads(data)
wx_num = data.get('wx_num')
now = time.strftime('%Y%m%d')
if msg_type == 'event':
event = xmlData.find('Event').text
# 關注事件
if event == 'subscribe':
eventkey = xmlData.find('EventKey').text # qrscene_14 爲關注數據形式
# 獲取access_token
# 微信公共號返回二種信息流 1未關注 qrscene_6 2 已關注 不發送 qrscene_data_123
try:
eventkey = int(eventkey[8:].encode("utf-8"))
except:
try:
eventkey = str(eventkey[13:].encode("utf-8"))
reply_info = "提取碼爲:%s" % eventkey
replyMsg = TextMsg(from_user_name, to_user_name, reply_info)
return HttpResponse(replyMsg.send())
except:
# 用戶關注時,自動推送信息
content = "終於等到你~感謝關注! ❤\n我們爲你提供海量關鍵詞的快速挖掘與智能導出服務,同時還可對關鍵詞進行統一管理," \
"便於使用。\n在這裏,你可以享受:\n挖詞進度即時通知,挖詞結果一鍵查詢,還可免費領鏟子哦!\n" \
"第一時間告訴你最新的優惠福利,做你最貼心的挖詞小助手。\n回覆【免費領鏟子】,即可每天免費領取%s把鏟子," \
"快來試一下吧" % wx_num
replyMsg = TextMsg(from_user_name, to_user_name, content)
return HttpResponse(replyMsg.send())
# 統一獲取微信公共號
access_token = get_access_token()
if access_token:
# 獲取微信用戶的基本信息
user_info_url = u'https://api.weixin.qq.com/cgi-bin/user/info'
params = {
'access_token': access_token,
'openid': from_user_name,
'lang': settings.WEIXIN_APPSECRET_TT,
}
try:
userinfo = requests.get(user_info_url, params=params).json()
nickname = userinfo['nickname']
try:
user_wx_info = UserWxInfo.objects.get(openid=from_user_name, uid=eventkey)
user_wx_info.wx_username = nickname
user_wx_info.focus_state = 1
user_wx_info.save()
except:
# 兩種情況 1.微信公共號未被使用 2. 重新綁定新用戶,老用戶解除綁定
try:
user_wx_info = UserWxInfo.objects.get(openid=from_user_name)
user_wx_info.openid = ''
user_wx_info.focus_state = 0
user_wx_info.save()
except:
pass
try:
user_wx_info = UserWxInfo.objects.get(uid=int(eventkey))
user_wx_info.openid = from_user_name
user_wx_info.wx_username = nickname
user_wx_info.focus_state = 1
user_wx_info.save()
except:
user_com = UserWxInfo(uid=eventkey, openid=from_user_name, wx_username=nickname,
focus_state=1, focus_state_done=1)
user_com.save()
# 用戶賬戶表鏟子變動更新
try:
_ = FinanceAccount.objects.get(uid=eventkey)
except Exception as e:
pass
else:
_.shovel = int(5) + _.shovel # 鏟子數量保存
_.save()
shovel_obj = FinanceAccount.objects.get(uid=eventkey)
# 產自明細表
data = FinanceShovelLog(uid=eventkey, incr_num=5, reason='獎勵', type=2,
reason_meta='首次關注微信公衆號', shovel=shovel_obj.shovel)
data.save()
except:
# 微信公共號獲取出現錯誤不做任何處理
# raise FieldError("openid", "獲取openid錯誤")
pass
# 用戶關注時,自動推送信息
content = "終於等到你~感謝關注! ❤\n我們爲你提供海量關鍵詞的快速挖掘與智能導出服務,同時還可對關鍵詞進行統一管理," \
"便於使用。\n在這裏,你可以享受:\n挖詞進度即時通知,挖詞結果一鍵查詢,還可免費領鏟子哦!\n" \
"第一時間告訴你最新的優惠福利,做你最貼心的挖詞小助手。\n回覆【免費領鏟子】,即可每天免費領取%s把鏟子," \
"快來試一下吧" % wx_num
replyMsg = TextMsg(from_user_name, to_user_name, content)
return HttpResponse(replyMsg.send())