php獲取小程序碼的實現代碼(B類接口)

 更新時間:2020-06-14 04:45:13   作者:佚名   我要評論(0)

效果圖

生成小程序碼的php代碼


public function qrcode(){
$member_id = session('id');
if(empty($member_id)) $this->error('請先登錄');

//推廣

效果圖

生成小程序碼的php代碼

public function qrcode(){
    $member_id = session('id');
    if(empty($member_id)) $this->error('請先登錄');
 
    //推廣二維碼
    $member = model('Member')->where('id',$member_id)->find();
    if($member['is_share'] && $member['share_qrcode']){
      $litpic  = $member['share_qrcode'];
    }else{
      header('content-type:image/jpg');//加載速度快
      // 生成小程序碼
      $wechatObj =  new \Wechat();//這是個類 這里有小程序appid和密碼
      $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$wechatObj->getAccessToken();
 
      $page = 'pages/index/index';
      $scene = 'share_id='.$member_id;
      $path = './upload/qrcode/'.$member_id.'.jpg';
       
    $postData = array();
    $postData['page'] = $page;
      $postData['scene'] = $scene;
      $data = json_encode($postData);
       
      $result = $this->api_notice_increment($url,$data);
      $image = 'data:image/jpg;base64,' . base64_encode($result);
       
      $other_result = $result;
       
      $file = fopen($path,"w");//打開文件準備寫入
    fwrite($file,$other_result);//寫入
    fclose($file);//關閉
       
      //return $result;
      $litpic  = $path;
      $litpic = ltrim($litpic,'.');
      //寫入數據庫
      $member->save(['share_qrcode'=>$litpic,'is_share'=>1]);
    }
 
    //推廣人數
    $path_member = model('Member')->where('path',$member_id)->field('id,name,litpic,add_time')->select();
    $path  = [];
    foreach($path_member as $v){
      $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
      $path[]   = $v;
    }
    $data  = [
      'litpic'  => $litpic,
      'path'   => $path,
    ];
    return json($data);
 
 
  }
   
   
  public function api_notice_increment($url,$data){
    //return $data;
    $curl = curl_init(); // 啟動一個CURL會話
    //$header = "Accept-Charset: utf-8";
    curl_setopt($curl, CURLOPT_URL, $url); // 要訪問的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 對認證證書來源的檢測
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 從證書中檢查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //解決數據包大不能提交
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自動設置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 發送一個常規的Post請求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的數據包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 設置超時限制防止死循
    curl_setopt($curl, CURLOPT_HEADER, 0); // 顯示返回的Header區域內容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 獲取的信息以文件流的形式返回
 
    $tmpInfo = curl_exec($curl); // 執行操作
    if (curl_errno($curl)) {
      echo 'Errno'.curl_error($curl);
    }
    curl_close($curl); // 關鍵CURL會話
    return $tmpInfo; // 返回數據
      
  }
   
 
function api_notice_increment($url,$data)
{
  $curl = curl_init();
  $a = strlen($data);
  $header = array("Content-Type: application/json; charset=utf-8","Content-Length: $a");
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($curl,CURLOPT_POST,1);
  curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
  curl_setopt($curl, CURLOPT_HEADER, 0);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $res = curl_exec($curl);
  curl_close($curl);
  return $res;
 
}

小程序端獲取二維碼中帶的參數

/**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function(option) {
    console.log(option)
    if(option.id){
     this.setData({ id: option.id });
     this.data.business_id = option.id;
     this.loadData(option.id);
    }
 
    //接受二維碼掃碼并獲取二維碼中的參數
    if (option.scene){
     const ids = decodeURIComponent(option.scene).split('=')[1];
     console.log("ids", ids);
     this.setData({ id: ids });
     this.data.business_id = ids;
     this.loadData(ids);
    }
     
    
  },

補充上wechat類

<?php
 
class Wechat
{
  // +----------------------------------------------------------------------
  // |    參數
  // +----------------------------------------------------------------------
  public $table;
  public $where_web;
  public $wechatId;
  public $wechatToken;
  public $wechatAppid;
  public $wechatAppsecret;
  public $wechatMchid;
  public $wechatPrivatekey;
  public $wechatAccessToken;
  public $wechatAccessTokenTime;
  public $wechatJsapiTicket;
  public $wechatJsapiTicketTime;
 
 
 
// +----------------------------------------------------------------------
// |  自動加載
// +----------------------------------------------------------------------
  public function __construct() {
 
 
 
    //測試
    /*$this->wechatId            = 1;
    $this->wechatAppid          = 'wx1161dbcdd18c52c2';
    $this->wechatAppsecret        = 'f373410716a198feb462182c69facb8a';
    $this->wechatMchid          = 1493574822;
    $this->wechatPrivatekey        = md5(123);
    */
    //客戶appid
    $this->wechatId            = 1;
    $this->wechatAppid          = 'your appid';
    $this->wechatAppsecret        = 'your appsecret';
    $this->wechatMchid          = 商戶號;
    $this->wechatPrivatekey        = '私鑰';
     
 
 
 
    /*
      $this->wechatToken          = $WechatInfo['wechat_token'];
      $this->wechatAccessToken       = $WechatInfo['wechat_access_token'];
      $this->wechatAccessTokenTime     = $WechatInfo['wechat_access_token_time'];
      $this->wechatJsapiTicket       = $WechatInfo['wechat_jsapi_ticket'];
      $this->wechatJsapiTicketTime     = $WechatInfo['wechat_jsapi_ticket_time'];
    */
  }
 
 
