上周的主要任務(wù)是做一個走微信公眾號的h5分享頁面,對于從來沒有接觸過微信程序的我,有點懵,還有h5頁面本來就不咋會寫,而且基本上沒人能給啥指導(dǎo),所以基本是自己一步步摸索。記錄一下這個苦逼的過程。
1: 既然說是要走微信公眾號,所以第一步,登錄微信公眾號后臺,不同功能的公眾號,所能調(diào)用的微信接口是不一樣的,可以登錄在接口權(quán)限的地方看一下自己具體有哪些權(quán)限。若是沒有公眾號,只是想自己練習(xí)如何做,在微信公眾平臺的文檔中有注冊測試帳號,附上鏈接:微信公眾平臺接口測試帳號申請
2: 拿到了id和secret,那如何進(jìn)行第一步的連接呢?首先url是外網(wǎng)地址,最好是將自己的程序放在服務(wù)器上,而且是默認(rèn)端口是80端口。若是沒有自己的服務(wù)器,可以將自己的服務(wù)器借助于花生殼、ngrok等工具將內(nèi)網(wǎng)的地址影射到外網(wǎng)(這里我用過ngrok,弄了挺長時間,但當(dāng)訪問的時候總是顯示不出來,后來就直接放棄了,部署在服務(wù)器上了)。
另外一個就是對于token,token是你自己定義的,剛開始并不知道自己定義是啥意思,其實這一步的驗證和后面的你要想是隔離開的,先進(jìn)行驗證。
驗證代碼:
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "weixinxijiji");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
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)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$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>";
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
private function checkSignature()
{
// you must define TOKEN by yourself
if (!defined("TOKEN")) {
throw new Exception('TOKEN is not defined!');
}
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>
3: 如何檢測我有沒有成功呢,需要借助微信web開發(fā)者工具。微信web開發(fā)者工具下載地址
使用方法:要在微信公眾號平臺中,開發(fā)->開發(fā)者工具->web開發(fā)者工具 上面綁定需要開發(fā)的微信帳號。這樣之后 就有權(quán)限進(jìn)行開發(fā)調(diào)試。
4: 如何進(jìn)行微信網(wǎng)頁開發(fā),參照微信網(wǎng)頁開發(fā)文檔,因為服務(wù)器端的是php環(huán)境,所以使用的是php寫的,主要分為,獲取access_token,獲取ticket,進(jìn)行校驗等。
<?php
$appid = "xxxx";
$secret = "xxxxxxxxxx";
$token = read('access_token', 3600);
$ticket = read('jsapi_ticket', 3600);
if (!$token || strlen($token) < 6) {
$res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
$res = json_decode($res, true);
$token = $res['access_token'];
write('access_token', $token, 3600);
}
if (!$ticket || strlen($ticket) < 6) {
$res = file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token.'&type=jsapi');
$res = json_decode($res, true);
$ticket = $res['ticket'];
write('jsapi_ticket', $ticket, 3600);
}
$timestamp = time();
$nonceStr = getRandChar(15);
//url為當(dāng)前頁面的url
$url = 'http://'.$_SERVER['HTTP_HOST'].'/act/icevelive2/third/';
$testurl = $_SERVER['QUERY_STRING'];
$first = strpos($testurl, '?');
$urltest = substr($testurl, 0, $first+0);
$url = $url.$urltest;
$str = "jsapi_ticket=".$ticket."&noncestr=".$nonceStr."×tamp=".$timestamp."&url=".$url;
$signature = sha1($str);
echo $timestamp.",".$nonceStr.",".$signature;
function read($file, $expires){
if(file_exists($file)) {
$time = filemtime($file);
if(time() - $time > $expires) {
return null;
}else {
return file_get_contents($file);
}
}
return null;
}
function write($file, $value){
@file_put_contents($file, $value);
}
function getRandChar($length){
$str = null;
$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($strPol)-1;
for($i=0;$i<$length;$i++){
$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max兩個數(shù)之間的一個隨機整數(shù)
}
return $str;
}
若是成功了,就可以進(jìn)行調(diào)用各種接口了。