laravel, laravel-admin, EasyWeChat, WangEditor

** Este blog presenta principalmente el uso de laravl y laravel-admin, EasyWeChat combinado con el uso de laravel, laravl-admin background call,

Editor de texto enriquecido WangEditor.

Sobre el uso de laravel y laravel-admin

Primero para ver más documentos,
probablemente sea un proceso ir compositor laravel frame y luego instalar y configurar la base de datos laravl-admin documentación del sitio web oficial para la instalación laravel-admin framework

Acerca del desarrollo de la cuenta pública de laravel WeChat basado en el token de
verificación EasyWeChat
use EasyWeChat \ Factory;
class TokenController extiende 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 ($ firma, $ timestamp , $ nonce)) {
ob_end_clean (); // El búfer debe limpiarse

        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 autorizó la página web para obtener información de usuario de WeChat

/ acceso /
prueba de función pública (Solicitar $ solicitud) {
$ 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 ("Ubicación:". $ 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;
}

función pública 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);
$ salida = curl_exec ($ ch);
curl_close ($ ch);
return json_decode ($ salida, verdadero);
}

Laravel-admin presenta un editor de texto WangEditor de terceros para cargar texto e imágenes.
Primero vaya a WangEditor para descargar el paquete WangEditor. Yo uso wangEditor-3.0.16

Coloque el paquete descargado en el directorio de proveedores de laravel framework

Luego cree el
contenido de WangEditor.php WangEditor.php en la carpeta damin / create Extensions
<? Php
namespace App \ Admin \ Extensions;
use Encore \ Admin \ Form \ Field; la
clase WangEditor extiende 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': $ ('entrada [nombre = "_ 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']) {
caso 6:
toastr.error ("Se pueden cargar hasta 4 imágenes");
romper;
caso 5:
toastr. error ("Seleccione un archivo");
interrupción;
caso 4:
toastr.error ("Error al cargar");
interrupción;
caso 3:
toastr.error (resultado ['información']);
interrupción;
caso 2:
toastr.error ("El tipo de archivo es ilegal");
break;
case 1:
toastr.error (result ['info']);
break;
}
}
}
editor.create ();
EOT;
return parent :: render ();
}
}
Nota :
Route :: post ('/ uploadFile', [UploadsController :: class, 'uploadImg ']); // Sube la imagen después de construir la ruta, escribe el editor de texto y sube la imagen

Cree UploadsController en http / controller /, preste atención al caso

<? php
espacio de nombres App \ Http \ Controllers;
use Illuminate \ Http \ Request;

class UploadsController extiende Controller
{
función pública 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;
}

}

Supongo que te gusta

Origin blog.51cto.com/kangjunfei/2548248
Recomendado
Clasificación