XzdFunc.php和TempFunc.php外加使用实例

2023-05-29  本文已影响0人  xueyueshuai
<?php

namespace app\api\library;
class XzdFunc
{
    /**
     * api 返回数据函数
     * @param (int)$code
     * @param (str)$msg
     * @param (arr)$data
     * @return (str) json的字符串
     */
    public static function msg($code, $msg = 'success', $data = []): \think\response\Json
    {



        header('Xzd-Code: ' . $code);
        header('Xzd-Msg: ' . rawurlencode($msg));
        header("Access-Control-Expose-Headers: Xzd-Code,Xzd-Msg");

        $code = (int)$code;
        $msg = (string)$msg;
        $data = (object)$data;
        // return json_encode(['code' => $code, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
        return json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }

    public static function myCurl($url, $post_arr_json_str = '', $seconds = 60, $headers = []): array
    {
        // 1 创建一个新cURL资源
        $ch = curl_init();

        // 2 设置配置
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $seconds); //设置超时
        curl_setopt($ch, CURLOPT_HEADER, false); //启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //0直接输出到浏览器  1字符串(不输出)
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $post_arr_json_str ? 'POST' : 'GET');
        curl_setopt($ch, CURLOPT_HEADER, true);


        // 如果是https的话,就加上这两句 // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);


        if ($headers) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        // 3 传参方式 和 参数
        // get传参
        // 写在$url后用'?'隔开键=值&键=值...

        // post传参
        // curl_setopt($ch, CURLOPT_POST, TRUE);
        // curl_setopt($ch, CURLOPT_POSTFIELDS,['a'=>1,'b'=>2]);      //方式1
        // curl_setopt($ch, CURLOPT_POSTFIELDS,'a=1&b=2');            //方式2
        if ($post_arr_json_str) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_arr_json_str); //方式1
        }

        $result = [];
        $result["error"] = false;
        // $result['response'] = '';
        $result['responseCode'] = null;
        $result['headerSize'] = 0;
        // $result["header"] = '';
        $result["body"] = '';

        try {
            $response = curl_exec($ch);
            if ($response === false) {
                throw new Exception(curl_error($ch));
            }
            // $result['response'] = $response;
            $result["responseCode"] = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $result["headerSize"] = $headerSize;

            // $result["header"] = substr($response, 0, $headerSize);
            $result["body"] = substr($response, $headerSize);

            // 关闭 curl 会话资源
            curl_close($ch);
        } catch (Exception $e) {
            $result["error"] = "CURL error: " . $e->getMessage();
        }



        return $result;

    }
}
<?php

namespace app\api\library;
use think\Env;

class TempFunc
{
    /**
     * api 返回数据函数
     * @param (int)$code
     * @param (str)$msg
     * @param (arr)$data
     * @return (str) json的字符串
     */
    public static function wxMiniProgramCodeToOpenid($code)
    {
        $appid = Env::get('wxProgram.appid');
        $secret = Env::get('wxProgram.secret');
        $js_code = $code;
        $res = XzdFunc::myCurl("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$js_code}&grant_type=authorization_code");

        if($res['error'] === false){
            $body = json_decode($res['body'],true);
            if(isset($body['openid'])){
                $openid = $body['openid'];
            }else{
                throw new \Exception($body['errmsg']);
            }
        }else{
            throw new \Exception('code兑换openid,请求错误');
        }

        return $openid;
    }
}
<?php

namespace app\api\controller;

use app\api\library\TempFunc;
use app\common\controller\Api;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function test()
    {
        try {
            $code = "0b1v8I0w3NbNE03IpT3w3SXe0T1v8I00";
            $openid = TempFunc::wxMiniProgramCodeToOpenid($code);
        } catch (\Throwable $exception) {
            $this->success($exception->getMessage(), null, 200);
        }

        $data = [];
        $data['openid'] = $openid;
        $this->success('返回成功', $data, 200);
    }

   

}

上一篇 下一篇

猜你喜欢

热点阅读