您尚未登录。

#2 Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » PHP微信开发-access-token的获取与存储 (转) » 2021-01-02 21:00:02

https://blog.csdn.net/HOLYLANCES/article/details/82018065

存储是以.txt的方式存储token值的 先上代码

<?php
 
require_once("file_cache.php");
class WeixinUtil{
    private $appId = 'appId ';
    private $appSecret = 'appSecret ';
    //获取AccessToken
    public function getAccessToken(){
        $wx_access_token_cache_key = 'wx_access_token';
 
        $cache = new FileCache('./access_token.txt');//存储的本地位置
        $token = $cache->get($wx_access_token_cache_key);//去文件中获取token
 
        if (!$token){//没有的话就创建新的
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
            $token = $this->https_curl_json($url,null);
            $cache->set($wx_access_token_cache_key, $token, time()+7000);
        }
 
        $token = json_decode($token);
        $token = $token->access_token;
        return $token;
    }
 
    /* 发送json格式的数据,到api接口*/
    public function https_curl_json($url,$data){
        $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;
    }
 
}
?>

另一个类 用来进行文件操作

<?php
//该类用来配合WeixinUtil.php类 进行token的文件操作
class FileCache{
    private $cache_file;
 
    private function load(){
        if(file_exists($this->cache_file)){
            $content = file_get_contents($this->cache_file);
            if (strlen($content) > 0){
                $data = json_decode($content);
                return $data;
            }
        }
        return array();
    }
 
    private function save($data){
        $content = json_encode($data);
        return file_put_contents($this->cache_file, $content);
    }
 
    public function __construct($filename) {
        $this->cache_file = $filename;
    }
 
    public function get($key){
        $data = $this->load();
 
        foreach($data as $item){
            if ($item->key == $key){
                if ($item->expire_time > time()){
                    return $item->value;
                }
                break;
            }
        }
        return NULL;
    }
 
    public function set($key, $value, $expire_time=NULL){
        $data = $this->load();
        $obj = NULL;
        foreach($data as $item){
            if ($item->key == $key){
                $obj = $item;
                $obj->value = $value;
                if ($expire_time != NULL){
                    $obj->expire_time = $expire_time;
                }
                break;
            }
        }
 
        if ($obj == NULL){
            $obj = new CacheItem($key, $value, $expire_time);
            array_push($data, $obj);
        }
        return $this->save($data);
    }
}
 
class CacheItem{
    public $key;
    public $value;
    public $expire_time;
 
    public function __construct($key, $value, $expire_time) {
        $this->key = $key;
        $this->value = $value;
        $this->expire_time = $expire_time;
    }
}
?>

最后 测试类

<?php
include "WeixinUtil.php";
$wx = new WeixinUtil();
echo $wx->getAccessToken();

第二个类来自https://www.cnblogs.com/hydonlee/p/5419063.html

=======================================================================================

18/9/11

access_token存储在DB里,参考文章↓

https://blog.csdn.net/sct_t/article/details/53002611

#3 VMWare/Linux/Ubuntu/Fedora/CentOS/U-BOOT » 为什么我这个笔记本电脑开VMWARE 之后, 插入USB设备经常性出现无法识别的USB设备, 重启电脑之后才会正常. » 2020-09-26 23:00:57

为什么我这个笔记本电脑开VMWARE 之后, 插入USB设备经常性出现无法识别的USB设备, 重启电脑之后才会正常.

请教大家

#4 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 请教大家, 手机第三方浏览器 可以做到拉起微信,并使用微信登录我的网站吗? » 2020-09-01 17:35:30

manhere 说:

不能,请注册一个认证服务号,使用网页授权登录方式。

我现在就是用服务号, 请问 网页授权登录方式 是指在微信内部打开网址?

#5 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 请教大家, 手机第三方浏览器 可以做到拉起微信,并使用微信登录我的网站吗? » 2020-09-01 17:04:25

https://bbs.csdn.net/topics/392336665

qq_38291203 说:

可以通过公众号授权登录。移动H5需要在微信浏览器打开,如果用户用其他浏览器,就会提示到微信客户端打开。目前对我们的产品是可行的,因为我们的移动H5主要是通过微信传播的。得让你们产品运营看看是否适用~

这个网友说只能在微信浏览器打开。

#8 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-09-01 09:26:17

微信公众号个性化菜单: https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Personalized_menu_interface.html#0

匹配条件, 分组/性别/地域/操作系统类型/语言 等:

