1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- <?php
- namespace App\Handlers;
- use GuzzleHttp\Client;
- use Illuminate\Support\Facades\Cache;
- class WechatMessageHandler {
- public function new(){
- $client=new Client();
- $client_id = config('config.appid');
- $secret = config('config.appsecret');
- $url = 'https://api.weixin.qq.com/cgi-bin/token';
- $array = [
- 'query' => [
- 'appid' => $client_id,
- 'secret' => $secret,
- 'grant_type' => 'client_credential',
- ],
- ];
- $response = $client->request('GET', $url, $array);
- $ad = json_decode($response->getBody()->getContents());
- $token=$ad->access_token;
- Cache::put('wechattoken',$token);
- }
- public function news($openid,$template_id,$data,$k=0){
- $client=new Client();
- $url='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send';
- $token=Cache::get('wechattoken');
- if (!$token){
- $this->new();
- $token=Cache::get('wechattoken');
- }
- $array = [
- 'query'=>[
- 'access_token' => $token,
- ],
- 'json' => [
- 'touser' => $openid,
- 'mp_template_msg'=>[
- 'appid'=>env('APPID'),
- 'template_id' => $template_id,
- 'url'=>'',
- "miniprogram"=>[
- "appid"=>config('config.appid'),
- "pagepath"=>"/pages/index/index"
- ],
- 'data'=>$data
- ]
- ],
- ];
- $response = $client->request('POST', $url, $array);
- $ad = json_decode($response->getBody()->getContents());
- if ($ad->errcode==0){
- return 200;
- }else{
- Cache::forget('wechattoken');
- $this->new();
- $k=$k+1;
- if ($k==2){
- return 300;
- }
- $code=$this->news($openid,$template_id,$data,$k);
- if ($code==200){
- return 200;
- }
- return 300;
- }
- }
- }
|