laravel配置微信服务器详细步骤 - 小众知识

laravel配置微信服务器详细步骤

2020-08-19 08:38:22 苏内容
  标签: laravel/微信
阅读:4955

基本信息

  • laravel5.4
  • 西部数码云服务器
  • 微信开放平台测试号

laravel开发重要的是路由,请求的大多数是POST和GET,在微信开发中需要注意的是:微信验证token的请求是GET方式,但是真正介入微信服务器采用的是POST方式,所以微信后台配置验证接口时候,要使用GET方式,验证成功配置完成再改成POST方式。

路由:

Route::group(['prefix' => 'backed', 'namespace' => 'Backeds'], function () {

    Route::get('weixin/token', 'WeixinController@token');
    Route::post('weixin/token', 'WeixinController@token');
    Route::any('weixin/api', 'WeixinController@api');//下面有具体方法代码});

laravel中还有一个需要注意的是中间件的概念,中间件是所有请求都需要经过验证才能分发给相应的控制器的玩意.laravel中POST提交都必须包含csrf防止跨域攻击的,在微信开发接口中需要关闭:
打开:app\Http\Middleware\VerifyCsrfToken.php

<?phpnamespace App\Http\Middleware;use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;class VerifyCsrfToken extends BaseVerifier{

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'weixin/api',
    ];}

接下来在对应的Controller中创建WeixinController.php

php artisan make:controller WeixinController

<?phpnamespace App\Http\Controllers\Backeds;use DB;use App\Http\Requests;use Illuminate\Http\Request;use App\Http\Controllers\Controller;class WeixinController extends Controller{

     //验证消息
    public function api()
     {
         $echoStr = $_GET["echostr"];
         if($this->checkSignature()){
             echo $echoStr;
             exit;
         }
     }
     //检查签名
     private function checkSignature()
     {
         $signature = $_GET["signature"];
         $timestamp = $_GET["timestamp"];
         $nonce = $_GET["nonce"];
         $token = "weixin";//可以随便填,只要和后台添加的一样就行
         $tmpArr = array($token, $timestamp, $nonce);
         sort($tmpArr, SORT_STRING);
         $tmpStr = implode($tmpArr);
         $tmpStr = sha1($tmpStr);
         if($tmpStr == $signature){
             return true;

         }else{
             return false;
         }
     }}

到此为止,打开微信公众号后台,开始配置微信服务器

配置URL:http://wechat.xhqlzj.com/backed/weixin/api
配置Token:weixin(Token要和WeixinController中checkSignature方法里面定义的token一样)

搞定


我眼睛看着验证信息没错,输出的echostr跟get提交来的一模一样,但是还是会出错。忍无可忍,一直无法搞定。

 

自己做开发也算基本上路了,还在这种坑吃亏,有点不服,最后查看日志,一点点搞定。

以下是我解决问题的办法:

1.网上有人说是header要设置utf-8,我也设置了,不行;

2.有人说可能是没有日志写入权限,导致信息能正常,但是页面代码不正常,打开console,发现,网页头显示500,麻蛋,这是服务器错误啊。

估计是腾讯一旦判断到你的500代码,就不继续了。

最后检查,发现是自己的服务器日志目录权限不足,无法写入日志!

就是这个原因,导致我浪费很多小时。

最后,我把验证微信公众号的token分享给各位兄弟,希望大家不要踩坑。

$token=’请填写你的公众号token’;

$timestamp = $_GET[‘timestamp’];
$nonce = $_GET[‘nonce’];
$signature = $_GET[‘signature’];
$array = array($timestamp,$nonce,$token);
sort($array);

//2.将排序后的三个参数拼接后用sha1加密
$tmpstr = implode(”,$array);
$tmpstr = sha1($tmpstr);

//3. 将加密后的字符串与 signature 进行对比, 判断该请求是否来自微信
if($tmpstr == $signature)
{
echo $_GET[‘echostr’];
}
return false;

另外,提醒各位兄弟,配置信息再微信测试号配置会好些,即便错了也不用每次都扫描二维码,累死人。

微信测试号地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login



微信开发准备工作

1、申请公众号测试账号地址,先注册账号


http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

2、更改接口信息配置的 Token 与 URL 地址



注:该 URL 是直接指向到具体能访问到的地址。


3、设置 JS 安全域名与设置网页授权回调地址



功能列表 -- 网页服务






4、开始接入微信验证 Token


<?php

namespace Test;


class TestController extends Controller 

{

    public function tokenSignature()

    {

        $timestamp = $_GET['timestamp'];

        $nonce = $_GET['noonce'];

        $token = 'sxs-hd'; //该处的值应该和第二条的TOKEN值一样

        $signature = $_GET['signature'];

        $array = array($timestamp, $nonce, $token);

        sort($array);

        //排序之后的数据拼接好使用sha1加密

        $tmpstr = implode('', $array);

        $tmpstr = sha1($tmpstr);

        //将加密后的字符串与singature进行对比,判断是否来自微信请求

        if ($tmpstr == $signature) {

            exit($_GET['echostr']);

        }

    }

}

5、获取自身的 access_token 值


<?php

    public function get_access_token()

    {

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='. self::APP_ID .'&secret=' . self::APP_SECRET;

        $token = file_get_contents($url);

        var_dump($token);


        //正常返回

        {

            "access_token":"ACCESS_TOKEN",

            "expires_in":7200

        }

        //失败返回

        {

            "errcode":40013,

            "errmsg":"invalid appid"

        }

    }

6、获取用户网页身份授权


第一步:用户同意授权,获取 code 值

<?php

$params = http_build_query([

    'appid' => '你的APPID',

    'redirect_uri => urlencode('https://mm.shaxiaoseng.com/Test/code'), //获取之后回调地址

    'response_type' => 'code',

    'scope' => 'snsapi_base',

    'state' => 123

]);

$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . $params . '#wechat_redirect';

#把上面的url在微信客户端打开就能看到返回的code值

第二步:通过 code 换取网页授权 access_token


//根据第一步获取到的code并回调到本方法

public function code()

{

    #根据拿到的code值去访问用户的access_token令牌

    $params = http_build_query([

            'appid' => 'APPID',

            'secret' => 'APP_SECERT',

            'code' => $_GET['code'],

            'grant_type' => 'authorization_code'

    ]);

    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . $params;

    $result = file_get_contents($url);


    var_dump($result);


    //正确返回

    { 

            "access_token":"ACCESS_TOKEN",

            "expires_in":7200,

            "refresh_token":"REFRESH_TOKEN",

            "openid":"OPENID",

            "scope":"SCOPE" 

    }

}

第三步:刷新 access_token 令牌

第四步:拉取用户信息

第五步:检验授权凭证 (access_token) 是否有效

其它的开发可以直接查看微信官方手册 [手册地址]


https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

 


扩展阅读
相关阅读
© CopyRight 2010-2021, PREDREAM.ORG, Inc.All Rights Reserved. 京ICP备13045924号-1