"matchrule": {
        "tag_id": "2",
        "sex": "1",
        "country": "中国",
        "province": "广东",
        "city": "广州",
        "client_platform_type": "2",
        "language": "zh_CN"
    }

执行文件 addconditional_menu.php 注册菜单, 返回菜单编号Id:

<?php

//通过微信获取access_token接口 获取的token
$ACCESS_TOKEN = '36_wH1VlEPwtqU5hhiS9QNayaoBON4h4MNH1ICWNAK8A5pBQpQ5Jx0-k1dAvT4ixloPaCgBFtlc15D-OAvxfraTIizvPzY-A96ubwtPpLWxTjKyL605hdKFt3unigoXt-AwKWDY5Q9fz53Rwl5CKQWfAGAEK';


$openid = 'oVEjzvmgLIF0oLHYccqGZnYyZ4r4';//用户openid

$template_id = 'dGjqe_2azli_K2W_T0Niel2823LxuoWS-VzB3Lp5goU';//配置的模板id

$url = '[url]https://xxx.cn/[/url]';//点击模板消息跳转的链接



//个性化菜单字符串
$menujson = '{
        "button":[
        {
        "type":"click",
        "name":"单击",
        "key":"V1001_TODAY_MUSIC"
        },
        {
                "name":"搜索",
                "sub_button":[
            {
                "type":"view",
                "name":"百度",
                "url":"http://www.baidu.com/"
            }
        ]
 }],
 "matchrule":{
  "sex":"1"
  }
}';




$send_template_url = '[url]https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=[/url]' . $ACCESS_TOKEN;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $send_template_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $menujson);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);

//$rinfo = curl_getinfo($ch);
//print_r($rinfo);

//输出收到的 json 回应: {"menuid":425482849}
printf("\n\n%s\n\n ---------------- \n\n", $res);

curl_close($ch);
return $res;
?>


关注的用户(openid)应用到该注册菜单 trymatch_menu.php:

<?php

//通过微信获取access_token接口 获取的token
$ACCESS_TOKEN = '36_wH1VlEPwtqU5hhiS9QNayaoBON4h4MNH1ICWNAK8A5pBQpQ5Jx0-k1dAvT4ixloPaCgBFtlc15D-OAvxfraTIizvPzY-A96ubwtPpLWxTjKyL605hdKFt3unigoXt-AwKWDY5Q9fz53Rwl5CKQWfAGAEK';


$openid = 'oVEjzvmgLIF0oLHYccqGZnYyZ4r4';//用户openid

$template_id = 'dGjqe_2azli_K2W_T0Niel2823LxuoWS-VzB3Lp5goU';//配置的模板id

$url = 'https://xxx.cn/';//点击模板消息跳转的链接


$json_trymenu = sprintf('{"user_id": "%s"}', $openid);



$send_template_url = 'https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=' . $ACCESS_TOKEN;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $send_template_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_trymenu);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);



printf("\n\n%s\n\n ---------------- \n\n", $res);

curl_close($ch);
return $res;
?>

收到字符串:

{"menu":{"button":[{"type":"click","name":"单击","key":"V1001_TODAY_MUSIC","sub_button":[]},{"name":"搜索","sub_button":[{"type":"view","name":"百度",                     "url":"http:\/\/www.baidu.com\/","sub_button":[]}]}]}}

然后你打开微信, 发现菜单是不是变了.

如果还没有变, 先取消关注, 再加关注即可。

#9 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-08-31 16:34:29

https://segmentfault.com/a/1190000019436016

<?php
header("Content-type: text/html; charset=utf-8");
define("ACCESS_TOKEN", "生成的Access_Token");
//创建菜单
function createMenu($data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".ACCESS_TOKEN);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);
if (curl_errno($ch)) {
 return curl_error($ch);
}
curl_close($ch);
return $tmpInfo;
}
//获取菜单
function getMenu(){
return file_get_contents("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".ACCESS_TOKEN);
}
//删除菜单
function deleteMenu(){
return file_get_contents("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".ACCESS_TOKEN);
}
$data = '{
   "button":[
   {
     "type":"click",
     "name":"首页",
     "key":"home"
   },
   {
      "type":"click",
      "name":"简介",
      "key":"introduct"
   },
   {
      "name":"菜单",
      "sub_button":[
      {
        "type":"click",
        "name":"hello word",
        "key":"V1001_HELLO_WORLD"
      },
      {
        "type":"click",
        "name":"赞一下我们",
        "key":"V1001_GOOD"
      }]
    }]
}';
echo createMenu($data);

给微信公众号设置菜单, 验证成功。

