1. 程式人生 > >html5+jquery獲取微信openid

html5+jquery獲取微信openid

     最近在修改一個移動商城,由於wap端是HTML5的,還大量使用了art模板技術,一開始修改很不適應,而且實現HTML5取openid一直沒能實現很好的實現,經過對獲取原理的理解和學習,終於還是實現了HTML獲取微信openid,而且改動不大,閒話少說,直接上乾貨:

一、寫個js,用於取accesscode,並直接通過openid讀取使用者表中的註冊資訊

$(function () {
    var wxopenid=getcookie('wxopenid');
    var key=getcookie('key');
    if (key==''){
        var access_code=GetQueryString('code');
        if (wxopenid==""){
            if (access_code==null)
            {   
                var fromurl=location.href;
                var url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=填你自已的appid喲&redirect_uri='+encodeURIComponent(fromurl)+'&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
                location.href=url;
            }
            else
            {   
                $.ajax({
                    type:'get',
                    url:ApiUrl+'/index.php?act=payment&op=getopenid', 
                    async:false,
                    cache:false,
                    data:{code:access_code},
                    dataType:'json',
                    success:function(result){                 
                            if (result!=null && result.hasOwnProperty('openid') && result.openid!=""){
                               addcookie('wxopenid',result.openid,360000);                           
                               getlogininfo(result.openid);
                            } 
                            else
                            {
                              alert('微信身份識別失敗 \n '+result);
                              location.href=fromurl;
                            }
                        }
                    });    
            }
        }else{
           if (key=='' && wxopenid!='')
               getlogininfo(wxopenid);  
        }

        function getlogininfo(wxopenid){       
            $.ajax({
               type:'get',
               url: ApiUrl + '/index.php?act=login&op=autologininfo',
               data: { wxopenid:wxopenid},
               dataType:'json',
               async:false,
               cache:false,               
               success: function (result) {                   
                       if (result.return_code=='OK'){
                           addcookie('key',result.memberinfo.key);
                           addcookie('username',result.memberinfo.username);
                       }else{
                           alert(result.return_msg);
                           location.href=WapSiteUrl+'/tmpl/member/login.html';
                       }
               }
            });
        }
    }
});
第二步:在html頁的head中載入js檔案
<head>
<meta charset="UTF-8">
<title>麥斯卡商城</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" type="text/css" href="css/member.css">
<script type="text/javascript" src="js/config.js"></script>
<script type="text/javascript" src="js/zepto.min.js"></script>
<script type="text/javascript" src="js/template.js"></script>
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript" src="js/getwxopenid_index.js"></script>
</head>
第三步:實現openid的後臺方法,這個方法不詳列了,官方有示例
 /**
     * 獲取openid
     * @return type
     */
    public function getopenidOp(){
        $jsApi=new JsApi_pub();
        $code = $_GET['code'];
        $jsApi->setCode($code);
        echo $jsApi->getOpenId();       
    }
function getOpenid()
<span style="white-space:pre">	</span>{
            $url = $this->createOauthUrlForOpenid();
            return $this->httpGet($url);
<span style="white-space:pre">	</span>}
/**
<span style="white-space:pre">	</span> * <span style="white-space:pre">	</span>作用:生成可以獲得openid的url
<span style="white-space:pre">	</span> */
<span style="white-space:pre">	</span>function createOauthUrlForOpenid()
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>$urlObj["appid"] = WxPayConf_pub::APPID;
<span style="white-space:pre">		</span>$urlObj["secret"] = WxPayConf_pub::APPSECRET;
<span style="white-space:pre">		</span>$urlObj["code"] = $this->code;
<span style="white-space:pre">		</span>$urlObj["grant_type"] = "authorization_code";
<span style="white-space:pre">		</span>$bizString = $this->formatBizQueryParaMap($urlObj, false);
                //api.weixin.qq.com=101.226.90.58
<span style="white-space:pre">		</span>return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
<span style="white-space:pre">	</span>}
function addcookie(name,value,expireHours){
	var cookieString=name+"="+escape(value)+"; path=/";
	//判斷是否設定過期時間
	if(expireHours>0){
		var date=new Date();
		date.setTime(date.getTime+expireHours*3600*1000);
		cookieString=cookieString+"; expire="+date.toGMTString();
	}
	document.cookie=cookieString;
}

function getcookie(name){
	var strcookie=document.cookie;
	var arrcookie=strcookie.split("; ");
	for(var i=0;i<arrcookie.length;i++){
	var arr=arrcookie[i].split("=");
	if(arr[0]==name)return decodeURIComponent(arr[1]); //增加對特殊字元的解析
	}
	return "";
}

function delCookie(name){//刪除cookie
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval=getcookie(name);
	if(cval!=null) document.cookie= name + "="+cval+"; path=/;expires="+exp.toGMTString();
}


另外,js檔案中的變數,儘量不要用全域性的,當多個js載入時,變數可能衝突,造成一些不可預則的問題;

這樣就實現了在html5頁面直接取accesscode,再通過ajax方法在後臺取openid;

 如果要看效果,可以微信掃碼進入商城(本來只想放個二維碼,又怕有人以為是什麼下載連結)