<?php

namespace api\modules\v1\controllers\user;

use yii\rest\Controller;
use yii\filters\VerbFilter;
use api\modules\v1\models\WechatUser;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\ServerErrorHttpException;

/**
 * Country Controller API
 *
 * @author Budi Irawan <deerawan@gmail.com>
 */
class UserIdController extends Controller
{
    const WECHAT_SECRET = "8845976fedc7523a3e0079f9291abec5";
    const WECHAT_ID = "wxedae9261492ca0c2";
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['verbs'] = [
            'class' => VerbFilter::className(),
            'actions' => [
                'getFromWechatLogin' => ['post', 'put'],
            ],
        ];
        return $behaviors;
    }
    
    public function actionGetFromWechatLogin()
    {
      $postData = \Yii::$app->request->post();
      if (!isset($postData['code'])) throw new BadRequestHttpException("Missing parameter 'code'")
      $params = [
      	      'code' => $postData['code'],
      	      'secret' => WECHAT_SECRET,
	      'appid' =>  WECHAT_ID,
	      'grant_type' => "authorization_code"
      ];
      
      $ch = curl_init();

     curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, 
       http_build_query($params));
    //curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // this is just a quick fix; for a long term solution, see https://stackoverflow.com/questions/4372710/php-curl-https that prevents MITM attack
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);

    curl_close($ch);
      // Send params to https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code 
      
      if (isset($response['errmsg'])) throw new BadRequestHttpException("Wechat Error: " . $response['errmsg']);
      // return $response['openid']
    }

}