123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace app\components\OpenAuth\core;
- use \Exception;
- use app\common\helpers\Session;
- use Yii;
- class Wxclient {
- private $APIMap;
- function __construct() {
- $this->oauth = new WX();
- /*
- * 初始化APIMap
- * 加#表示非必须,无则不传入url(url中不会出现该参数), "key" => "val" 表示key如果没有定义则使用默认值val
- * 规则 array( baseUrl, argListArr, method)
- */
- $this->APIMap = array(
- "get_user_info" => array(
- "https://api.weixin.qq.com/sns/userinfo",
- array("format" => "json"),
- "GET"
- )
- );
- }
- //调用相应api
- private function _applyAPI($arr, $argsList, $baseUrl, $method) {
- $pre = "#";
- $keysArr = array(
- "access_token" => Session::get('wx_token.access_token'),
- "openid" => Session::get('wx_token.openid')
- );
- if ($method == "POST") {
- $this->oauth->ssl_verifypeer = 0;
- $response = $this->oauth->https_request($baseUrl, null, $keysArr);
- } else if ($method == "GET") {
- $baseUrl.="?".http_build_query($keysArr);
- $response = $this->oauth->https_request($baseUrl);
- }
- return $response;
- }
- public function __call($name, $arg) {
- //如果APIMap不存在相应的api
- if (empty($this->APIMap[$name])) {
- throw new Exception("不存在的API: <span style='color:red;'>$name</span>");
- }
- //从APIMap获取api相应参数
- $baseUrl = $this->APIMap[$name][0];
- $argsList = $this->APIMap[$name][1];
- $method = isset($this->APIMap[$name][2]) ? $this->APIMap[$name][2] : "GET";
- if (empty($arg)) {
- $arg[0] = null;
- }
- //对于get_tenpay_addr,特殊处理,php json_decode对\xA312此类字符支持不好
- $responseArr = $this->obj2array($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
- //检查返回ret判断api是否成功调用
- if ($responseArr['ret'] == 0) {
- return $responseArr;
- } else {
- throw new Exception($responseArr['msg']);
- }
- }
- /**
- * 多级对象转数组
- * @param obj $object 待转换的对象
- * @return array
- */
- private function obj2array($object = NULL) {
- $array = (array) $object;
- foreach ($array as $key => $val) {
- //判断是否为对象或数组,因为数组中可能还会存在对象
- if (is_object($val) || is_array($val)) {
- $val = obj2array($val);
- }
- $array[$key] = $val;
- }
- return $array;
- }
- //php 对象到数组转换
- private function objToArr($obj) {
- if (!is_object($obj) && !is_array($obj)) {
- return $obj;
- }
- $arr = array();
- foreach ($obj as $k => $v) {
- $arr[$k] = $this->objToArr($v);
- }
- return $arr;
- }
- public function get_access_token() {
- return Session::get('wx_token.access_token');
- }
- //简单实现json到php数组转换功能
- private function simple_json_parser($json) {
- $json = str_replace("{", "", str_replace("}", "", $json));
- $jsonValue = explode(",", $json);
- $arr = array();
- foreach ($jsonValue as $v) {
- $jValue = explode(":", $v);
- $arr[str_replace('"', "", $jValue[0])] = (str_replace('"', "", $jValue[1]));
- }
- return $arr;
- }
- }
|