// +----------------------------------------------------------------------
// |    獲取access_token
// +----------------------------------------------------------------------
  public function getAccessToken(){
 
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->wechatAppid.'&secret='.$this->wechatAppsecret;
    $data = $this -> curlGet($url);
    $access_token = $data['access_token'];
    $expires_in  = $data['expires_in'];
    $save['wechat_access_token']    = $access_token;
    $save['wechat_access_token_time']  = ($expires_in+time())-360;
    $this  ->  wechatAccessToken    = $save['wechat_access_token'];
    $this  ->  wechatAccessTokenTime  = $save['wechat_access_token_time'];
    return $access_token;
 
  }
  // +----------------------------------------------------------------------
  // |    獲取access_token
  // +----------------------------------------------------------------------
  public function getJsapiTicket(){
 
    $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$this -> getAccessToken().'&type=jsapi';
    $data = $this -> curlGet($url);
 
    $jsapi_ticket = $data['ticket'];
    $expires_in  = $data['expires_in'];
 
    $save['wechat_jsapi_ticket']    = $jsapi_ticket;
    $save['wechat_jsapi_ticket_time']  = ($expires_in+time())-360;
 
    $this->wechatJsapiTicket    = $save['wechat_jsapi_ticket'];
    $this->wechatJsapiTicketTime  = $save['wechat_jsapi_ticket_time'];
 
    return $jsapi_ticket;
 
  }
  // +----------------------------------------------------------------------
  // |    獲取signature
  // +----------------------------------------------------------------------
  public function getSignature($appId,$timestamp,$nonceStr,$url)
  {
 
    $jsapi_ticket = $this -> getJsapiTicket();
    $string1 = "jsapi_ticket={$jsapi_ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
    $signature = sha1($string1);
    return $signature;
  }
  // +----------------------------------------------------------------------
  // |    獲取createNonceStr
  // +----------------------------------------------------------------------
  public function getCreateNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
     $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }
  // +----------------------------------------------------------------------
  // |    下載本地
  // +----------------------------------------------------------------------
  public function curlDownload($url,$name)
  {
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt ( $ch, CURLOPT_URL, $url );
    ob_start ();
    curl_exec ( $ch );
    $return_content = ob_get_contents ();
    ob_end_clean ();
    $return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
 
    $filename = "Uploads/Card/{$name}";
    $fp= @fopen($filename,"a");
    fwrite($fp,$return_content);
    // 關閉URL請求
    curl_close($ch);
 
    $url = "/Uploads/Card/{$name}";
 
    return "{$url}";
  }
  // +----------------------------------------------------------------------
  // |    GET請求
  // +----------------------------------------------------------------------
  public function curlGet($url)
  {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      $output = curl_exec($ch);
      curl_close($ch);
      $jsoninfo = json_decode($output, true);
      return $jsoninfo;
  }
  // +----------------------------------------------------------------------
  // |    POST SSL請求
  // +----------------------------------------------------------------------
  public function curlPostSSL($url, $vars, $second=30,$aHeader=array()){
    $ch = curl_init();
    //超時時間
    curl_setopt($ch,CURLOPT_TIMEOUT,$second);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
    //這里設置代理,如果有的話
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
    //curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
    curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert/apiclient_cert.pem');
    //curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
    curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/cert/apiclient_key.pem');
 
    if( count($aHeader) >= 1 ){
      curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
    }
 
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
    $data = curl_exec($ch);
    if($data){
      curl_close($ch);
      return $data;
    } else {
      $error = curl_errno($ch);
      echo "call faild, errorCode:$error\n";
      curl_close($ch);
      return false;
    }
  }
 
  // +----------------------------------------------------------------------
  // | 發送退款
  //  退款單號 out_trade_no
  //  交易金額 total_fee
  //  退款金額 refund_fee
  // +----------------------------------------------------------------------
  public function refund($out_trade_no,$total_fee,$refund_fee){
 
    $arr['appid']      =  $this->wechatAppid;
    $arr['mch_id']     =  $this->wechatMchid;
    $arr['nonce_str']    =  $this->getNonceStr();
    $arr['out_trade_no']  =  $out_trade_no;
    $arr['out_refund_no']  =  $this->getNonceStr();
    $arr['total_fee']    =  $total_fee;
    $arr['refund_fee']   =  $refund_fee;
    $arr['sign']      =  $this->MakeSign($arr);
 
    //將統一下單數組 轉換xml
    $xml            =  $this->ToXml($arr);
 
 
    //post xml 到微信退款接口
    $url  =  "https://api.mch.weixin.qq.com/secapi/pay/refund";;//微信退款地址,post請求
    $ch=curl_init();
    //需要獲取的URL地址,也可以在 curl_init() 函數中設置。
    curl_setopt($ch,CURLOPT_URL,$url);
    //啟用時會將頭文件的信息作為數據流輸出。
    //curl_setopt($ch,CURLOPT_HEADER,1);
    //將 curl_exec() 獲取的信息以文件流的形式返回,而不是直接輸出。
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    //證書檢查
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    //證書的類型。支持的格式有"PEM" (默認值), "DER"和"ENG"。
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    //一個包含PEM格式證書的文件名。
    curl_setopt($ch,CURLOPT_SSLCERT,GEN.'/cert/apiclient_cert.pem');
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    curl_setopt($ch,CURLOPT_TIMEOUT,30);
    //包含SSL私鑰的文件名。
    curl_setopt($ch,CURLOPT_SSLKEY,GEN.'/cert/apiclient_key.pem');
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    //一個保存著1個或多個用來讓服務端驗證的證書的文件名。這個參數僅僅在和 CURLOPT_SSL_VERIFYPEER 一起使用時才有意義。 .
    // curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/cert/rootca.pem');
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
    $data=curl_exec($ch);
    if($data){
      curl_close($ch);
      $data_arr = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
      return $data_arr;
    }else{
      $error =  curl_errno($ch);
      return "curl 錯誤:".$error;
    }
  }
 
 
 
 
 
 
 
  // +----------------------------------------------------------------------
  // | 企業付款
  //  退款單號 out_trade_no
  //  交易金額 total_fee
  //  退款金額 refund_fee
  // +----------------------------------------------------------------------
  public function payment($partner_trade_no,$openid,$amount,$desc){
 
    // 獲取
    $arr['mch_appid']      =  $this->wechatAppid;
    $arr['mchid']        =  $this->wechatMchid;
    $arr['nonce_str']      =  $this->getNonceStr();
    $arr['partner_trade_no']  =  $partner_trade_no;
    $arr['openid']       =  $openid;
    $arr['check_name']     =  "NO_CHECK";
    $arr['amount']       =  $amount*100;
    $arr['desc']        =  $desc;
    $arr['spbill_create_ip']  =  request()->ip();
    $arr['sign']        =  $this->MakeSign($arr);
 
    //將統一下單數組 轉換xml
    $xml            =  $this->ToXml($arr);
 
    //post xml 到微信退款接口
    $url  =  "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";//微信退款地址,post請求
    $ch=curl_init();
    //需要獲取的URL地址,也可以在 curl_init() 函數中設置。
    curl_setopt($ch,CURLOPT_URL,$url);
    //啟用時會將頭文件的信息作為數據流輸出。
    //curl_setopt($ch,CURLOPT_HEADER,1);
    //將 curl_exec() 獲取的信息以文件流的形式返回,而不是直接輸出。
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    //證書檢查
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    //證書的類型。支持的格式有"PEM" (默認值), "DER"和"ENG"。
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    //一個包含PEM格式證書的文件名。
    curl_setopt($ch,CURLOPT_SSLCERT,GEN.'/cert/apiclient_cert.pem');
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    curl_setopt($ch,CURLOPT_TIMEOUT,30);
    //包含SSL私鑰的文件名。
    curl_setopt($ch,CURLOPT_SSLKEY,GEN.'/cert/apiclient_key.pem');
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    //一個保存著1個或多個用來讓服務端驗證的證書的文件名。這個參數僅僅在和 CURLOPT_SSL_VERIFYPEER 一起使用時才有意義。 .
    // curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/cert/rootca.pem');
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
    $data=curl_exec($ch);
    if($data){
      curl_close($ch);
      $data_arr = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
      return $data_arr;
    }else{
      $error =  curl_errno($ch);
      return "curl 錯誤:".$error;
    }
 
 
 
  }
 
 
 
  // +----------------------------------------------------------------------
  // |    POST請求
  // +----------------------------------------------------------------------
  public function curlPost($url,$post_data)
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($post_data)){
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
 
    return $output;
  }
  // +----------------------------------------------------------------------
  // |    齊力短信
  // +----------------------------------------------------------------------
  public function message($mobile){
 
    $info  =  M('web')
        ->  find();
 
    $post_data = array();
    $post_data['userid']  =  $info['message_id'];
    $post_data['account']  =  $info['message_account'];
    $post_data['password'] =  $info['message_password'];
    $code = rand(1111,9999);
    session('code',$code);
    $post_data['content'] =   $info['message_autograph'].'您的驗證碼是:'.$code.' 請務必保管好,以免泄露';
    $post_data['mobile'] = $mobile;
    $post_data['sendtime'] = date('Y-m-d');
    $url='http://pt.sdqlweb.com/sms.aspx?action=send';
    $o='';
    foreach ($post_data as $k=>$v)
    {
    $o.="$k=".urlencode($v).'&';
    }
    $post_data=substr($o,0,-1);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    $data = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    curl_close($ch);
    return $data;
  }
  // +----------------------------------------------------------------------
  // |    以post方式提交xml到對應的接口url
  // +----------------------------------------------------------------------
  public function postXmlCurl($xml, $url, $useCert = false, $second = 30)
  {
    $ch = curl_init();
    //設置超時
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//嚴格校驗
    //設置header
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    //要求結果為字符串且輸出到屏幕上
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    //post提交方式
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    //運行curl
    $data = curl_exec($ch);
    //返回結果
    if($data){
      curl_close($ch);
      return $data;
    } else {
      $error = curl_errno($ch);
      curl_close($ch);
    }
  }
  // +----------------------------------------------------------------------
  // |    輸出xml字符
  // +----------------------------------------------------------------------
  public function ToXml($array)
  {
    if(!is_array($array)
      || count($array) <= 0)
    {
      throw new WxPayException("數組數據異常!");
    }
    $xml = "<xml>";
    foreach ($array as $key=>$val)
    {
      if (is_numeric($val)){
        $xml.="<".$key.">".$val."</".$key.">";
      }else{
        $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
      }
    }
    $xml.="</xml>";
    return $xml;
  }
  // +----------------------------------------------------------------------
  // |    獲取微信RAS公鑰
  // +----------------------------------------------------------------------
  public function get_pub_key(){
 
    $url        =  "https://fraud.mch.weixin.qq.com/risk/getpublickey";
    $arr['mch_id']   =  $this->wechatMchid;
    $arr['nonce_str']  =  $this->getNonceStr();
    $arr['sign_type']  =  'MD5';
    $arr['sign']    =  $this->MakeSign($arr);
    $xml        =  $this->ToXml($arr);
    $ch =  curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert/apiclient_cert.pem');
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/cert/apiclient_key.pem');
    curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
    curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/cert/rootca.pem');
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
    $data  =  $this->FromXml(curl_exec($ch));
    //要創建的兩個文件
    $TxtFileName = "./cert/public.pem";
    //以讀寫方式打寫指定文件,如果文件不存則創建
    if( ($TxtRes=fopen ($TxtFileName,"w+")) === false){
      echo("創建可寫文件:".$TxtFileName."失敗");
      exit();
    }
      echo ("創建可寫文件".$TxtFileName."成功!</br>");
      $StrConents =  $data['pub_key'];//要 寫進文件的內容
    if(!fwrite ($TxtRes,$StrConents)){ //將信息寫入文件
      echo ("嘗試向文件".$TxtFileName."寫入".$StrConents."失敗!");
      fclose($TxtRes);
      exit();
    }
      echo ("嘗試向文件".$TxtFileName."寫入".$StrConents."成功!");
      fclose ($TxtRes); //關閉指針
  }
  // +----------------------------------------------------------------------
  // |    將xml轉為array
  // +----------------------------------------------------------------------
  public function FromXml($xml)
  {
    //禁止引用外部xml實體
    libxml_disable_entity_loader(true);
    $this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $this->values;
  }
  // +----------------------------------------------------------------------
  // |    微信銀行卡編碼
  // +----------------------------------------------------------------------
  public function Cardcode($card_name)
  {
    $arr  =  array(
      '工商銀行'=>1002,
      '農業銀行'=>1005,
      '中國銀行'=>1026,
      '建設銀行'=>1003,
      '招商銀行'=>1001,
      '郵儲銀行'=>1066,
      '交通銀行'=>1020,
      '浦發銀行'=>1004,
      '民生銀行'=>1006,
      '興業銀行'=>1009,
      '平安銀行'=>1010,
      '中信銀行'=>1021,
      '華夏銀行'=>1025,
      '廣發銀行'=>1027,
      '光大銀行'=>1022,
      '北京銀行'=>1032,
      '寧波銀行'=>1056
    );
 
    foreach($arr as $k=>$v){
      if($k == $card_name){
        return $v;
      }
    }
  }
  // +----------------------------------------------------------------------
  // |    格式化參數格式化成url參數
  // +----------------------------------------------------------------------
  public function ToUrlParams($array)
  {
    $buff = "";
    foreach ($array as $k => $v)
    {
      if($k != "sign" && $v != "" && !is_array($v)){
        $buff .= $k . "=" . $v . "&";
      }
    }
    $buff = trim($buff, "&");
    return $buff;
  }
  // +----------------------------------------------------------------------
  // |    生成簽名 本函數不覆蓋sign成員變量,如要設置簽名需要調用SetSign方法賦值
  // +----------------------------------------------------------------------
  public function MakeSign($array)
  {
    //簽名步驟一:按字典序排序參數
    ksort($array);
    $string =  $this->ToUrlParams($array);
    //簽名步驟二:在string后加入KEY
    $string =  $string."&key=".$this->wechatPrivatekey;
    //簽名步驟三:MD5加密
    $string =  md5($string);
    //簽名步驟四:所有字符轉為大寫
    $string =  strtoupper($string);
    return $string;
  }
  // +----------------------------------------------------------------------
  // |    產生的隨機字符串
  // +----------------------------------------------------------------------
  public function getNonceStr($length = 32)
  {
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ ) {
      $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
  }
  // +----------------------------------------------------------------------
  // |    打印log日志
  // +----------------------------------------------------------------------
  public function save_log($msg){
    error_log(date("Y-m-d H:i:s")."\r\n".print_r($msg,1)."\r\n \r\n \r\n ",3,'./error.log');
  }
  // +----------------------------------------------------------------------
  // |    將圖片上傳至微信服務器
  // +----------------------------------------------------------------------
  public function curlImg($images){
 
    $url    =  "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$this->getAccessToken()."&type=image";
    $ch1    =  curl_init ();
    $timeout  =  5;
    $real_path =  "{$_SERVER['DOCUMENT_ROOT']}{$images}";
 
    $data= array("media"=>"@{$real_path}",'form-data'=>$file_info);
    curl_setopt ( $ch1, CURLOPT_URL, $url );
    curl_setopt ( $ch1, CURLOPT_POST, 1 );
    curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
    curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
    curl_setopt ( $ch1, CURLOPT_POSTFIELDS, $data );
    $result = curl_exec ( $ch1 );
    curl_close ( $ch1 );
    if(curl_errno()==0){
      $result=json_decode($result,true);
      return $result;
    }else {
      return false;
    }
  }
  // +----------------------------------------------------------------------
  // |    將文章轉換為微信文章
  // +----------------------------------------------------------------------
  public function wechatText($content){
    $parrent = "/<[img|IMG].*?src='(.*?)'/";
    $str  =  html_entity_decode($content);
    preg_match_all($parrent,$str,$match);
    foreach( $match[1] as $v){
      $imgurl   =  $this->curlImg($v);
      $content  =  str_replace($v,$imgurl['url'],$content);
    }
    return ($content);
  }
  // +----------------------------------------------------------------------
  // |    驗證銀行卡號
  // +----------------------------------------------------------------------
   public function check_bank_card($card){
 
      $url  =  "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo={$card}&cardBinCheck=true";
      $data  =  $this->curlGet($url);
      $name  =  [
          "SRCB"=> "深圳農村商業銀行",
          "BGB"=> "廣西北部灣銀行",
          "SHRCB"=> "上海農村商業銀行",
          "BJBANK"=> "北京銀行",
          "WHCCB"=> "威海市商業銀行",
          "BOZK"=> "周口銀行",
          "KORLABANK"=> "庫爾勒市商業銀行",
          "SPABANK"=> "平安銀行",
          "SDEB"=> "順德農商銀行",
          "HURCB"=> "湖北省農村信用社",
          "WRCB"=> "無錫農村商業銀行",
          "BOCY"=> "朝陽銀行",
          "CZBANK"=> "浙商銀行",
          "HDBANK"=> "邯鄲銀行",
          "BOC"=> "中國銀行",
          "BOD"=> "東莞銀行",
          "CCB"=> "中國建設銀行",
          "ZYCBANK"=> "遵義市商業銀行",
          "SXCB"=> "紹興銀行",
          "GZRCU"=> "貴州省農村信用社",
          "ZJKCCB"=> "張家口市商業銀行",
          "BOJZ"=> "錦州銀行",
          "BOP"=> "平頂山銀行",
          "HKB"=> "漢口銀行",
          "SPDB"=> "上海浦東發展銀行",
          "NXRCU"=> "寧夏黃河農村商業銀行",
          "NYNB"=> "廣東南粵銀行",
          "GRCB"=> "廣州農商銀行",
          "BOSZ"=> "蘇州銀行",
          "HZCB"=> "杭州銀行",
          "HSBK"=> "衡水銀行",
          "HBC"=> "湖北銀行",
          "JXBANK"=> "嘉興銀行",
          "HRXJB"=> "華融湘江銀行",
          "BODD"=> "丹東銀行",
          "AYCB"=> "安陽銀行",
          "EGBANK"=> "恒豐銀行",
          "CDB"=> "國家開發銀行",
          "TCRCB"=> "江蘇太倉農村商業銀行",
          "NJCB"=> "南京銀行",
          "ZZBANK"=> "鄭州銀行",
          "DYCB"=> "德陽商業銀行",
          "YBCCB"=> "宜賓市商業銀行",
          "SCRCU"=> "四川省農村信用",
          "KLB"=> "昆侖銀行",
          "LSBANK"=> "萊商銀行",
          "YDRCB"=> "堯都農商行",
          "CCQTGB"=> "重慶三峽銀行",
          "FDB"=> "富滇銀行",
          "JSRCU"=> "江蘇省農村信用聯合社",
          "JNBANK"=> "濟寧銀行",
          "CMB"=> "招商銀行",
          "JINCHB"=> "晉城銀行JCBANK",
          "FXCB"=> "阜新銀行",
          "WHRCB"=> "武漢農村商業銀行",
          "HBYCBANK"=> "湖北銀行宜昌分行",
          "TZCB"=> "臺州銀行",
          "TACCB"=> "泰安市商業銀行",
          "XCYH"=> "許昌銀行",
          "CEB"=> "中國光大銀行",
          "NXBANK"=> "寧夏銀行",
          "HSBANK"=> "徽商銀行",
          "JJBANK"=> "九江銀行",
          "NHQS"=> "農信銀清算中心",
          "MTBANK"=> "浙江民泰商業銀行",
          "LANGFB"=> "廊坊銀行",
          "ASCB"=> "鞍山銀行",
          "KSRB"=> "昆山農村商業銀行",
          "YXCCB"=> "玉溪市商業銀行",
          "DLB"=> "大連銀行",
          "DRCBCL"=> "東莞農村商業銀行",
          "GCB"=> "廣州銀行",
          "NBBANK"=> "寧波銀行",
          "BOYK"=> "營口銀行",
          "SXRCCU"=> "陜西信合",
          "GLBANK"=> "桂林銀行",
          "BOQH"=> "青海銀行",
          "CDRCB"=> "成都農商銀行",
          "QDCCB"=> "青島銀行",
          "HKBEA"=> "東亞銀行",
          "HBHSBANK"=> "湖北銀行黃石分行",
          "WZCB"=> "溫州銀行",
          "TRCB"=> "天津農商銀行",
          "QLBANK"=> "齊魯銀行",
          "GDRCC"=> "廣東省農村信用社聯合社",
          "ZJTLCB"=> "浙江泰隆商業銀行",
          "GZB"=> "贛州銀行",
          "GYCB"=> "貴陽市商業銀行",
          "CQBANK"=> "重慶銀行",
          "DAQINGB"=> "龍江銀行",
          "CGNB"=> "南充市商業銀行",
          "SCCB"=> "三門峽銀行",
          "CSRCB"=> "常熟農村商業銀行",
          "SHBANK"=> "上海銀行",
          "JLBANK"=> "吉林銀行",
          "CZRCB"=> "常州農村信用聯社",
          "BANKWF"=> "濰坊銀行",
          "ZRCBANK"=> "張家港農村商業銀行",
          "FJHXBC"=> "福建海峽銀行",
          "ZJNX"=> "浙江省農村信用社聯合社",
          "LZYH"=> "蘭州銀行",
          "JSB"=> "晉商銀行",
          "BOHAIB"=> "渤海銀行",
          "CZCB"=> "浙江稠州商業銀行",
          "YQCCB"=> "陽泉銀行",
          "SJBANK"=> "盛京銀行",
          "XABANK"=> "西安銀行",
          "BSB"=> "包商銀行",
          "JSBANK"=> "江蘇銀行",
          "FSCB"=> "撫順銀行",
          "HNRCU"=> "河南省農村信用",
          "COMM"=> "交通銀行",
          "XTB"=> "邢臺銀行",
          "CITIC"=> "中信銀行",
          "HXBANK"=> "華夏銀行",
          "HNRCC"=> "湖南省農村信用社",
          "DYCCB"=> "東營市商業銀行",
          "ORBANK"=> "鄂爾多斯銀行",
          "BJRCB"=> "北京農村商業銀行",
          "XYBANK"=> "信陽銀行",
          "ZGCCB"=> "自貢市商業銀行",
          "CDCB"=> "成都銀行",
          "HANABANK"=> "韓亞銀行",
          "CMBC"=> "中國民生銀行",
          "LYBANK"=> "洛陽銀行",
          "GDB"=> "廣東發展銀行",
          "ZBCB"=> "齊商銀行",
          "CBKF"=> "開封市商業銀行",
          "H3CB"=> "內蒙古銀行",
          "CIB"=> "興業銀行",
          "CRCBANK"=> "重慶農村商業銀行",
          "SZSBK"=> "石嘴山銀行",
          "DZBANK"=> "德州銀行",
          "SRBANK"=> "上饒銀行",
          "LSCCB"=> "樂山市商業銀行",
          "JXRCU"=> "江西省農村信用",
          "ICBC"=> "中國工商銀行",
          "JZBANK"=> "晉中市商業銀行",
          "HZCCB"=> "湖州市商業銀行",
          "NHB"=> "南海農村信用聯社",
          "XXBANK"=> "新鄉銀行",
          "JRCB"=> "江蘇江陰農村商業銀行",
          "YNRCC"=> "云南省農村信用社",
          "ABC"=> "中國農業銀行",
          "GXRCU"=> "廣西省農村信用",
          "PSBC"=> "中國郵政儲蓄銀行",
          "BZMD"=> "駐馬店銀行",
          "ARCU"=> "安徽省農村信用社",
          "GSRCU"=> "甘肅省農村信用",
          "LYCB"=> "遼陽市商業銀行",
          "JLRCU"=> "吉林農信",
          "URMQCCB"=> "烏魯木齊市商業銀行",
          "XLBANK"=> "中山小欖村鎮銀行",
          "CSCB"=> "長沙銀行",
          "JHBANK"=> "金華銀行",
          "BHB"=> "河北銀行",
          "NBYZ"=> "鄞州銀行",
          "LSBC"=> "臨商銀行",
          "BOCD"=> "承德銀行",
          "SDRCU"=> "山東農信",
          "NCB"=> "南昌銀行",
          "TCCB"=> "天津銀行",
          "WJRCB"=> "吳江農商銀行",
          "CBBQS"=> "城市商業銀行資金清算中心",
          "HBRCU"=> "河北省農村信用社"
       ];
 
 
      $bank  =  $data['bank'];
      $name  =  $name[$bank];
      if($name){
        if($bank){
          $url1      = "https://apimg.alipay.com/combo.png?d=cashier&t={$bank}";
          $msg['pic']   =  $this->curlDownload($url1,time().'.png');
          $msg['logo']  =  $this->imagecropper('.'.$msg['pic'],30,35);
          $msg['status'] = 200;
          $msg['name'] = $name;
          return $msg;
        }
      }else{
        $msg['status'] = 500;
        $msg['data'] = '系統檢測到該銀行卡無效,請輸入有效銀行卡卡號';
        return $msg;
      }
 
    }
 
