Yii using easywechat to realize the method of getting user’s openid by applet

Time:2020-11-27

1: Installing easywechat

Easywechat document: https://www.easywechat.com/docs

When using easywechat in Yii, there are two extensions that can be used: jianyan74 / yii2 easy wechat for easywechat 4. X, and Max Wen / yii2 easy wechat for easywechat 3. X. here I use jianyan74 / yii2 easy wechat extension


composer require jianyan74/yii2-easy-wechat

2: Configure easywechat

1: In config/ main.php Add the

'wechat' => [ 
  'class' => 'jianyan\easywechat\Wechat', 
  'useroptions' = > [], // user identity class parameters 
  'sessionparam '= >'wechatuser', // wechat user information will be stored in the session in this key 
  'returnUrlParam' => '_ Wechatreturnurl ', // returnurl is stored in the session 
  'rebinds' = > [// custom service module 
  ] 
],

2: In config/ params.php File (here I only configure the applet. For other configurations, please refer to the official website of easywechat)

//Wechat applet configuration 
'wechatMiniProgramConfig' => \[ 
  'app\_id' => 'XXXX', 
  'secret' => 'XXXX', 
  //Here are the options 
  //Specifies the type of return result of API call: array (default) / collection / object / raw / custom class name 
  'response\_type' => 'array', 
  //Log configuration 
  'log' => \[ 
    'level' => 'debug', 
    'file' => dirname(dirname(\_\_DIR\_\_)) . '/api/runtime/wechat.log', 
  \], 
\],

3: Get the user’s openid according to the code from the front end

$request = Yii::$app->getRequest(); 
$miniProgram = Yii::$app->wechat->miniProgram; 
$code2Session = $miniProgram->auth->session($request->post('code', '')); 
$openid = $code2session \ ['openid '\]; // user's openid 
$sessionKey = $code2Session\['session\_key'\];//session\_key

4: Code value acquisition on applet side

It can be used on the applet side wx.login Method to get the code value

wx.login({ 
 success (res) { 
  if (res.code) { 
   //Get code 
   console.log(res.code) 
   }) 
  } else { 
   console.log ('login failed! ' +  res.errMsg ) 
  } 
 } 
})

This article introduces the method of Yii using easywechat to obtain users’ openid. For more related Yii applets to get users’ openid content, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!