//get_ticket.php
$content = file_get_contents(“php://input”);
if($content){
file_put_contents(“./req/appid.php”, “\r\n” . $content .’**’. $_GET[‘timestamp’] . ‘**’ . $_GET[‘nonce’] . “**” . $_GET[‘msg_signature’]);
echo “success”;
}
// req/do.php
$content = file_get_contents(‘./req/appid.php’);
$arr = explode(‘**’,$content);
var_dump($arr);
//exit;
require ‘./req/weixin.php';
$encodingAesKey = ‘cmbjxccwtnylfyshlzdscmbjxccwtnylfyshlzds015′;
$token = ‘diemeng2015′;
$appId = “wxe1219eb7d5780e65″;
$timeStamp =$arr[1];
$nonce = $arr[2];
$msg_sign = $arr[3];
$encryptMsg = $arr[0];
$pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
$xml_tree = new DOMDocument();
$xml_tree -> loadXML($encryptMsg);
$array_e = $xml_tree -> getElementsByTagName(‘Encrypt’);
$encrypt = $array_e -> item(0) -> nodeValue;
$format = “ $from_xml = sprintf($format, $encrypt);
// 第三方收到公众号平台发送的消息
$msg = ”;
$errCode = $pc -> decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
if ($errCode == 0) {
//print(“解密后: ” . $msg . “\n”);
$xml = new DOMDocument();
$xml -> loadXML($msg);
$array_e = $xml -> getElementsByTagName(‘ComponentVerifyTicket’);
$component_verify_ticket = $array_e -> item(0) -> nodeValue;
/*$array_e = $xml -> getElementsByTagName(‘ComponentVerifyTicket’);
$component_verify_ticket = $array_e -> item(0) -> nodeValue;
$array_b = $xml->getElementsByTagName(‘InfoType’);
$infotype = $array_b->item(0)->nodeValue;
$array_c = $xml->getElementsByTagName(‘AuthorizerAppid’);
$authorizerappid = $array_c->item(0)->nodeValue;
$array_d = $xml->getElementsByTagName(‘event’);
$event = $array_d->item(0)->nodeValue;
$array_e = $xml->getElementsByTagName(‘FromUserName’);
$from_user = $array_e->item(0)->nodeValue;
*/
//echo “$authorizerappid”;
//记录解密的xml数据
//file_put_contents(“./get.php”, “\r\n”. $msg.”\r\n” .$infotype.”\r\n”.$authorizerappid, FILE_APPEND);
if($component_verify_ticket){
//file::write(‘./cache/component_verify_ticket.json’, json_encode(array(‘component_verify_ticket’ => $component_verify_ticket)));
//db::update(‘ticket’,”ticket=’$component_verify_ticket’,time=’$timeStamp'”,”id=1″);
echo ‘success';
}
}
?>
//req weixin.php
$array_e = $xml->getElementsByTagName('Encrypt');
$array_a = $xml->getElementsByTagName('ToUserName');
$encrypt = $array_e->item(0)->nodeValue;
$tousername = $array_a->item(0)->nodeValue;
return array(0, $encrypt, $tousername);
} catch (Exception $e) {
//print $e . "\n";
return array(ErrorCode::$ParseXmlError, null, null);
}
}
public function generate($encrypt, $signature, $timestamp, $nonce)
{
$format = ”
%s
%s
%s
%s
“;
return sprintf($format, $encrypt, $signature, $timestamp, $nonce);
}
}
class PKCS7Encoder
{
public static $block_size = 32;
function encode($text)
{
$block_size = PKCS7Encoder::$block_size;
$text_length = strlen($text);
//计算需要填充的位数
$amount_to_pad = PKCS7Encoder::$block_size – ($text_length % PKCS7Encoder::$block_size);
if ($amount_to_pad == 0) {
$amount_to_pad = PKCS7Encoder::block_size;
}
//获得补位所用的字符
$pad_chr = chr($amount_to_pad);
$tmp = “”;
for ($index = 0; $index < $amount_to_pad; $index++) { $tmp .= $pad_chr; } return $text . $tmp; } function decode($text) { $pad = ord(substr($text, -1)); if ($pad < 1 || $pad > 32) {
$pad = 0;
}
return substr($text, 0, (strlen($text) – $pad));
}
}
class Prpcrypt
{
public $key;
function Prpcrypt($k)
{
$this->key = base64_decode($k . “=”);
}
public function encrypt($text, $appid)
{
try {
//获得16位随机字符串,填充到明文之前
$random = $this->getRandomStr();
$text = $random . pack(“N”, strlen($text)) . $text . $appid;
// 网络字节序
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, ”, MCRYPT_MODE_CBC, ”);
$iv = substr($this->key, 0, 16);
//使用自定义的填充方式对明文进行补位填充
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
mcrypt_generic_init($module, $this->key, $iv);
//加密
$encrypted = mcrypt_generic($module, $text);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
//print(base64_encode($encrypted));
//使用BASE64对加密后的字符串进行编码
return array(ErrorCode::$OK, base64_encode($encrypted));
} catch (Exception $e) {
//print $e;
return array(ErrorCode::$EncryptAESError, null);
}
}
public function decrypt($encrypted, $appid)
{
try {
//使用BASE64对需要解密的字符串进行解码
$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, ”, MCRYPT_MODE_CBC, ”);
$iv = substr($this->key, 0, 16);
mcrypt_generic_init($module, $this->key, $iv);
//解密
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
} catch (Exception $e) {
return array(ErrorCode::$DecryptAESError, null);
}
try {
//去除补位字符
$pkc_encoder = new PKCS7Encoder;
$result = $pkc_encoder->decode($decrypted);
//去除16位随机字符串,网络字节序和AppId
if (strlen($result) < 16) return “”; $content = substr($result, 16, strlen($result)); $len_list = unpack(“N”, substr($content, 0, 4)); $xml_len = $len_list[1]; $xml_content = substr($content, 4, $xml_len); $from_appid = substr($content, $xml_len + 4); } catch (Exception $e) { //print $e; return array(ErrorCode::$IllegalBuffer, null); } if ($from_appid != $appid) return array(ErrorCode::$ValidateAppidError, null); return array(0, $xml_content); } function getRandomStr() { $str = “”; $str_pol = “ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz”; $max = strlen($str_pol) – 1; for ($i = 0; $i < 16; $i++) { $str .= $str_pol[mt_rand(0, $max)]; } return $str; } } class WXBizMsgCrypt { private $token; private $encodingAesKey; private $appId; public function WXBizMsgCrypt($token, $encodingAesKey, $appId) { $this->token = $token;
$this->encodingAesKey = $encodingAesKey;
$this->appId = $appId;
}
public function encryptMsg($replyMsg, $timeStamp, $nonce, &$encryptMsg)
{
$pc = new Prpcrypt($this->encodingAesKey);
//加密
$array = $pc->encrypt($replyMsg, $this->appId);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
if ($timeStamp == null) {
$timeStamp = time();
}
$encrypt = $array[1];
//生成安全签名
$sha1 = new SHA1;
$array = $sha1->getSHA1($this->token, $timeStamp, $nonce, $encrypt);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
$signature = $array[1];
//生成发送的xml
$xmlparse = new XMLParse;
$encryptMsg = $xmlparse->generate($encrypt, $signature, $timeStamp, $nonce);
return ErrorCode::$OK;
}
public function decryptMsg($msgSignature, $timestamp = null, $nonce, $postData, &$msg)
{
if (strlen($this->encodingAesKey) != 43) {
return ErrorCode::$IllegalAesKey;
}
$pc = new Prpcrypt($this->encodingAesKey);
//提取密文
$xmlparse = new XMLParse;
$array = $xmlparse->extract($postData);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
if ($timestamp == null) {
$timestamp = time();
}
$encrypt = $array[1];
$touser_name = $array[2];
//验证安全签名
$sha1 = new SHA1;
$array = $sha1->getSHA1($this->token, $timestamp, $nonce, $encrypt);
$ret = $array[0];
if ($ret != 0) {
return $ret;
}
$signature = $array[1];
if ($signature != $msgSignature) {
return ErrorCode::$ValidateSignatureError;
}
$result = $pc->decrypt($encrypt, $this->appId);
if ($result[0] != 0) {
return $result[0];
}
$msg = $result[1];
return ErrorCode::$OK;
}
}
在req中的创建三个空php文件,权限首先设置777
authorizer_access_token.php authorizer_refresh_token.php appid.php
// get_acc.php
$url = “https://api.weixin.qq.com/cgi-bin/component/api_component_token”;
$post_data1[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data1[‘component_appsecret’] = ‘a8c304ab88a7300673ca2321bb816390′;
$post_data1[‘component_verify_ticket’] = ‘ticket@@@V2qugs6veYTi8GLD-_SFQTB2ket6SIrDQEqYRM3QsQL1uU431KePyHLm3rIiwX7nwe-j1eVrBtJFOPTuNdfRkQ';
$post_data = json_encode($post_data1);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$component_access_token = $resdata->component_access_token;
echo $component_access_token;
echo ”
“;
//获取预授权码
$parameter = “component_access_token=”.$component_access_token;
$url = “https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?”.$parameter;
$post_data2[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data = json_encode($post_data2);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$pre_auth_code = $resdata->pre_auth_code;
echo $pre_auth_code;
echo ”
“;
//公众号授权给第三方
/*$web_url = “http://demo.irudder.me/wei/user/wxlogin”;
$href=’https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=’.$appId.’&pre_auth_code=’.$pre_auth_code.’&redirect_uri=’.$web_url;
echo $href;
header(‘refresh:3;url=’.$href);
echo ”
“;
*/
//使用授权码换取公众号的授权信息
$parameter = “component_access_token=”.$component_access_token;
$url = “https://api.weixin.qq.com/cgi-bin/component/api_query_auth?”.$parameter;
//授权后才会有的!
$auth_code = “preauthcode@@@vZWncWE6F0FFQ20BDc6UP-07N2eba3v7EZzW1ZNKKk-5QC-05uhaL7NTeM2eY0is”;
$post_data3[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data3[‘authorization_code’] = $auth_code;
$post_data = json_encode($post_data3);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$authorizer_access_token = $resdata->authorization_info->authorizer_access_token;
echo $authorizer_access_token;
/**
* 模拟post进行url请求
* @param string $url
* @param array $post_data
*/
function request_post($url = ”, $post_data = array()) {
if (empty($url) || empty($post_data)) {
return false;
}
$postUrl = $url;
$curlPost = $post_data;
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
return $data;
}
//post_wx.php
";
echo $msg;
echo "
";
echo $component_verify_ticket;
echo "
";
*/
//获取第三方平台access_token
$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
$post_data1['component_appid'] = 'wxe1219eb7d5780e65';
$post_data1['component_appsecret'] = 'a8c304ab88a7300673ca2321bb816390';
$post_data1['component_verify_ticket'] = $component_verify_ticket;
$post_data = json_encode($post_data1);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$component_access_token = $resdata->component_access_token;
echo $component_access_token;
echo ”
“;
//获取预授权码
$parameter = “component_access_token=”.$component_access_token;
$url = “https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?”.$parameter;
$post_data2[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data = json_encode($post_data2);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$pre_auth_code = $resdata->pre_auth_code;
echo $pre_auth_code;
echo ”
“;
//公众号授权给第三方
$web_url = “http://demo.irudder.me/deal.php”;
$href=’https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=’.$appId.’&pre_auth_code=’.$pre_auth_code.’&redirect_uri=’.$web_url;
echo $href;
header(‘refresh:3;url=’.$href);
echo ”
“;
//使用授权码换取公众号的授权信息
$parameter = “component_access_token=”.$component_access_token;
$url = “https://api.weixin.qq.com/cgi-bin/component/api_query_auth?”.$parameter;
//授权后才会有的!
$auth_code = “queryauthcode@@@j41WQzJIfyu8nEQ7NvTipcq-H1Mn2rMODIPVCd0QT_fX61qTHDhpJJ2YzYIve-Jx1MgerGDTLb-SLArpaFoEYA”;
$post_data3[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data3[‘authorization_code’] = $auth_code;
$post_data = json_encode($post_data3);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$authorizer_access_token = $resdata->authorization_info->authorizer_access_token;
/*
$authorizer_refresh_token = $resdata->authorization_info->authorizer_refresh_token;
echo $authorizer_access_token;
file_put_contents(“./req/authorizer_access_token.php”, $authorizer_access_token);
file_put_contents(“./req/authorizer_refresh_token.php”, $authorizer_refresh_token);
/*$authorizer_refresh_token = $resdata->authorizer_refresh_token;
echo $authorizer_refresh_token;*/
echo ”
“;
//在指定ip下使用上面的到的第三方authorizer_access_token 去调用公众号开发接口!!
//N4Zd9p_Qz0a-3HxH5iUpJ3KCcMQuthhbrfPOcHO7qf0_UHBpZe2Q3Oonaq3MEtQ0nc7I8TRFt99zYX1YgdlU-XySXdMdYCwb6MLm3m5W1zsMA5kqxRR3FfdO3ce-NHN3EPFhADDALB
/*
$url = “https://api.weixin.qq.com/cgi-bin/menu/create?access_token=”.$authorizer_access_token;
$xjson = ‘{
“button”:[
{
“type”:”click”,
“name”:”今日歌曲”,
“key”:”V1001_TODAY_MUSIC”
}
]
}';
$res = request_post($url, $xjson);
var_dump($res);
*/
$art ='{
“articles”: [{
“title”: TITLE,
“thumb_media_id”: THUMB_MEDIA_ID,
“author”: AUTHOR,
“digest”: DIGEST,
“show_cover_pic”: SHOW_COVER_PIC(0 / 1),
“content”: CONTENT,
“content_source_url”: CONTENT_SOURCE_URL
},
//若新增的是多图文素材,则此处应还有几段articles结构
]
}';
//$type = “image”;
//$filepath = “9.png”;
//$filedata = array(“file1″ => “@”.$filepath);
/*
$file_info = array(
‘filename’ => “9.png”,
‘content-type’=>”image/jpeg”,
‘filelength’=>”78710″
);
$filedata= array(“media”=>”9.png”,’form-data’=>$file_info);
$filedata= json_encode($filedata);
*/
/*
$filepath = “9.png”;
$ajson = ‘{
“articles”: [{
“title”: “你好呀”,
“thumb_media_id”: “20151116”,
“author”: “rudder”,
“digest”: ”,
“show_cover_pic”: 1,
“content”: “这是内容了,…”,
“content_source_url”: “http://irudder.me”,
},
]
}';
$url = “https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=”.$authorizer_access_token;
*/
var_dump(request_get(“https://api.weixin.qq.com/cgi-bin/media/get?access_token=RsuienekdmR2bJYPG3HZiThYmW8ksad5IIvxp1sfGYV6CkSXUwe1Hd7qQgDMCZJf61Q37Z-j3pHnjhCyl-kpcQvQcYEXkSBaN0n-uLREtlHVIoeARkzeB2-BMZ0_P2MlFEIfALDSRV&media_id=Yb1K-aOWqptks7TAhi45Sd6HP0OLnKk84ARCzMl4HSmMiXQKDyWyYtLJ4l92lq8r”));
//$res = request_post($url, $ajson);
//var_dump($res);
echo ”
“;
function request_get($url = ”){
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
$output=curl_exec($ch);
$fh=fopen(“test.php”,’w’);
fwrite($fh,$output);
fclose($fh);
}
/**
* 模拟post进行url请求
* @param string $url
* @param array $post_data
*/
function request_post($url = ”, $post_data = array()) {
if (empty($url) || empty($post_data)) {
return false;
}
$postUrl = $url;
$curlPost = $post_data;
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
return $data;
}
?>
//dothing.php
////foreach($resdata as $key=>$val){
//echo $val->media_id;
//echo " ";
//var_dump($resdata[6]->content->news_item);
echo "
";
//var_dump($val->content->news_item[0]->title);
echo "
";
//}
$mediadata = $resdata[1]->content->news_item;
foreach($mediadata as $key=>$val){
echo $val->thumb_media_id;
echo ” “;
echo $val->title;
echo ”
“;
}
echo ”
“;
/*
var_dump($resdata[8]);
echo ”
“;
$mediadata = $resdata[8]->content->news_item;
foreach($mediadata as $key=>$val){
echo $val->thumb_media_id;
echo ” “;
echo $val->title;
echo ”
“;
}
*/
$url = “https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=”.$authorizer_access_token;
$post_data6[‘media_id’] = ‘TCelQtZUkPbI9BZe2zS4f8j-EeNak7jzcnuPCP6tvRo';
$post_data = json_encode($post_data6);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
$resdata = $resdata->item;
var_dump($resdata);
/*
//获取指定media_id的素材
$url = “https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=”.$authorizer_access_token;
$post_data5[‘media_id’] = ‘ZEYdr1p9fWH8C4YElr5052jbtnHrsuIE2qkBz1DvvJs';
$post_data = json_encode($post_data5);
$resdata = request_post($url, $post_data);
var_dump($resdata);
*/
//自定义菜单
$url = “https://api.weixin.qq.com/cgi-bin/menu/create?access_token=”.$authorizer_access_token;
$xjson = ‘{
“button”:[
{
“type”: “view_limited”,
“name”:”使用教程”,
“media_id”: “TCelQtZUkPbI9BZe2zS4f8j-EeNak7jzcnuPCP6tvRo”
},
{
“type”: “view_limited”,
“name”:”公告通知”,
“media_id”: “TCelQtZUkPbI9BZe2zS4f8j-EeNak7jzcnuPCP6tvRo”
},
{
“name”:”今日更新”,
“sub_button”:[
{
“type”: “view_limited”,
“name”: “剧集目录”,
“media_id”: “TCelQtZUkPbI9BZe2zS4f8j-EeNak7jzcnuPCP6tvRo”
},
{
“type”: “view_limited”,
“name”: “电影更新”,
“media_id”: “TCelQtZUkPbI9BZe2zS4f8j-EeNak7jzcnuPCP6tvRo”
},
{
“type”: “view_limited”,
“name”: “动漫更新”,
“media_id”: “TCelQtZUkPbI9BZe2zS4f8j-EeNak7jzcnuPCP6tvRo”
},
]
}
]
}';
$res = request_post($url, $xjson);
$res = json_decode($res);
//echo $res->errmsg;
var_dump($res);
exit;
if($res->errmsg!=’ok’){
require(‘./req/do.php’);
//获取第三方平台access_token
$url = “https://api.weixin.qq.com/cgi-bin/component/api_component_token”;
$post_data1[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data1[‘component_appsecret’] = ‘a8c304ab88a7300673ca2321bb816390′;
$post_data1[‘component_verify_ticket’] = $component_verify_ticket;
$post_data = json_encode($post_data1);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$component_access_token = $resdata->component_access_token;
//获取刷新令牌和授权方的appid
$arr = file_get_contents(‘req/authorizer_refresh_token.php’);
$arr = explode(‘**’, $arr);
var_dump($arr);
echo ”
“;
$appid = $arr[0];
$authorizer_refresh_token = $arr[1];
$url = “https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=”.$component_access_token;
$post_data5[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data5[‘authorizer_appid’] = $appid;
$post_data5[‘authorizer_refresh_token’] = $authorizer_refresh_token;
$post_data = json_encode($post_data5);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
var_dump($resdata);
echo ”
“;
$authorizer_access_token = $resdata->authorizer_access_token;
$authorizer_refresh_token = $appid.’**’.$resdata->authorizer_refresh_token;
if($authorizer_access_token==” || !$resdata->authorizer_refresh_token){
echo “缺少必要的数据,请刷新试试”;
exit;
}
$myfile1 = fopen(“req/authorizer_access_token.php”, “w”) or die(“权限错误!”);
fwrite($myfile1, $authorizer_access_token);
fclose($myfile1);
$myfile2 = fopen(“req/authorizer_refresh_token.php”, “w”) or die(“权限错误!”);
fwrite($myfile2, $authorizer_appid.’**’.$authorizer_refresh_token);
fclose($myfile2);
}
echo ”
“;
function request_get($url = ”){
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
$output=curl_exec($ch);
//$fh=fopen(“test.php”,’w’);
$data = curl_exec($ch);//运行curl
//fwrite($fh,$output);
//fclose($ch);
return $data;
}
/**
* 模拟post进行url请求
* @param string $url
* @param array $post_data
*/
function request_post($url = ”, $post_data = array()) {
if (empty($url) || empty($post_data)) {
return false;
}
$postUrl = $url;
$curlPost = $post_data;
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
return $data;
}
//deal.php
//echo $component_access_token;
echo ”
“;
//获取预授权码
$parameter = “component_access_token=”.$component_access_token;
$url = “https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?”.$parameter;
$post_data2[‘component_appid’] = ‘wxe1219eb7d5780e65′;
$post_data = json_encode($post_data2);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
$pre_auth_code = $resdata->pre_auth_code;
//echo $pre_auth_code;
echo ”
“;
//使用授权码换取公众号的授权信息
$parameter = “component_access_token=”.$component_access_token;
$url = “https://api.weixin.qq.com/cgi-bin/component/api_query_auth?”.$parameter;
//授权后才会有的!
$auth_code = $_GET[‘auth_code’]; //”queryauthcode@@@j41WQzJIfyu8nEQ7NvTipcq-H1Mn2rMODIPVCd0QT_fX61qTHDhpJJ2YzYIve-Jx1MgerGDTLb-SLArpaFoEYA”;
$post_data3[‘component_appid’] = ‘xxxxxx';
$post_data3[‘authorization_code’] = $auth_code;
$post_data = json_encode($post_data3);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
//var_dump($resdata);
/*
$authorizer_access_token = $resdata->authorization_info->authorizer_access_token;
echo $authorizer_access_token;
/*$authorizer_refresh_token = $resdata->authorizer_refresh_token;
echo $authorizer_refresh_token;*/
//获取令牌 和刷新令牌 存入
$authorizer_access_token = $resdata->authorization_info->authorizer_access_token;
$authorizer_refresh_token = $resdata->authorization_info->authorizer_refresh_token;
$authorizer_appid = $resdata->authorization_info->authorizer_appid;
echo $authorizer_access_token;
echo ”
“;
echo $authorizer_refresh_token;
//echo file_put_contents(“req/authorizer_access_token.php”, ‘hhhhhhhhhhhhhhjashdfhsadjfhkjsadfhksahdfksahdfkjhsadkjfhksajdfh你算的复苏回暖’);
//echo file_put_contents(“req/authorizer_refresh_token.php”, $authorizer_refresh_token);
$myfile1 = fopen(“req/authorizer_access_token.php”, “w”) or die(“权限错误!”);
fwrite($myfile1, $authorizer_access_token);
fclose($myfile1);
$myfile2 = fopen(“req/authorizer_refresh_token.php”, “w”) or die(“权限错误!”);
fwrite($myfile2, $authorizer_appid.’**’.$authorizer_refresh_token);
fclose($myfile2);
echo ”
“;
//在指定ip下使用上面的到的第三方authorizer_access_token 去调用公众号开发接口!!
//N4Zd9p_Qz0a-3HxH5iUpJ3KCcMQuthhbrfPOcHO7qf0_UHBpZe2Q3Oonaq3MEtQ0nc7I8TRFt99zYX1YgdlU-XySXdMdYCwb6MLm3m5W1zsMA5kqxRR3FfdO3ce-NHN3EPFhADDALB
/*
//获取全部永久素材
$url = “https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=”.$authorizer_access_token;
$post_data4[‘type’] = ‘news';
$post_data4[‘offset’] = 0;
$post_data4[‘count’] = 20;
$post_data = json_encode($post_data4);
$resdata = request_post($url, $post_data);
$resdata = json_decode($resdata);
$resdata = $resdata->item;
foreach($resdata as $key=>$val){
echo $val->media_id;
echo ” “;
}
*/
/*
//获取指定media_id的素材
$url = “https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=”.$authorizer_access_token;
$post_data5[‘media_id’] = ‘ZEYdr1p9fWH8C4YElr5052jbtnHrsuIE2qkBz1DvvJs';
$post_data = json_encode($post_data5);
$resdata = request_post($url, $post_data);
var_dump($resdata);
*/
/*
//自定义菜单
$url = “https://api.weixin.qq.com/cgi-bin/menu/create?access_token=”.$authorizer_access_token;
$xjson = ‘{
“button”:[
{
“name”:”菜单”,
“sub_button”:[
{
“type”: “view_limited”,
“name”: “手撕”,
“media_id”: “ZEYdr1p9fWH8C4YElr5052jbtnHrsuIE2qkBz1DvvJs”
},
}
]
}';
$res = request_post($url, $xjson);
var_dump($res);
*/
echo ”
“;
function request_get($url = ”){
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
$output=curl_exec($ch);
//$fh=fopen(“test.php”,’w’);
$data = curl_exec($ch);//运行curl
//fwrite($fh,$output);
//fclose($ch);
return $data;
}
/**
* 模拟post进行url请求
* @param string $url
* @param array $post_data
*/
function request_post($url = ”, $post_data = array()) {
if (empty($url) || empty($post_data)) {
return false;
}
$postUrl = $url;
$curlPost = $post_data;
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运行curl
curl_close($ch);
return $data;
}
//weixin/content.php
**1449756775**2076038412**7591546637fc23a87f2c3b2f2a09d863456124b6
//weixin/reply.php
$array_e = $xml_tree -> getElementsByTagName('Encrypt');
$encrypt = $array_e -> item(0) -> nodeValue;
//echo $encrypt;
$format = "
$from_xml = sprintf($format, $encrypt);
//var_dump($from_xml);
// 第三方收到公众号平台发送的消息
$msg = '';
$errCode = $pc -> decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
//var_dump($arr);
//echo "
";
//var_dump($msg);
//echo "
";
//echo $errCode;
//echo "
";
if ($errCode == 0) {
//print("解密后: " . $msg . "\n");
$xml = new DOMDocument();
$xml -> loadXML($msg);
//获取发送者 接受者 发送的内容
$content = $xml -> getElementsByTagName('Content');
$Content = $content -> item(0) -> nodeValue;
$ToUserName = $xml -> getElementsByTagName(‘ToUserName’);
$ToUserName = $ToUserName -> item(0) -> nodeValue;
$FromUserName = $xml -> getElementsByTagName(‘FromUserName’);
$FromUserName = $FromUserName -> item(0) -> nodeValue;
//$Content = $_GET[‘key’];
//echo $Content;
//var_dump($Content);
//echo ”
“;
/*
$con = mysql_connect(“xxx”,”root”,”xxxx”);
$db = mysql_select_db(“wp”,$con);
mysql_query(“set names utf8″);
//$sql = “select `content` from `wp_custom_reply_text` where `keyword`=’$Content'”;
$sql = “select * from `wp_custom_reply_text` where `keyword` like ‘%$Content%'”;
$result = mysql_query($sql ,$con);
//$contentStr = ‘没有进行查询';
//echo $sql;
//echo ”
“;
//var_dump($result);
*/
/*
$contentStr = ‘没有进行查询';
$res = conn($key);
if($row = mysql_fetch_array($result)){
/*$contentStr = “萌萌机器人:不知道为啥,就是搜索不到你说的这个,让我再想想怎么办好呢。。“;*\/
//$url = “http://www.tuling123.com/openapi/api?key=d812d695a5e0df258df952698faca6cc&info=”.$Content;//weiphp的
//$url = “http://www.tuling123.com/openapi/api?key=1ccf45268dcafb72785e86e638164753&info=”.$Content;//我的
$url = “http://www.tuling123.com/openapi/api?key=07c75391574596404af60937d9ee9bf8&info=”.$Content;//蝶梦
$contentStr = “萌萌机器人:”.json_decode(request_get($url))->text;
}else{
while($row = mysql_fetch_array($result))
{
$contentStr = $row[‘content’];
}
}
while($contentStr==”没有进行查询”){
$i = 0;
if(!mysql_fetch_row($result)){
$contentStr = “萌萌机器人:不知道为啥,就是搜索不到你说的这个,让我再想想怎么办好呢。。“;
}else{
while($row = mysql_fetch_array($result))
{
$contentStr = $row[‘content’];
}
}
$i++;
if($i=10){
//echo $i;
break;
}
}*/
//echo $contentStr;
//echo ‘
‘;
//echo $Content;
$contentStr = “萌萌机器人:不知道为啥,就是搜索不到你说的这个,让我再想想怎么办好呢。。“;
$res = conn($Content);
//var_dump($res);
//echo $res[‘content’];
if(!$res || $res==”){
$url = “http://www.tuling123.com/openapi/api?key=07c75391574596404af60937d9ee9bf8&info=”.$Content;//蝶梦
$contentStr = “萌萌机器人:”.json_decode(request_get($url))->text;
}else{
//var_dump($res);
$contentStr = $res[0][‘content’];
}
//echo $contentStr;
$text = ‘
%s
<![CDATA
]>
0
‘;
$CreateTime = time();
$text = sprintf($text, $FromUserName, $ToUserName, $CreateTime, $contentStr);
//var_dump($text);
/* 可直接运用的例子
$text = ‘
1449298059
<![CDATA
]>
0
‘;
*/
$from_xml = sprintf($format, $encrypt);
//$errCode = $pc -> encryptMsg($msg_sign, $timeStamp, $nonce, $msg);
$errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
//echo $encryptMsg;
$arr = explode(‘ ‘,$encryptMsg);//4个空格
//var_dump($arr);
$encryptMsg = substr($arr[1],0,-1);
$signature = substr($arr[2],0,-1);
$timestamp = substr($arr[3],0,-1);
$nonce = substr($arr[4],0,-1);
$format = ”
%s
“;
echo sprintf($format, $encryptMsg, $signature, $timestamp, $nonce);
//var_dump($from_xml);
//var_dump($msg);
//echo $errCode;
}else{
echo “解密出错。,。。”;
}
function request_get($url = ”){
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
$output=curl_exec($ch);
//$fh=fopen(“test.php”,’w’);
$data = curl_exec($ch);//运行curl
//fwrite($fh,$output);
//fclose($ch);
return $data;
}
/**连接数据库*/
function conn($key){
/*try {
$dbh = new PDO(‘mysql:host=xxxxxxxxx;dbname=wp’, ‘root’, ‘xxxxxx’);
$dbh->exec(“SET NAMES ‘utf8′”);
$sql = “SELECT `content` from wp_custom_reply_text where `keyword` like ‘%$key%’ AND `token`=’gh_e261fc4ecccb’ limit 1″;
$data = $dbh->query($sql);
var_dump($data);
foreach($data as $row) {
//print_r($row);
return $row;
}
$dbh = null;*/
try {
$dbh = new PDO(‘mysql:host=xxxxxx;dbname=wp’, ‘root’, ‘xxxxxxxxxxxx’);
$dbh->exec(“SET NAMES ‘utf8′”);
$sql = “SELECT `content` from wp_custom_reply_text where `keyword`=’$key’ AND `token`=’gh_e261fc4ecccb’ limit 1″;
//echo $sql;
$rs = $dbh->query($sql);
$data = $rs->fetchAll();
if($data){
//echo 1;
}else{
$sql = “SELECT `content` from wp_custom_reply_text where `keyword` like ‘%$key’ AND `token`=’gh_e261fc4ecccb’ limit 1″;
$rs = $dbh->query($sql);
$data = $rs->fetchAll();
if($data){
//echo 2;
}else{
$sql = “SELECT `content` from wp_custom_reply_text where `keyword` like ‘$key%’ AND `token`=’gh_e261fc4ecccb’ limit 1″;
$rs = $dbh->query($sql);
$data = $rs->fetchAll();
//echo 3;
}
}
//echo $sql;
return $data;
$dbh = null;
} catch (PDOException $e) {
//print “Error!: ” . $e->getMessage() . ”
“;
return “Error!: ” . $e->getMessage() . ”
“;
die();
}
}
/*
$con = mysql_connect(“xxxxxxxx”,”root”,”密码”);
$db = mysql_select_db(“weiphp”,$con);
mysql_query(“set names utf8″);
define(“TOKEN”, “xxxxxxxxxx”);
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();
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)){
$postObj = simplexml_load_string($postStr, ‘SimpleXMLElement’, LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$type = $postObj->MsgType;
$event = $postObj->Event;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = ”
%s
0
“;
//加载图文模版
$picTpl = ”
%s
1
1
“;
if($type == “event” && $event == “subscribe”)
{
$msgType = “text”;
$contentStr = “欢迎关注蝶梦小筑!”;
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
//$keywords = iconv(“UTF-8″,”gbk”,$keyword);
$result = mysql_query(“select aid,typeid from `weiphp` where keyword like ‘%{$keywords}%’ “);
while ($row = mysql_fetch_array($result)) {
$id = $row[‘aid’];
$typeid = $row[‘typeid’];
}
if(empty($id)){
$msgType = “text”;
$contentStr = “很抱歉没有搜索到相关信息,您可以登录http://m.365rzf.com来查询相关信息” ;
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
$url = array(
1 => ‘http://www.demonzone.cn/’,
);
$xinxi = mysql_query(“select title,litpic,pubdate,description from `数据库` where id ={$id}”);
while ($jay = mysql_fetch_array($xinxi)) {
$title = $jay[‘title’];
$image = “http://www.demonzone.cn”.$jay[‘litpic’];
$data = date(‘Y/md’,$jay[‘pubdate’]);
$desription = $jay[‘description’];
}
$turl = $url[$typeid].$data.”/”.$id.”.html”; //url抵制
$title= iconv(“GBK”,”UTF-8″,$title); //标题名称
$desription= iconv(“GBK”,”UTF-8″,$desription); //描述
$msgType = “news”; //类型
$resultStr = sprintf($picTpl, $fromUsername, $toUsername, $time, $msgType, $title,$desription,$image,$turl);
echo $resultStr;
}
}
}else {
echo “”;
exit;
}
}
private function checkSignature()
{
$signature = $_GET[“signature”];
$timestamp = $_GET[“timestamp”];
$nonce = $_GET[“nonce”];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}*/
//代码附件
code