#10 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-08-31 11:42:52

Screenshot_2020-08-31-11-35-51-403_com_tencent_mm.jpg


楼上两位说得对, 刚刚搞定了模板消息

代码全部是这个: https://www.jianshu.com/p/2ac8cba649a4

$ACCESS_TOKEN = '';//通过微信获取access_token接口 获取的token
$openid = '';//用户openid
$template_id = '';//配置的模板id
$url = '';//点击模板消息跳转的链接

$template = array(
    'touser' => $openid,
    'template_id' => $template_id,
    'url' => $url,
    'data' => array(
        'first' => array('value' => '恭喜你购买成功!', 'color' => "#173177"),
        'keyword1' => array('value' => '巧克力', 'color' => '#173177'),
        'keyword2' => array('value' => '39.8元', 'color' => '#173177'),
        'keyword3' => array('value' => '2014年9月22日', 'color' => '#173177'),
        'remark' => array('value' => '欢迎再次购买!', 'color' => '#173177'),)
);

$send_template_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $send_template_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($template));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
curl_close($ch);
return $res;

只改了配置, 就能给关注的微信号主动推送模板消息了。

#11 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-08-30 22:08:28

QQ图片20200830221131.jpg



cat wx1.php

<?php
function wx_log($log_msg)
{
        $log_filename = $_SERVER['DOCUMENT_ROOT']."/logs";
        if (!file_exists($log_filename))
        {
                // create directory/folder uploads.
                mkdir($log_filename, 0777, true);
        }
        $log_file_data = $log_filename.'/' . date('Y-m-d') . '.log';
        file_put_contents($log_file_data, $log_msg, FILE_APPEND);
        file_put_contents($log_file_data, "\n", FILE_APPEND);
}

define(TOKEN, "my_token");

$data = file_get_contents('php://input');

if(empty($data))
{
        //wx_log($GLOBALS['HTTP_RAW_POST_DATA']);

        wx_log('sign: ' . $_GET['signature']);
        wx_log($_GET['echostr']);
        wx_log($_GET['timestamp']);
        wx_log($_GET['nonce']);

        $signature = $_GET['signature'];//签名
        $echostr = $_GET['echostr'];
        $timestamp = $_GET['timestamp'];//时间戳
        $nonce = $_GET['nonce'];//随机数

        $arr = [$timestamp, $nonce, TOKEN];
        sort($arr, SORT_STRING);

        $str = sha1(implode($arr));//重新计算签名

        wx_log($str);

        if(($str == $signature) && ($str != ""))//如果签名吻合,那么给微信服务器回推消息
        {
                echo $echostr;
        }
}
else
{
        wx_log($data);

        $obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        wx_log('ToUserName:' . $obj->ToUserName);
        wx_log('FromUserName:' . $obj->FromUserName);
        wx_log('CreateTime:' . $obj->CreateTime);
        wx_log('MsgType:' . $obj->MsgType);
        wx_log('Content:' . $obj->Content);


        $ToUserName = $obj->ToUserName;
        $FromUserName = $obj->FromUserName;
        $MessageContent = $obj->Content;

        $xml_template = '<xml><ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>';

        if($MessageContent == '我是谁')
        {
                $xml_send = sprintf($xml_template, $FromUserName, $ToUserName, time(), 'text', '你是唯一的自己.');
        }
        else if($MessageContent == '你是谁')
        {
                $xml_send = sprintf($xml_template, $FromUserName, $ToUserName, time(), 'text', '我是无所不能的公众号');
        }
        else
        {
                $xml_send = sprintf($xml_template, $FromUserName, $ToUserName, time(), 'text', '你的问题我没有办法回答,去问周公吧.');
        }

        echo $xml_send;
        exit;
}

?>

这是一天的工作成果.

#12 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-08-30 21:07:32

看视频学来的 $GLOBALS[‘HTTP_RAW_POST_DATA’],

结果在我的网页服务器死活不显示,

一开始因为我输错了, 检查100遍之后, 发现还是没错.

网上一搜, 原来这个数组在php7已经不适应了,

新的接口是: $data = file_get_contents('php://input');

#13 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-08-30 20:47:11

楼顶那个是强行推送成功消息, 并没有验证签名:

这个是校验签名的 wx.php 代码:

<?php
function wx_log($log_msg)
{
        $log_filename = $_SERVER['DOCUMENT_ROOT']."/logs";
        if (!file_exists($log_filename))
        {
                // create directory/folder uploads.
                mkdir($log_filename, 0777, true);
        }
        $log_file_data = $log_filename.'/' . date('Y-m-d') . '.log';
        file_put_contents($log_file_data, $log_msg, FILE_APPEND);
        file_put_contents($log_file_data, "\n", FILE_APPEND);
}

define(TOKEN, "my_token");

wx_log('sign: ' . $_GET['signature']);
wx_log($_GET['echostr']);
wx_log($_GET['timestamp']);
wx_log($_GET['nonce']);

$signature = $_GET['signature'];//签名
$echostr = $_GET['echostr'];
$timestamp = $_GET['timestamp'];//时间戳
$nonce = $_GET['nonce'];//随机数

$arr = [$timestamp, $nonce, TOKEN];
sort($arr, SORT_STRING);

$str = sha1(implode($arr));//重新计算签名

wx_log($str);

if(($str == $signature) && ($str != ""))//如果签名吻合,那么给微信服务器回推消息
{
        echo $echostr;
}
?>

#14 Re: Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-08-30 15:16:14

然后呢, 然后当然是 启用配置,

启用该配置之后,  关注者微信 给 微信公众号发送的消息都传到了 wx.php

你可以继续观察 apache2 log,

cat /var/log/apache2/access.log:

127.0.0.1 - - [30/Aug/2020:00:13:04 -0700] "POST /wx.php?signature=75752c0a62a02d368d467fdeb0fa2d346ef9eab4&timestamp=1598771583&nonce=719528559&openid=oVEjzvmgLIF0oLHYccqGZnYyZ4r4 HTTP/1.1" 200 167 "-" "Mozilla/4.0"
127.0.0.1 - - [30/Aug/2020:00:13:16 -0700] "POST /wx.php?signature=877a7a65284aad0a74b4746fd92efb2e192aa7aa&timestamp=1598771596&nonce=665457187&openid=oVEjzvmgLIF0oLHYccqGZnYyZ4r4 HTTP/1.1" 200 167 "-" "Mozilla/4.0"

#15 Php/Nodejs/Web/HTML5/Javascript/微信开发/Python » 跟上时代,记录一下刚刚看视频学会的 php + 微信公众号开发 » 2020-08-30 14:32:04

QQ截图20200830142608.png





只要一点 [提交], 看网页服务器就会出现log记录 cat /var/log/apache2/access.log:

127.0.0.1 - - [29/Aug/2020:23:07:57 -0700] "GET /wx.php?signature=1f4142af46fa98cd30b5a57d3e6b8b14f01ea78f&echostr=7204982403406724733&timestamp=1598767677&nonce=1224769556 HTTP/1.1" 404 452 "-" "Mozilla/4.0"
127.0.0.1 - - [29/Aug/2020:23:09:29 -0700] "GET /wx.php?signature=66b48d050fdfee446a4ad94b489fb176ba86d402&echostr=8184609992026876859&timestamp=1598767769&nonce=1984465893 HTTP/1.1" 404 452 "-" "Mozilla/4.0"
127.0.0.1 - - [29/Aug/2020:23:09:36 -0700] "GET /wx.php HTTP/1.1" 404 452 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
127.0.0.1 - - [29/Aug/2020:23:11:59 -0700] "GET /wx.php HTTP/1.1" 200 167 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
127.0.0.1 - - [29/Aug/2020:23:12:15 -0700] "GET /wx.php?signature=918f4a236bcfd5f8f2b25369b85050411dda08a2&echostr=525327352018754495&timestamp=1598767935&nonce=813200003 HTTP/1.1" 200 186 "-" "Mozilla/4.0"
127.0.0.1 - - [29/Aug/2020:23:20:45 -0700] "GET /wx.php HTTP/1.1" 200 167 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27 MicroMessenger/6.5.5 NetType/WIFI Language/zh_CN"
127.0.0.1 - - [29/Aug/2020:23:25:23 -0700] "GET /wx.php?signature=7aa15240c3f687e0ab49b1934ad983652623ee7e&echostr=4353787308509460447&timestamp=1598768723&nonce=473211795 HTTP/1.1" 200 187 "-" "Mozilla/4.0"

只要新建 wx.php, 返回 echostr 即可:

<?php
        echo $_GET["echostr"];

?>

这样就会显示右上角 提交成功

页脚

工信部备案:粤ICP备20025096号 Powered by FluxBB

感谢为中文互联网持续输出优质内容的各位老铁们。 QQ: 516333132, 微信(wechat): whycan_cn (哇酷网/挖坑网/填坑网) service@whycan.cn