Technology Selection

  • Laravel
  • EasyWechat

Implementation

Create a new Laravel project, configure the database parameters, and introduce the Easywechat extension

Create a data table

php artisan make:model Wechat -m

Initialize WeChat related data fields

public function up()
    {
        Schema::create('wechats', function (Blueprint $table) {
            $table->increments('id');
            $table->string('aid')->nullable();

            $table->string('wechat_app_id')->nullable(); //WeChat official account setting parameters
            $table->string('wechat_secret')->nullable();
            $table->string('wechat_token')->nullable();
            $table->string('wechat_aes_key')->nullable();

            $table->string('pay_mch_id')->nullable(); //WeChat payment setting parameters
            $table->string('pay_api_key')->nullable();
            $table->string('pay_cert_path')->nullable();
            $table->string('pay_key_path')->nullable();

            $table->string('op_app_id')->nullable(); //WeChat open platform setting parameters
            $table->string('op_secret')->nullable();
            $table->string('op_token')->nullable();
            $table->string('op_aes_key')->nullable();

            $table->string('work_corp_id')->nullable(); //WeChat enterprise account setting parameters
            $table->string('work_agent_id')->nullable();
            $table->string('work_secret')->nullable();
            $table->timestamps();
        });
    }

App\Handlers Create a helper function WechatConfigHandler.php file

<?php

namespace App\Handlers;

use App\Wechat;
use EasyWeChat\Factory;

class WechatConfigHandler
{
    //[1-1] WeChat Official Account Settings
    public function app_config($account)
    {
        $wechat = Wechat::where('aid',$account)->first();
        if (!$wechat) {
            return $config = [];
        }
        $config = [
            'app_id' => $wechat->wechat_app_id, // AppID
            'secret' => $wechat->wechat_secret, // AppSecret
            'token' => $wechat->wechat_token, // Token
            'aes_key' => $wechat->wechat_aes_key, // EncodingAESKey, in compatibility and security mode, please be sure to fill it out! ! !
            'response_type' =>'array',
            'oauth' => [
                //'scopes' => array_map('trim', explode(',', env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_SCOPES','snsapi_userinfo'))),
                'scopes' =>'snsapi_userinfo',
                //'callback' => env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_CALLBACK','/oauth_callback'),
                'callback' =>'/oauth_callback/'.$account,
                ],
            'log' => [
                'level' =>'debug',
                'file' => storage_path('logs/wechat.log'), //This must be present, or if there is a problem with debugging, you will not find the reason
            ],
        ];
        return $config;
    }

    //[1-2] Generate WeChat official account related
    public function app($account)
    {
        $app = Factory::officialAccount($this->app_config($account));
        return $app;
    }

    //[2-1] WeChat payment settings
    public function pay_config($account)
    {
        $wechat = Wechat::where('aid',$account)->first();
        if (!$wechat) {
            return $config = [];
        }
        $config = [
            'app_id' => $wechat->wechat_app_id, // AppID
            'secret' => $wechat->wechat_secret, // AppSecret
            'mch_id' => $wechat->pay_mch_id,
            'key' => $wechat->pay_api_key, // API key
            // If you need to use sensitive interfaces (such as refunding, sending red envelopes, etc.), you need to configure the API certificate path (login to the merchant platform to download the API certificate)
            'cert_path' => $wechat->pay_api_key, // XXX: absolute path! ! ! !
            'key_path' => $wechat->pay_api_key, // XXX: absolute path! ! ! !
            'notify_url' =>'Default order callback address', // You can also set it separately when placing an order and want to override it
        ];
        return $config;
    }

    //[2-2] Generate WeChat payment related
    public function pay($account)
    {
        $pay = Factory::payment($this->pay_config($account));
        return $pay;
    }

    //[3-1] WeChat Mini Program Settings
    public function mini_config($account)
    {
        $wechat = Wechat::where('aid',$account)->first();
        if (!$wechat) {
            return $config = [];
        }
        $config = [
            'app_id' => $wechat->wechat_app_id, // AppID
            'secret' => $wechat->wechat_secret, // AppSecret
            'response_type' =>'array',
        ];
        return $config;
    }

    //[3-2] WeChat applet related
    public function miniProgram($account)
    {
        $miniProgram = Factory::miniProgram($this->mini_config($account));
        return $miniProgram;
    }

    //[4-1] WeChat open platform setting parameters
    public function opconfig($account)
    {
        $wechat = Wechat::where('aid',$account)->first();
        if (!$wechat) {
            return $config = [];
        }
        $config = [
            'app_id' => $wechat->op_app_id,
            'secret' => $wechat->op_secret,
            'token' => $wechat->op_token,
            'aes_key' => $wechat->op_aes_key
        ];
        return $config;
    }

    //[4-2] WeChat open platform related
    public function openPlatform($account)
    {
        $openPlatform = Factory::openPlatform($this->opconfig($account));
        return $openPlatform;
    }

    //[5-1] WeChat enterprise account setting parameters
    public function workconfig($account)
    {
        $wechat = Wechat::where('aid',$account)->first();if (!$wechat) {
            return $config = [];
        }
        $config = [
            'corp_id' => $wechat->work_corp_id,
            'agent_id' => $wechat->work_agent_id,
            'secret' => $wechat->work_secret,

            'response_type' =>'array',
        ];
        return $config;

    }

    //[5-2] WeChat enterprise account related
    public function work($account)
    {
        $work = Factory::work($this->workconfig($account));
        return $work;
    }
}

WeChat Controller (WeChat public platform docking)

php artisan make:controller WechatController
protected $wechat;

public function __construct(WechatConfigHandler $wechat)
{
    $this->wechat = $wechat;
}

public function serve($account)
{
    $app = $this->wechat->app($account);
    $app->server->push(function($message){
        switch ($message['MsgType']) {
            case'event':
                if ($message['Event'] =='subscribe') {
                    return'Welcome to follow Elephdev! ';
                }
                break;
            case'text':
                return'Received text message';
                break;
            case'image':
                return'Receive picture message';
                break;
            case'voice':
                return'Received voice message';
                break;
            case'video':
                return'received video message';
                break;
            case'location':
                return'Receive coordinate message';
                break;
            case'link':
                return'Received link message';
                break;
            // ... other news
            default:
                return'Receive other messages';
                break;
        }
    });
    $response = $app->server->serve();
    return $response;
}

public function oauth_callback($account)
{
    $app = $this->wechat->app($account);
    $user = $app->oauth->user();
    session(['wechat.oauth_user' => $user->toArray()]);
    //No matter which page the user login status is detected, the session value must be written: target_url
    $targetUrl = session()->has('target_url')? session('target_url'):'/';
    //header('location:'. $targetUrl);
    return redirect()->to($targetUrl);
}

VerifyCsrfToken.php in the Middleware folder to modify the route to ignore

protected $except = [
    'wechat/*'
];

Usage example

$app = $this->wechat->app($account); //Official account
$app = $this->wechat->pay($account); //WeChat Pay
$app = $this->wechat->miniProgram($account); //WeChat Mini Program
$app = $this->wechat->work($account); //Enterprise account application

WeChat public platform developer option settings

http://www.xxx.com/wechat/1

Routing configuration

Route::any('wechat/{account}','WechatController@serve');
Route::any('/oauth_callback/{account}','WechatController@oauth_callback');

wechat/1 is in the database, aid is the official account of 1 to access, you can test other functions yourself

Summary

  1. Create a public account parameter table
  2. Create WeChat Controller
  3. Create a helper function
  4. Configure routing
  5. Set routing ignore
Likes(0)

Comment list count 0 Comments

No Comments