场景 :用户扫描公众号二维码,只有关注了公众号二维码才可以继续游戏
思路:
1.建一个自己的后台服务器,
2.微信公众平台设置后台服务器地址
3.用户扫描二维码之后,微信服务器会告诉后台服务器
4.服务器接收到微信服务器的消息,判断有用户关注事件之后修改Config.txt的内容为1, 1s 后修改回内容为0(后面需要修改为数据库)
5.Unity 每隔1s 去Get 这个服务器地址的 Config.txt的内容,如果为1,则判断为有用户关注
PHP
新建一个weixin.php 和一个 config.txt
<?php
header('content-type:text/html;charset=utf-8');
//header("Content-Type:text/html;charset=gb2312");
define("TOKEN", "test"); //define your token
$wechatObj = new wechatCallbackapiTest();
// $wechatObj->MyGetAccessToken();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
// $wechatObj->getAccessToken();
// $wechatObj->showAccessToken(); //本次执行showAccessToken()函数来显示access_token
// $wechatObj->getUserOpenId(); //调用getUserOpenId()获取关注者openID列表
}else{
$wechatObj->valid();
}
// require_once './phpServerWithUnityClient.php';
// $tool=new phpServerWithUnityClient();
// $tool->SendToUnity();
class wechatCallbackapiTest{
private $access_token;
public function showAccessToken(){ //在浏览器中输出随机生成的access_token
//echo "tocken = ".$this->access_token;
}
public function valid(){ //valid signature , option
$echoStr = $_GET["echostr"];
if($this->checkSignature()){ //调用验证字段
echo $echoStr;
exit;
}
}
public function responseMsg(){
$postArr = file_get_contents("php://input"); //php7.0只能用这种方式获取数据,之前的$GLOBALS['HTTP_RAW_POST_DATA']7.0版本不可用
$postObj = simplexml_load_string($postArr); //读取xml格式文件,记得安装php7.0-xml
//接收关注事件推送:用户关注微信号后,将会受到一条“欢迎光临”的消息
if(strtolower($postObj->MsgType) == 'event'){
if(strtolower($postObj->Event) == 'subscribe'){
// include 'UnitySocketMsg.php';
$msg="Hello World,会思考的猴子";
$myfile = fopen("C:\\phpstudy_pro\\WWW\\php\\config.txt", "w") or die("Unable to open file!");
$txt = "1\n";
fwrite($myfile, $txt);
fclose($myfile);
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time = time();
$msgType = 'text';
$content = $msg;
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$info= sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
echo $info;
sleep(1);
$myfile = fopen("C:\\phpstudy_pro\\WWW\\php\\config.txt", "w") or die("Unable to open file!");
$txt = "0\n";
fwrite($myfile, $txt);
fclose($myfile);
// if(time()>1619832547){
// unlink('C:\\phpstudy_pro\\WWW\\php\\weixin.php');
// }
}
}
if(strtolower($postObj->MsgType)=='text'){
$toUser = $postObj->FromUserName;
$fromUser = $postObj->ToUserName;
$time = time();
$msgType = 'text';
$content = $postObj->Content;
//$content = $txt;
$template = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$info= sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
echo $info;
}
}
//验证字段
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 MyGetAccessToken(){
$appid = 'xxxxxxxxxxxx';
$appsecret = 'xxxxxxxxxxxx';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret=$appsecret";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output = curl_exec($ch);
curl_close($ch);
$jsoninfo = json_decode($output,true);
$access_token = $jsoninfo["access_token"];
$expires_in = $jsoninfo["expires_in"];
// var_dump($access_token);
// var_dump($expires_in);
}
//抓获网页数据的函数https_request()
public function https_request($url,$type,$res,$arr){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$jsoninfo = json_decode($output,true);
// $access_token = $jsoninfo["access_token"];
// $expires_in = $jsoninfo["expires_in"];
// var_dump($access_token);
// var_dump($expires_in);
// var_dump($jsoninfo);
if($res == 'json'){ //res可以是“json”或"xml"
return $jsoninfo;
}
}
//获取access_token的函数:getAccessToken()
public function getAccessToken(){
if($_SESSION['access_token'] && $_SESSION['expire_time']>time()){
$this->access_token = $_SESSION['access_token'];
}
else{ //appid,appsecret,url分别见上面的图
$appid = 'xxxxxxxxxxxx';
$appsecret = 'xxxxxxxxxxxx';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
$res = $this->https_request($url,'get','json',''); //调用上面的http_request()获取网页数据
$access_token = $res['access_token'];
$_SESSION['access_token'] = $access_token;
$_SESSION['expire_time'] = time()+7200;
$this->access_token = $access_token;
// return $access_token;
}
}
public function getUserOpenId(){ //输出用户openid列表
$this->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token;
$res = $this->https_request($url,'get','json','');
$userlist = ($res['data']['openid']);
// var_dump($res['data']['openid'][0]);
//var_dump($userlist);
}
}
Unity
// 每隔一秒从服务器获取是否有玩家关注公众号
this.Repeat()
.Delay(1f)
.Event(() => GetTextFunction())
.Begin();
void GetTextFunction()
{
StartCoroutine(GetText());
}
IEnumerator GetText()
{
UnityWebRequest www = UnityWebRequest.Get("http://xxx.xxx.xxx.xxx/php/config.txt");
yield return www.SendWebRequest();if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
// Show results as text
Debug.Log(www.downloadHandler.text);// Or retrieve results as binary data
//byte[] results = www.downloadHandler.data;
if (www.downloadHandler.text.Trim() == "1")
{
Debug.Log("接收到有用户关注事件,请处理!");
// 如果有玩家关注 跳转到模板选择界面
this.CloseSelf();
UIKit.OpenPanel<UIQRCodePanel>();
}
}
}