<!--#include file="config.asp"-->
<%
''' EYCMS QQ登录处理
''' ==================================================================

	sub callback()
		dim states:states=eycms.enhtml(eycms.fget("state",0))
		dim code:code=eycms.enhtml(eycms.fget("code",0))
		dim t0:t0=eycms.enhtml(eycms.loadsession("qq_state"))
		if t0="" then
			eycms.echo "会话过期，无法登录"
			exit sub
		end if
		if eycms.strlen(states)=0 or eycms.strlen(code)=0 then
			eycms.echo "非法参数传递，无法登录"
			exit sub
		end if
		if states<>t0 then
			eycms.echo "登录验证失败，无法登录"
			exit sub
		else
			dim url:url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"
				url=url&"&client_id="&qq_appid
				url=url&"&client_secret="&qq_appkey
				url=url&"&redirect_uri="&qq_callback
				url=url&"&code="&code
			dim str:str=eycms.gethttp(url,"")
			if instr(str,"callback")>0 then
				str=replace(str,"callback( ","")
				str=replace(str," )","")
				dim json
				set json=toobject(str)
					eycms.echo "错误编号："&eycms.enhtml(json.error)&"<br>"
					eycms.echo "错误原因："&eycms.enhtml(json.error_description)&"<br>"
				set json=nothing
				exit sub
			end if
			if left(str,13)="access_token=" then
				dim access_token:access_token=mid(str,14,instr(str,"&")-14)
				eycms.setsession "access_token",eycms.enhtml(access_token)
			else
				eycms.echo "未知错误"
				exit sub
			end if
		end if
	end sub
	
	sub get_openid()
		dim url:url="https://graph.qq.com/oauth2.0/me?access_token="&eycms.loadsession("access_token")
		dim str:str=eycms.gethttp(url,"")
		dim gourl:gourl=eycms.loadsession("api_backurl")
		if instr(str,"callback")>0 then
			str=replace(str,"callback( ","")
			str=replace(str," )","")
			dim json
			set json=toobject(str)
			dim openid:openid=eycms.enhtml(json.openid)
				eycms.setsession "openid",openid
			set json=nothing
			'查询openid，如果存在则直接获取会员信息，否则跳转到绑定页面
			dim data:data=eycms.db.dbload(1,"n.userid,u.logintimes","ey_user_bind n left join ey_user u on n.userid=u.id","n.openid='"&openid&"' and n.opentype='qq'","")
			if ubound(data)<0 then
				eycms.setsession "api_backurl",""
				eycms.go "bind.asp?api_backurl="&gourl
				exit sub
			else
				eycms.db.dbupdate "ey_user","id="&data(0,0)&"",array(array("logintimes",data(1,0)+1,0,0))
				eycms.resetuserinfo("u.id="&data(0,0)&"")
				'清空API数据
				eycms.setsession "qq_state",""
				eycms.setsession "access_token",""
				eycms.setsession "openid",""
				eycms.setsession "api_backurl",""
				if eycms.strlen(gourl)=0 then gourl=webroot
				eycms.go gourl
			end if
		else
			eycms.echo "无法获取数据，登录失败"
			exit sub
		end if
	end sub

	callback()
	get_openid()
%>
