laravel 和 laravel-admin , EasyWeChat , WangEditor

**This blog mainly introduces the use of laravl and laravel-admin, EasyWeChat combined with the use of laravel, laravl-admin background call,

WangEditor rich text editor.

About the use of laravel and laravel-admin

First to see more documents it
probably is a process to go composer laravel frame and then install and configure the database laravl-admin official website documentation for installation laravel-admin framework

About laravel WeChat public account development based on EasyWeChat
verification token
use EasyWeChat\Factory;
class TokenController extends Controller
{
public function wxtoken(Request $request)
{
/* $signature = $request->input('signature');
$timestamp = $request ->input('timestamp');
$nonce = $request->input('nonce');
$echoStr = $request->input('echostr');
if ($this->checkSignature($signature, $timestamp , $nonce)) {
ob_end_clean(); //The buffer must be cleared

        return $echoStr;
    } else {
        return 'Token verification failed.';
    }*/
    $options = [
        'app_id'    => '####',
        'secret'    => '###',
        'token'     => 'loveerys',//和公众号后台匹配的token  确保公众号访问 一至
        'aes_key' => '####',
        'log' => [
            'level' => 'debug',
            'file'  => '/tmp/easywechat.log',
        ],
        'oauth' => [
            'scopes'   => ['snsapi_userinfo'],
            'callback' => '/serve',
        ],
    ];

    $app = Factory::officialAccount($options); //调取EasyWeChat公众号类
    $app->server->push(function ($message) {
      //  $message['FromUserName']; // 用户的 openid
        $message_text =Reply::find(1);
        return "$message_text->text";
    });            //自动回复
   /* $message = $app->server->getMessage();
    var_dump($message);exit;*/
    $response = $app->server->serve();
    return $response;

}
/**
 * 微信官方提供的验签方法
 *
 * @param $signature
 * @param $timestamp
 * @param $nonce
 * @return bool
 */
private function checkSignature($signature, $timestamp, $nonce)
{
    $token = 'loveerys';
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1($tmpStr);

    if ($tmpStr == $signature) {

        return true;
    } else {
        return false;
    }
}

}

laravl authorized webpage to obtain WeChat user information

/ access /
public function test(Request $request){
$appid='##';
$redirect_uri = urlencode (' http://###.###.#/mobile/user ');
$url =" https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect ";
header("Location:".$ url);

}
/*跳转*/
public function  user(){
    $appid = "#####";
    $secret = "##";
    $code = $_GET["code"];
    //access_token
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
    $token =$this->getJson($url);
    //openid
    $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
    $oauth2 = $this->getJson($oauth2Url);
    $access_token = $token["access_token"];
    $openid = $oauth2['openid'];
    $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
    $userinfo = $this->getJson($get_user_info_url);
    var_dump($userinfo);exit;
}

public function getJson($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}

Laravel-admin introduces a third-party WangEditor text editor to upload text and pictures.
First go to WangEditor to download the WangEditor package. I use wangEditor-3.0.16

Put the downloaded package in the laravel framework vendor directory

Then create the
content of WangEditor.php WangEditor.php under damin/create Extensions folder
<?php
namespace App\Admin\Extensions;
use Encore\Admin\Form\Field;
class WangEditor extends Field
{
protected $view ='admin.wang -editor';

protected static $css = [
    '/vendor/wangEditor-3.0.16/release/wangEditor.min.css',
];
protected static $js = [
    '/vendor/wangEditor-3.0.16/release/wangEditor.min.js',
];
public function render()
{
    $name = $this->formatName($this->column);

    $this->script = <<<EOT

var E = window.wangEditor
var editor = new E('#{$this->id}');
editor.customConfig.uploadFileName = 'mypic[]';
editor.customConfig.uploadImgHeaders = {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
editor.customConfig.zIndex = 0;
editor.customConfig.uploadImgServer = '/index.php/uploadFile';
editor.customConfig.onchange = function (html) {
$('input[name=$name]').val(html);
}
editor.customConfig.uploadImgHooks = {
customInsert: function (insertImg, result, editor) {
if (typeof(result.length) != "undefined") {
for (var i = 0; i <= result.length - 1; i++) {
var j = i;
var url = result[i].newFileName;
insertImg(url);
}
toastr.success(result[j]['info']);
}
switch (result['ResultData']) {
case 6:
toastr.error("Up to 4 pictures can be uploaded");
break;
case 5:
toastr. error("Please select a file");
break;
case 4:
toastr.error("Upload failed");
break;
case 3:
toastr.error(result['info']);
break;
case 2:
toastr.error ("File type is illegal");
break;
case 1:
toastr.error(result['info']);
break;
}
}
}
editor.create();
EOT;
return parent::render();
}
}
Note :
Route::post('/uploadFile', [UploadsController::class, 'uploadImg']);//Upload the picture after the route is built, write the text editor and upload the picture

Create UploadsController under http/controller/, pay attention to case

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UploadsController extends Controller
{
public function uploadImg(Request $request)
{

    $file = $request->file("mypic");

    if (!empty($file)) {
        foreach ($file as $key => $value) {
            $len = $key;
        }
        if ($len > 25) {
            return response()->json(['ResultData' => 6, 'info' => '最多可以上传25张图片']);
        }
        $m = 0;
        $k = 0;
        for ($i = 0; $i <= $len; $i++) {
            // $n 表示第几张图片
            $n = $i + 1;
            if ($file[$i]->isValid()) {
                if (in_array(strtolower($file[$i]->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
                    $picname = $file[$i]->getClientOriginalName();//获取上传原文件名
                    $ext = $file[$i]->getClientOriginalExtension();//获取上传文件的后缀名
                    // 重命名
                    $number = mt_rand(1000000000,9999999999);
                    $filename = time() .$number . "." . $ext;

                    if ($file[$i]->move("uploads/images", $filename)) {
                        $newFileName = '/' . "uploads/images" . '/' . $filename;
                        $m = $m + 1;
                        // return response()->json(['ResultData' => 0, 'info' => '上传成功', 'newFileName' => $newFileName ]);
                    } else {
                        $k = $k + 1;
                        // return response()->json(['ResultData' => 4, 'info' => '上传失败']);
                    }
                    $msg = $m . "张图片上传成功 " . $k . "张图片上传失败<br>";
                    $return[] = ['ResultData' => 0, 'info' => $msg, 'newFileName' => $newFileName];
                } else {
                    return response()->json(['ResultData' => 3, 'info' => '第' . $n . '张图片后缀名不合法!<br/>' . '只支持jpeg/jpg/png/gif格式']);
                }
            } else {
                return response()->json(['ResultData' => 1, 'info' => '第' . $n . '张图片超过最大限制!<br/>' . '图片最大支持2M']);
            }
        }
    } else {
        return response()->json(['ResultData' => 5, 'info' => '请选择文件']);
    }
    return $return;
}

}

Guess you like

Origin blog.51cto.com/kangjunfei/2548248