/**
* 圖像裁剪
* @param $title string 原圖路徑
* @param $content string 需要裁剪的寬
* @param $encode string 需要裁剪的高
*/
    public function imagecropper($source_path, $target_width, $target_height){
 
      $source_info = getimagesize($source_path);
      $source_width = $source_info[0];
      $source_height = $source_info[1];
      $source_mime = $source_info['mime'];
      $source_x = 0;
      $source_y = 0;
      switch ($source_mime)
      {
        case 'image/gif':
        $source_image = imagecreatefromgif($source_path);
        break;
 
        case 'image/jpeg':
        $source_image = imagecreatefromjpeg($source_path);
        break;
 
        case 'image/png':
        $source_image = imagecreatefrompng($source_path);
        break;
 
        default:
        return false;
        break;
      }
      $target_image = imagecreatetruecolor($target_width, $target_height);
      $cropped_image = imagecreatetruecolor($target_width, $target_height);
      // 裁剪
      imagecopy($cropped_image, $source_image,0,0, $source_x, $source_y, $target_width, $target_height);
      // 縮放
      imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $target_width, $target_height);
      imagecolortransparent($target_image,imagecolorallocate($target_image,255,255,255));
      $fileName = time()."1.png";
      $path  =  './Uploads/Card/'.$fileName;
      imagepng($target_image,$path);
      return '/Uploads/Card/'.$fileName;
    }
 
 
    // 隨機字符
    public function noncestr($length = 12){
      $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      $str ="";
      for ( $i = 0; $i < $length; $i++ ) {
        $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
      }
      return $str;
    }
 
}
?>

下面是其他網友的補充

PHP獲取小程序碼并返回前端顯示圖片

小程序的二維碼分為小程序碼和二維碼;
生成小程序二維碼文檔中說后端來生成。

參考 小程序開發文檔資料:https://developers.weixin.qq.com/miniprogram/dev/api/getWXACodeUnlimit.html

文檔的參數介紹還是蠻詳細的,但是沒有具體的demo,對于請求的接口的返回值是進制流(也就是在瀏覽器顯示一堆亂碼)也是很令人懊惱,這里貼一下我的代碼:

//獲取小程序碼,這里調用的是小程序碼的A接口類型
  public function getQRCodeAction()
  {
    $data['scene'] = $this->_req->getQuery('shareId',11); //scence、page的使用要參考文檔(比如:scene的值不能超過32個字符等)
    $data['width'] = $this->_req->getQuery('width',220);
    $data['auto_color'] = $this->_req->getQuery('auto_color');
    $data['line_color'] = $this->_req->getQuery('line_color');
    $data['is_hyaline'] = $this->_req->getQuery('is_hyaline',true);
    $data['page'] = $this->_req->getQuery('page',"");  //由這行以上代碼是二維碼的樣式等由前端傳值的形式,也可以直接在后端設置
    $wxModel = new WxAuthModel();
    $token = $wxModel->getAccessToken();
    $res_url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token"; //請求微信提供的接口
    header('content-type:image/png');
    $data = json_encode($data);
    $Qr_code = $wxModel->http_request($res_url,$data); //到這里就已經返回微信提供的返回數據了,這個時候的數據是二進制流,要處理下再返回給前端
    file_put_contents('/tmp/qr_code.png', $Qr_code); //將獲得的數據讀到一個臨時圖片里
    $img_string = $this->fileToBase64('/tmp/qr_code.png'); //將圖片文件轉化為base64
    response::result($img_string);
  }

  //本地文件轉base64
  private function fileToBase64($file){
    $base64_file = '';
    if(file_exists($file)){
      $mime_type= mime_content_type($file); //如果這里明確是圖片的話我建議獲取圖片類型這句可以省略,直接知道了mine_type='image/png',因為我這里我雖然存的圖片,但是讀到的mine_type值為text/plain
      $base64_data = base64_encode(file_get_contents($file));
      $base64_file = 'data:'.$mime_type.';base64,'.$base64_data; //$base64_file = 'data:image/png;base64,'.$base64_data; 
    }
    return $base64_file;
  }


 /*獲取access_token,不需要code參數,不能用于獲取用戶信息的token*/
  public function getAccessToken()
  {
    $token_file = '/dev/shm/heka2_token.json'; //由于獲取token的次數存在限制,所以將一段時間內的token緩存到一個文件(注意緩存路徑服務器支持可寫可讀),過期后再重新獲取
    $data = json_decode(file_get_contents($token_file));
    if ($data->expire_time < time()) {
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
      $res = json_decode($this->http_request($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        file_put_contents($token_file, json_encode($data));
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
  }

感覺一個完整的PHP實現的代碼目前我還沒找到,這個自己用的還行。如有不恰當的地方,歡迎指出~ _

相關文章

  • php獲取小程序碼的實現代碼(B類接口)

    php獲取小程序碼的實現代碼(B類接口)

    效果圖 生成小程序碼的php代碼 public function qrcode(){ $member_id = session('id'); if(empty($member_id)) $this->error('請先登錄'); //推廣
    2020-06-14
  • PyInstaller運行原理及常用操作詳解

    PyInstaller運行原理及常用操作詳解

    pyinstaller 屬于Python第三方庫,使用前需先安裝 # 首先安裝pyinstaller pip install pyinstaller PyInstaller生成可執行程序 # PyInstaller 工具的命
    2020-06-14
  • Python輕量級web框架bottle使用方法解析

    Python輕量級web框架bottle使用方法解析

    Bottle是一個輕量級的Web框架,此框架只由一個 bottle.py 文件構成,不依賴任何第三方模塊。 #!/usr/bin/env python # -*- coding:utf-8 -*- from bottle import
    2020-06-14
  • Python xpath表達式如何實現數據處理

    Python xpath表達式如何實現數據處理

    xpath表達式 1. xpath語法 <bookstore> <book> <title lang="eng">Harry Potter</title> <price>999</price> </book> <book> <title lang="eng">Learning X
    2020-06-14
  • Python Django搭建網站流程圖解

    Python Django搭建網站流程圖解

    1. 創建Django REST framework工程 1.1手動創建工程文件夾 1.2進去工程文件夾內,執行命令:django-admin startproject web_project創建工程目錄 1.3修改,添加目錄
    2020-06-14
  • 簡單了解Spring Web相關模塊運行原理

    簡單了解Spring Web相關模塊運行原理

    Spring 的Web層中有4個模塊,分別為spring-web, spring-webmvc, spring-websocket 和 spring-webmvc-portlet。 spring-web spring-web 提供了核心的Web相關功能的
    2020-06-14
  • python如何更新包

    python如何更新包

    Python安裝新包,pip是很好用的安裝工具。 pip list 可以查詢所有已安裝的包和版本。怎么知道本地安裝包的版本是否有可以更新的新版本呢?通過pip list函數可以實現
    2020-06-14
  • numpy的Fancy Indexing和array比較詳解

    numpy的Fancy Indexing和array比較詳解

    一:Fancy Indexing import numpy as np #Fancy Indexing x = np.arange(16) np.random.shuffle(x) print(x) #打印所有的元素 print(x[2])#獲取某個元素
    2020-06-14
  • python屬于解釋語言嗎

    python屬于解釋語言嗎

    Python是一門解釋型語言? Python是一門解釋性語言,我就這樣一直相信下去,直到發現了*.pyc文件的存在。 如果是解釋型語言,那么生成的*.pyc文件是什么呢?c應該是
    2020-06-14
  • 使用sklearn對多分類的每個類別進行指標評價操作

    使用sklearn對多分類的每個類別進行指標評價操作

    今天晚上,筆者接到客戶的一個需要,那就是:對多分類結果的每個類別進行指標評價,也就是需要輸出每個類型的精確率(precision),召回率(recall)以及F1值(F1-s
    2020-06-14

最新評論

买宝宝用品赚钱吗 在线配资诚信减配资 黑龙江体彩61开奖号码 江苏快3历史开奖结果 3d走势图专业版 快乐十分免费预测软件 东方6+1玩法 2011年12月上证指数 北京十一选五奖金 腾讯二分彩开奖号码 股票趋势技术分析8 网上理财 辽宁11选五走势图大乐透 群英会20选5绝密算法 吉林快三黑彩大小单双 广西十一选五开奖结果图 重庆快乐10分开奖官网