PHP version WeChat public platform Red Envelope api_php Example

Source: Internet
Author: User
Tags oauth openid sha1 vars
Rewrite the API interface below PHP,

Red envelope support, JSAPI dynamic parameter interface support

http://git.oschina.net/youkuiyuan/yky_test/blob/master/class/wxapi.class.php

API class-Add red envelope support

<?php/******************************************************** * @author Kyler you
 
  
   * @link http://mp.weixin.qq.com/wiki/home/index.html * @version 2.0.1 * @uses $wxApi = new Wxapi ();     * @package API interface will continue to update ********************************************************/class Wxapi {const APPID    = "";     Const APPSECRET = ""; Const MCHID = ""; Merchant Number Const Privatekey = "";     Private key Public $parameters = Array ();     Public Function __construct () {}/**************************************************** * commits the API method, returns the specified JSON /Public Function Wxhttpsrequest ($url, $data = null) {$curl        = Curl_init ();        curl_setopt ($curl, Curlopt_url, $url);        curl_setopt ($curl, Curlopt_ssl_verifypeer, FALSE);        curl_setopt ($curl, Curlopt_ssl_verifyhost, FALSE);            if (!empty ($data)) {curl_setopt ($curl, Curlopt_post, 1);        curl_setopt ($curl, Curlopt_postfields, $data);        } curl_setopt ($curl, Curlopt_returntransfer, 1); $oUtput = curl_exec ($curl);        Curl_close ($curl);    return $output; /**************************************************** * With certificate submission data-Red envelopes use ************************************* /Public Function Wxhttpsrequestpem ($url, $vars, $second =30, $aHeader =array ()) {$ch = Curl_init ()        ;        Time-out curl_setopt ($ch, Curlopt_timeout, $second);        curl_setopt ($ch, Curlopt_returntransfer, 1);        Here set the agent, if any,//curl_setopt ($ch, Curlopt_proxy, ' 10.206.30.98 ');        curl_setopt ($ch, curlopt_proxyport, 8080);        curl_setopt ($ch, Curlopt_url, $url);        curl_setopt ($ch, Curlopt_ssl_verifypeer,false);         curl_setopt ($ch, Curlopt_ssl_verifyhost,false); There are two ways to choose one//first method, cert and key belong to two. pem file//default format is PEM, you can annotate curl_setopt ($ch, Curlopt_sslcerttype, ' P        EM '); curl_setopt ($ch, CURLOPT_SSLCERT,GETCWD (). '        /apiclient_cert.pem ');  The default format is PEM, which can be annotated with curl_setopt ($ch, Curlopt_sslkeytype, ' PEM ');      curl_setopt ($ch, CURLOPT_SSLKEY,GETCWD (). '         /apiclient_key.pem ');        curl_setopt ($ch, Curlopt_cainfo, ' PEM '); curl_setopt ($ch, CURLOPT_CAINFO,GETCWD (). '         /rootca.pem '); The second way, two files to synthesize a. pem file//curl_setopt ($ch, CURLOPT_SSLCERT,GETCWD ().         /all.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; }}/**************************************************** * Gets Accesstoken returns the at information for the specified public number ********************     /Public Function Wxaccesstoken ($appId = null, $appSecret = null) {$appId = Is_null ($APPID)?        Self::appid: $appId; $appSecret = Is_null ($appSecret)?        Self::appsecret: $appSecret;        Echo $appId, $appSecret; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". $appId. "        &secret= ". $appSecret;        $result = $this->wxhttpsrequest ($url);        Print_r ($result);        $jsoninfo = Json_decode ($result, true);        $access _token = $jsoninfo ["Access_token"];    return $access _token; /**************************************************** * Get user information via OpenID, return array ********************************        /Public Function Wxgetuser ($openId) {$wxAccessToken = $this->wxaccesstoken (); $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=". $wxAccessToken. " &openid= ". $openId."        &AMP;LANG=ZH_CN ";        $result = $this->wxhttpsrequest ($url);        $jsoninfo = Json_decode ($result, true);    return $jsoninfo; }     /***** Sent to the specified user by specifying the template information and returning the specified JSON data after the send is complete ******************************        /Public Function Wxsendtemplate ($jsonData) {$wxAccessToken = $this->wxaccesstoken ();        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=". $wxAccessToken;        $result = $this->wxhttpsrequest ($url, $jsonData);    return $result; /**************************************************** * Send custom Template message *************************************** /Public Function Wxsetsend ($touser, $template _id, $url, $data, $topcolor = ' #7B68EE ') {$template            = Array (' touser ' = $touser, ' template_id ' = = $template _id, ' url ' = = $url,        ' Topcolor ' = $topcolor, ' data ' = $data);        $jsonData = Json_encode ($template);        $result = $this->wxsendtemplate ($jsonData); return $result;   /**************************************************** * Set OAuth jump URL, return string information-SCOPE = snsapi_base//validation does not return confirmation page, you can only get OpenID ****************************************************/public Function wxoauthbase ($REDIRECTURL, $stat E = "", $appId = NULL) {$appId = Is_null ($appId)?        Self::appid: $appId; $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=". $appId. " &redirect_uri= ". $redirectUrl." &response_type=code&scope=snsapi_base&state= ". $state."        #wechat_redirect ";    return $url; }/**************************************************** * Set OAuth jump URL, return string information-SCOPE = snsapi_userinfo//get user full letter ****************************************************/Public Function Wxoauthuserinfo ($REDIRECTURL, $state = "", $        AppId = NULL) {$appId = Is_null ($appId)? Self::appid: $appId; $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=". $appId. " &redirect_uri= ". $redirectUrl." &responsE_type=code&scope=snsapi_userinfo&state= ". $state."        #wechat_redirect ";    return $url; }/**************************************************** * OAuth jump Specifies URL ***************************************    /Public Function Wxheader ($url) {header ("Location:". $url); /**************************************************** * Gets the at information through the OAuth return page ********************************* /Public Function Wxoauthaccesstoken ($code, $appId = null, $appSecret = null) {$appId = Is_null ($appId)?        Self::appid: $appId; $appSecret = Is_null ($appSecret)?        Self::appsecret: $appSecret; $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=". $appId. " &secret= ". $appSecret." &code= ". $code."        &grant_type=authorization_code ";        $result = $this->wxhttpsrequest ($url);        Print_r ($result);        $jsoninfo = Json_decode ($result, true); $access _token = $jsoninfo ["acCess_token "];          return $jsoninfo; /**************************************************** * Get current user information via OAuth's Access_token information//execute only in Snsapi_userinfo mode Run ****************************************************/Public Function Wxoauthuser ($OauthAT, $openId) {$ur L = "https://api.weixin.qq.com/sns/userinfo?access_token=". $OauthAT. " &openid= ". $openId."        &AMP;LANG=ZH_CN ";        $result = $this->wxhttpsrequest ($url);        $jsoninfo = Json_decode ($result, true);          return $jsoninfo; /***************************************************** * Generates a random string-up to a maximum of 32-bit strings ************************* /Public Function wxnoncestr ($length = +, $type = FALSE) {$chars = "Abcdefghijklmnop      qrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";      $str = "";      for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1); } if ($type = = TRUE) {REturn Strtoupper (MD5 (Time (). $str));      } else {return $str; }}/******************************************************* * Merchant order number-Maximum 28-bit string *********************        /Public Function Wxmchbillno ($mchid = NULL) {if (Is_null ($mchid)) { if (Self::mchid = = "" | |        Is_null (Self::mchid)) {$mchid = time ();        } else{$mchid = Self::mchid;      }} else{$mchid = substr (Addslashes ($mchid), 0,10);    Return date ("Ymd", Time ()). Time (). $mchid; }/******************************************************* * formatted array becomes parameter format-supports URL encryption ********************* /Public Function Wxsetparam ($parameters) {if (Is_array ($parameters) &amp        ;&!empty ($parameters)) {$this->parameters = $parameters;      return $this->parameters;      } else{return Array (); }    }         /*** formatted array becomes parameter format-supports URL encryption ********************************** /Public Function Wxformatarray ($parameters = NULL, $urlencode = FALSE) {if (Is_null ($param      eters) {$parameters = $this->parameters; } $restr = "";//Initialize Empty ksort ($parameters);//Sort parameter foreach ($parameters as $k + $v) {//Loop custom parameter if (nul L! = $v && "null"! = $v && "sign"! = $k) {if ($urlencode) {///if the parameter needs to be increased by URL encryption, do not need $          v = urlencode ($v); } $restr. = $k. "=" . $v.  "&";//Return full string} if (Strlen ($RESTR) > 0) {//If there is data then the last "&" Delete $restr = substr ($restr, 0,      Strlen ($RESTR)-1); } return $RESTR;//Return string}/******************************************************* * MD5 signature Generator-required number of parameters The group is converted to a string [Wxformatarray method] *******************************************************/Public function wxmd5sign ($contENT, $privatekey) {try {if (Is_null ($key)) {throw new Exception ("Tenpay signature key cannot be empty!        ");        } if (Is_null ($content)) {throw new Exception ("Tenpay signature content cannot be empty"); } $signStr = $content. "&key=".        $key;      Return Strtoupper (MD5 ($SIGNSTR));      } catch (Exception $e) {die ($e->getmessage ()); }}/******************************************************* * SHA1 signature Generator-need to convert a parameter array into a string [Wxformatarray method ] *******************************************************/Public Function wxsha1sign ($content, $privatekey) {TR y {if (Is_null ($key)) {throw new Exception ("Tenpay signature key cannot be empty!        ");        } if (Is_null ($content)) {throw new Exception ("Tenpay signature content cannot be empty"); } $signStr = $content. "&key=".        $key;      Return Strtoupper (SHA1 ($SIGNSTR));      } catch (Exception $e) {die ($e->getmessage ()); }    }     /************************************ Array parsing XML-Red Envelope interface *******************************************************/public fun      Ction wxarraytoxml ($parameters = NULL) {if (Is_null ($parameters)) {$parameters = $this->parameters;      } if (!is_array ($parameters) | | empty ($parameters)) {die ("parameter not unresolved for an array"); } $xml = "
  
   
    
 "; foreach ($arr as $key = + $val) {if (Is_numeric ($val)) {$xml. = "<". $key. "         > ". $val." 
     ; } else $xml. = "<". $key. "       > ".$val." 
     "; } $xml. = "
 
   
  ";     return $xml; }       }
 

Later or will be added together to do this class, online resources are many, but there is a certain basis for people to see the change can be, for no contact just contact novice still need to give support. Help users to train their ideas.

The above mentioned is the whole content of this article, I hope you can like.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.