什麼是微信openid?javascript
某個微信帳號,針對某個公衆號,的惟一標示,並且不變;針對不一樣的公衆號會有不一樣的openid;php
openid有什麼用?html
用來獲取用戶基本信息,頭像、暱稱、性別、地區等java
*暱稱帶ios圖標的須要urlencode轉碼保存入數據庫,轉碼出來才能顯示,否則會出現字符不能識別,暱稱空白亂碼ios
****************************************************************************************************************************************數據庫
1、關於微信開發json
涉及到微信開發的,基本都是獲取openid來肯定用戶的惟一性(用戶的惟一id);剩下的只是看需求處理;api
例如,如何微信登錄?數據庫保存openid,經過獲取openid和數據庫的openid作匹配,也能夠寫進cookie,不須要每次都經過微信獲取openid;安全
那麼如何獲取openid?服務器
首先須要AppID(應用ID)和AppSecret(應用密鑰),在微信後臺能夠獲取,由於全部調用微信端的方法都須要用到
AppID(應用ID) xxxxxxxxxxxxxxxxxxx
AppSecret(應用密鑰) xxxxxxxxxxxxxxxxxxxxxxxxxx
code列如:
define("APPID", "xxxxxxxxxxxxxxxxxxx");
define("SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxx");
// 不須要受權按鈕,默認受權
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlencode("http://www.xxxxxxxx.com/?app=appxxx&act=bx_redirect_pre")."&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect";
// 若是要獲取用戶的詳細信息(暱稱、頭像、地區等) (需受權按鈕,scope設置爲snsapi_userinfo)
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlencode("http://www.xxxxxxxx.com/?app=appxxx&act=bx_redirect_pre")."&response_type=code&scope=snsapi_userinfo&state=STATEconnect_redirect=1#wechat_redirect"; header("Location: ".$url);
//經過code換取網頁受權,獲取到網頁受權access_token的同時,也獲取到了openid:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
//微信回調方法
function bx_redirect_pre() { $code = $_GET['code']; // 1. 用get方法獲得回調的code if ( $code ) { // 2. 根據code得到,用戶的openid $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".SECRET."&code=".$code."&grant_type=authorization_code"; $json = file_get_contents($url); $array = json_decode($json, true); $weixin_openid = $array['openid']; //這裏獲取微信openid $access_token = $array['access_token']; //網頁受權接口調用憑證,注意:此access_token與基礎支持的access_token不一樣 // openid已獲取,隨便折騰………………………… // 若是要獲取用戶的詳細信息(暱稱、頭像、地區等) (需受權按鈕,scope設置爲snsapi_userinfo) // http:GET(請使用https協議) // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN if ($weixin_openid) { // 獲取用戶信息 $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$weixin_openid."&lang=zh_CN"; $user_info_json = json_decode(file_get_contents($user_info_url), true); $headimgurl = $user_info_json['headimgurl']; $unionid = $user_info_json['unionid']; $nickname = $user_info_json['nickname']; $nickname = urlencode($nickname); $sex = $user_info_json['sex']; $language = $user_info_json['language']; $city = $user_info_json['city']; $province = $user_info_json['province']; $privilege = ""; } } }
****************************************************************************************************************************************
2、微信公衆平臺消息接管操做
http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html
1.首先配置微信接口,提供url連接,驗證網站是否能夠處理微信消息,在微信平臺填寫url進行驗證
2.驗證經過後就能夠屏蔽這個方法,寫入本身的程序替代驗證方法,用於處理用戶輸入信息(能夠是語音信息)
public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; // //extract post data if (!empty($postStr)) { $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; if ( trim($postObj->Recognition) ) { //語音 $keyword = trim($postObj->Recognition); } else { $keyword = trim($postObj->Content); } $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; $msgType = "text"; //關注消息推送、或其餘事件自定義 // $event = $postObj->Event; if ($event=="subscribe") { $contentStr = "這些推送剛關注的消息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; exit(); } $weixin_openid = $fromUsername; if( ! empty( $keyword ) ) { $contentStr = "推送的消息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } } else { exit; } } //微信接口數據處理 public function jiekou() { //1.判斷是否已經存入紅包 //$this->valid(); $this->responseMsg(); }
問題:當服務器卡,或其餘緣由,會出現微信重複推送消息的問題
解決方法:
根據 MsgID 或 openid+createtime 來排除重複的推送請求,重複的推送 MsgID 或 openid+createtime 會相同
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $createTime = $postObj->CreateTime; $msgId = $postObj->MsgId;
****************************************************************************************************************************************
3、微信分享html頁面
<?php require_once ("jssdk.php"); $jssdk = new JSSDK("wx059077272f261fb8", "c8902a348825a64627ffa7a05be036c9"); $signPackage = $jssdk->GetSignPackage(); ?>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script> /* * 注意: * 1. 全部的JS接口只能在公衆號綁定的域名下調用,公衆號開發者須要先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」。 * 2. 若是發如今 Android 不能分享自定義內容,請到官網下載最新的包覆蓋安裝,Android 自定義分享接口需升級至 6.0.2.58 版本及以上。 * 3. 常見問題及完整 JS-SDK 文檔地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html * * 開發中遇到問題詳見文檔「附錄5-常見錯誤及解決辦法」解決,如仍未能解決可經過如下渠道反饋: * 郵箱地址:weixin-open@qq.com * 郵件主題:【微信JS-SDK反饋】具體問題 * 郵件內容說明:用簡明的語言描述問題所在,並交代清楚遇到該問題的場景,可附上截屏圖片,微信團隊會盡快處理你的反饋。 */ wx.config({ debug: false, appId: '{$signPackage["appId"]}', timestamp: {$signPackage["timestamp"]}, nonceStr: '{$signPackage["nonceStr"]}', signature: '{$signPackage["signature"]}', jsApiList: [ // 全部要調用的 API 都要加到這個列表中 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage' ] }); wx.ready(function () { //獲取「分享到朋友圈」 wx.onMenuShareTimeline({ title: '', // 分享標題 link: "", // 分享連接 imgUrl: "share.jpg", // 分享圖標 desc: '', // 分享描述 success: function () { //分享成功操做 }, cancel: function () { } }); //獲取「分享給朋友」 wx.onMenuShareAppMessage({ title: '', // 分享標題 link: "", // 分享連接 imgUrl: "share.jpg", // 分享圖標 desc: '', // 分享描述 success: function () { //分享成功操做 }, cancel: function () { } }); }); </script>
附錄文件jssdk.php
<?php class JSSDK { private $appId; private $appSecret; public function __construct($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } public function getSignPackage() { $jsapiTicket = $this->getJsApiTicket(); // 注意 URL 必定要動態獲取,不能 hardcode. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 這裏參數的順序要按照 key 值 ASCII 碼升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = array( "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPackage; } private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } private function getJsApiTicket() { // jsapi_ticket 應該全局存儲與更新,如下代碼以寫入到文件中作示例 $data = json_decode(file_get_contents("jsapi_ticket.json")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); // 若是是企業號用如下 URL 獲取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; $res = json_decode($this->httpGet($url)); $ticket = $res->ticket; if ($ticket) { $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen("jsapi_ticket.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $ticket = $data->jsapi_ticket; } return $ticket; } private function getAccessToken() { // access_token 應該全局存儲與更新,如下代碼以寫入到文件中作示例 $data = json_decode(file_get_contents("access_token.json")); if ($data->expire_time < time()) { // 若是是企業號用如下URL獲取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; $res = json_decode($this->httpGet($url)); $access_token = $res->access_token; if ($access_token) { $data->expire_time = time() + 7000; $data->access_token = $access_token; $fp = fopen("access_token.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $access_token = $data->access_token; } return $access_token; } private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } }