1. 程式人生 > >微信介面開發【php程式碼】

微信介面開發【php程式碼】

首先準備一個api.php檔案 這個檔案可以再微信開發平臺網站手冊裡面下載到

需要配置的是token

微信測試地址

https://mp.weixin.qq.com/debug/

<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "這裡寫你的token");
$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;
		}
	}
}

?>

然後配置你的伺服器 

輸入你設定的token 配置完成就可以進行開發了

首先需要的幾個引數

首先你會擁有一個appID和appsecret


然後你需要設定你的介面配置


這裡的url填寫你的最開始的那個檔案路徑

token可以隨便寫

token填到第一個檔案裡面去

然後儲存提交



提交之後便可以開始開發了 這裡附上最基本的獲取使用者頭像和使用者名稱的程式碼

新建一個檔案weixin.php


以下有三個引數需要填寫

appid填寫你的appid

appsecret填寫你的appsecret

redirect_uri填寫你的回撥域名

<meta charset="utf-8">
<?php
$appid='填寫你的appid';
$appsecret='填寫你的appsecret';
$redirect_uri='填寫你的域名地址/weixin.php';
$code=isset($_GET['code'])?$_GET['code']:'';

$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';

//獲取html程式碼
function getSslPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}


$user=getSslPage($url);
// $user=file_get_contents($url);
// echo $user;exit;
$access_token=explode('access_token":"',$user)[1];
$access_token=explode('"',$user)[0];//access_token
$openid=explode('"openid":"',$user)[1];
$openid=explode('"',$openid)[0];//openid
$refresh_token=explode('refresh_token":"',$user)[1];
$refresh_token=explode('"',$refresh_token)[0];//refresh_token

$aa=json($user);
echo $aa->access_token;


// $user_info_url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$use_url='https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$refresh_token;
$user_cont=getSslPage($use_url);
// echo $user_cont;exit;
$access_token=explode('access_token":"',$user_cont)[1];
$access_token=explode('"',$access_token)[0];//access_token
$openid=explode('"openid":"',$user_cont)[1];
$openid=explode('"',$openid)[0];//openid
$refresh_token=explode('refresh_token":"',$user_cont)[1];
$refresh_token=explode('"',$refresh_token)[0];//refresh_token

$user_info='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN;';
$text=getSslPage($user_info);
$arr=json_decode($text,true);
echo '網名:'.$arr['nickname'].'</br>';
echo '頭像:<img src='.$arr['headimgurl'].'></br>';
然後微信訪問這個weixin.php檔案就能看到你的頭像和網名了