Analysis on using YII2 to develop the background of micro-credit

Source: Internet
Author: User
Tags cdata openid php framework sha1 ticket yii
This article mainly introduces the use of YII2 back-end development of the analysis, has a certain reference value, now share to everyone, the need for friends can refer to

Yii2 is a high-performance, component-based PHP framework, this article gives you a detailed introduction to the use of YII2 development background. Let's see it together.

There are many online YII2.0 development tutorials, but too complicated and messy, so here today to summarize the use of YII2 backstage development series, to the needs of the small partners reference.

One: Access

YII2 Background Configuration

1. Configure the token parameter in app/config/params.php

return [//Access ' WeChat ' =>[' token ' = ' your token ',];

2. Configure routing in app/config/main.php

Because the interface module uses RESTful APIs, you need to define routing rules.

' Urlmanager ' = [' Enableprettyurl ' + true, ' enablestrictparsing ' = ' = ', ' showscriptname ' = ' false ', ' rules ' = = [  ' class ' = ' Yii\rest\urlrule ',  ' controller ' = ' WeChat ',  ' extrapatterns ' and ' [  ' GET Valid ' = ' valid ',], [],],  ],

3. Create a new Wechatcontroller in App/controllers

<?phpnamespace api\controllers;use yii;use Yii\rest\activecontroller;class Wechatcontroller extends activecontroller{Public $modelClass = ", Public function Actionvalid () {$echoStr = $_get[" Echostr "]; $signature = $_get ["Signature"]; $timestamp = $_get["timestamp"]; $nonce = $_get["nonce"]; Valid signature, option if ($this->checksignature ($signature, $timestamp, $nonce)) {  echo $echoStr;}} private function Checksignature ($signature, $timestamp, $nonce) {/must define TOKEN by yourself $token = Yii:: $app->params [' WeChat '] [' token ']; if (! $token) {  echo ' token is not defined! ';} else {  $TMPARR = array ($token, $timestamp, $nonce);  Use sort_string rule  SORT ($TMPARR, sort_string);  $TMPSTR = implode ($TMPARR);  $TMPSTR = SHA1 ($TMPSTR);  if ($tmpStr = = $signature) {  return true;  } else{  return false;}}}  

Public Number Background configuration

Configure the URL and token in the background of the public number, then submit the verification.

Url:http://app.demo.com/wechats/validtoken:your token

Second: access to user information

User table Design

CREATE TABLE ' wechat_user ' (  ' id ' int (one) not null,  ' OpenID ' varchar (255) COLLATE utf8_unicode_ci NOT null,  ' Nickname ' varchar (COLLATE) utf8_unicode_ci not null COMMENT ' nickname ',  ' sex ' tinyint (4) NOT null COMMENT ' sex ',  ' head '  Imgurl ' varchar (255) COLLATE utf8_unicode_ci not NULL COMMENT ' avatar ',  ' country ' varchar (COLLATE utf8_unicode_ci not) Null COMMENT ' country ',  ' province ' varchar (COLLATE) utf8_unicode_ci not NULL COMMENT ' province ',  ' city ' varchar (COLLA) TE utf8_unicode_ci NOT null COMMENT ' city ',  ' access_token ' varchar (255) COLLATE utf8_unicode_ci NOT null,  ' Refresh _token ' varchar (255) COLLATE utf8_unicode_ci NOT NULL,  ' created_at ' timestamp NULL DEFAULT current_timestamp) Engine=innodb auto_increment=4 DEFAULT Charset=utf8 collate=utf8_unicode_ci; ALTER TABLE ' wechat_user '  ADD PRIMARY KEY (' id ');

Get the relevant interface for user information

1. User authorization interface: Get Access_token, OpenID, etc. get and save user data to Database

Public Function Actionaccesstoken () {$code = $_get["code"];    $state = $_get["state"];    $appid = Yii:: $app->params[' WeChat ' [' AppID '];    $appsecret = Yii:: $app->params[' WeChat ' [' Appsecret ']; $request _url = ' https://api.weixin.qq.com/sns/oauth2/access_token?appid= '. $appid. ' &secret= '. $appsecret. ' &code= '. $code. '    &grant_type=authorization_code ';    Initializes a curl session $ch = Curl_init ();    curl_setopt ($ch, Curlopt_url, $request _url);    curl_setopt ($ch, Curlopt_returntransfer, true);    $result = curl_exec ($ch);    Curl_close ($ch);    $result = $this->response ($result);    Get token and OpenID successful, data parsing $access _token = $result [' Access_token '];    $refresh _token = $result [' Refresh_token '];    $openid = $result [' OpenID '];    Request interface, get user information $userInfo = $this->getuserinfo ($access _token, $openid);    $user _check = Wechatuser::find ()->where ([' OpenID ' = $openid])->one (); if ($user _check) {//update user profile} else {//save user Profile}//redirect if for front page($openid)    {return $this->redirect ($state. $openid);    } else {return $this->redirect ($state); }}

2. Obtaining user information from

Public Function GetUserInfo ($access _token, $openid) {    $request _url = ' Https://api.weixin.qq.com/sns/userinfo? Access_token= '. $access _token. ' &openid= '. $openid. ' &LANG=ZH_CN ';    Initializes a curl session    $ch = Curl_init ();    curl_setopt ($ch, Curlopt_url, $request _url);    curl_setopt ($ch, Curlopt_returntransfer, true);    $result = curl_exec ($ch);    Curl_close ($ch);    $result = $this->response ($result);    return $result;}

3. Get the user Data interface

Public Function Actionuserinfo () {if (Isset ($_request["OpenID")) {  $openid = $_request["OpenID"];  $user = Wechatuser::find ()->where ([' OpenID ' = $openid])->one ();  if ($user) {   $result [' error '] = 0;   $result [' msg '] = ' get success ';   $result [' user '] = $user;  } else {   $result [' error '] = 1;   $result [' msg '] = ' no user ';  } } else {  $result [' error '] = 1;  $result [' msg '] = ' OpenID is empty '; } return $result;}

Three: Payment

1. Payment Interface: Package payment data

public function Actionpay () {if (Isset ($_request["UID"]) &&isset ($_        request["OID"]) &&isset ($_request["Totalfee"]) {//uid, oid, totalfee $uid = $_request["UID"];        $oid = $_request["oid"];        $totalFee = $_request["Totalfee"];        $timestamp = time ();        Payment Parameters $appid = Yii:: $app->params[' WeChat ' [' AppID '];        $mchid = Yii:: $app->params[' WeChat ' [' Mchid '];        $key = Yii:: $app->params[' WeChat ' [' Key '];        $NOTIFYURL = Yii:: $app->params[' WeChat ' [' Notifyurl '];        Payment Package $wx _pay = new Wechatpay ($mchid, $appid, $key);        $package = $wx _pay->createjsbizpackage ($uid, $totalFee, $oid, $NOTIFYURL, $timestamp);        $result [' error '] = 0;        $result [' msg '] = ' pay package success ';        $result [' package '] = $package;    return $result;        }else{$result [' error '] = 1;    $result [' msg '] = ' request parameter error '; } return $result;} 

2. Receive an asynchronous payment result notification sent

Public Function actionnotify () {$postStr = $GLOBALS ["Http_raw_post_data"];    $POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', libxml_nocdata);    if ($POSTOBJ = = = False) {die (' Parse XML error ');    } if ($postObj->return_code! = ' SUCCESS ') {die ($postObj->return_msg);    } if ($postObj->result_code! = ' SUCCESS ') {die ($postObj->err_code);    }//Payment parameters $appid = Yii:: $app->params[' WeChat ' [' AppID '];    $mchid = Yii:: $app->params[' WeChat ' [' Mchid '];    $key = Yii:: $app->params[' WeChat ' [' Key '];    $WX _pay = new Wechatpay ($mchid, $appid, $key);    Verify Signature $arr = (array) $postObj;    unset ($arr [' sign ']);    if ($wx _pay->getsign ($arr, $key)! = $postObj->sign) {die ("signature error"); }//payment processing is correct-determine if the payment status has been processed $orders = Order::find ()->where ([' uid ' = ' = ' $postObj->openid, ' oid ' = = $POSTOBJ->ou    T_trade_no, ' status ' = 0])->all (); if (count ($orders) > 0) {//Update order status foreach ($orDERs as $order) {//update order $order [' status '] = 1;        $order->update (); } return ' <xml><return_code><! [cdata[success]]></return_code><return_msg><!    [cdata[ok]]></return_msg></xml> '; } else {//order status updated, return directly to ' <xml><return_code><![ cdata[success]]></return_code><return_msg><!    [cdata[ok]]></return_msg></xml> '; }}

3. Payment Class wechatpay.php

<?phpnamespace api\sdk;use yii;class wechatpay{protected $mchid;    protected $appid;    protected $key;        Public function __construct ($mchid, $appid, $key) {$this->mchid = $mchid;        $this->appid = $appid;    $this->key = $key; Public Function Createjsbizpackage ($openid, $totalFee, $outTradeNo, $orderName, $NOTIFYURL, $timestamp) {$conf IG = Array (' mch_id ' = = $this->mchid, ' appid ' = + $this->appid, ' key ' = $t        His->key,); $unified = Array (' appid ' = = $config [' AppID '], ' attach ' = ' pay ', ' body ' and ' = ' $orde Rname, ' mch_id ' = $config [' mch_id '], ' nonce_str ' + self::createnoncestr (), ' Notif Y_url ' + $notifyUrl, ' OpenID ' = $openid, ' out_trade_no ' + $outTradeNo, ' Spbil           L_create_ip ' = ' 127.0.0.1 ', ' Total_fee ' and intval ($totalFee * 100), ' Trade_type ' = ' JSAPI ',);        $unified [' sign '] = Self::getsign ($unified, $config [' key ']);        $RESPONSEXML = Self::curlpost (' Https://api.mch.weixin.qq.com/pay/unifiedorder ', Self::arraytoxml ($unified));        $unifiedOrder = simplexml_load_string ($responseXml, ' simplexmlelement ', libxml_nocdata);        if ($unifiedOrder = = = False) {die (' Parse XML error ');        } if ($unifiedOrder->return_code! = ' SUCCESS ') {die ($unifiedOrder->return_msg);        } if ($unifiedOrder->result_code! = ' SUCCESS ') {die ($unifiedOrder->err_code); } $arr = Array ("appId" = = $config [' appId '], "timeStamp" and "= $timestamp," Non Cestr "= Self::createnoncestr ()," package "=" prepay_id= ".        $unifiedOrder->prepay_id, "signtype" = ' MD5 ',);        $arr [' paysign '] = self::getsign ($arr, $config [' key ']);    return $arr; } public static FUnction curlget ($url = ", $options = Array ()) {$ch = Curl_init ($url);        curl_setopt ($ch, Curlopt_returntransfer, 1);        curl_setopt ($ch, Curlopt_timeout, 30);        if (!empty ($options)) {Curl_setopt_array ($ch, $options);        }//https request does not validate the certificate and host curl_setopt ($ch, Curlopt_ssl_verifypeer, false);        curl_setopt ($ch, Curlopt_ssl_verifyhost, false);        $data = curl_exec ($ch);        Curl_close ($ch);    return $data;            public static function Curlpost ($url = ", $postData =", $options = Array ()) {if (Is_array ($postData)) {        $postData = Http_build_query ($postData);        } $ch = Curl_init ();        curl_setopt ($ch, Curlopt_url, $url);        curl_setopt ($ch, Curlopt_returntransfer, 1);        curl_setopt ($ch, Curlopt_post, 1);        curl_setopt ($ch, Curlopt_postfields, $postData); curl_setopt ($ch, Curlopt_timeout, 30); Sets the maximum number of seconds that curl allows to execute if (!empty ($options)) {Curl_setopt_arRay ($ch, $options);        }//https request does not validate the certificate and host curl_setopt ($ch, Curlopt_ssl_verifypeer, false);        curl_setopt ($ch, Curlopt_ssl_verifyhost, false);        $data = curl_exec ($ch);        Curl_close ($ch);    return $data; } public static function createnoncestr ($length = +) {$chars = ' Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu        VWXYZ0123456789 ';        $str = ";        for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);    } return $STR;        public static function Arraytoxml ($arr) {$xml = "<xml>"; foreach ($arr as $key = + $val) {if (Is_numeric ($val)) {$xml. = "<". $key. ">". $val. "</". $key.            ">"; } else {$xml. = "<". $key. "><! [cdata[]. $val. "]]></". $key.            ">";        }} $xml. = "</xml>";    return $xml; } public static FunctIon Getsign ($params, $key) {ksort ($params, sort_string);        $unSignParaString = Self::formatqueryparamap ($params, false); $SIGNSTR = Strtoupper (MD5 ($unSignParaString. "&key=".        $key));    return $signStr;        } protected static function Formatqueryparamap ($paraMap, $urlEncode = False) {$buff = "";        Ksort ($PARAMAP);                    foreach ($paraMap as $k = + $v) {if (null! = $v && "null"! = $v) {if ($urlEncode) {                $v = UrlEncode ($v); } $buff. = $k. "=" . $v.            "&";        }} $reqPar = ';        if (strlen ($buff) >0) {$reqPar = substr ($buff, 0, strlen ($buff)-1);    } return $reqPar; }}

Four: Get the config parameter of JS-SDK

According to the Public Platform developer Documentation:

All pages that need to use JS-SDK must first inject the configuration information, otherwise they will not be called (the same URL needs to be called only once, the Web app for the spa that changes the URL can be called every time the URL changes, the Android client currently does not support the Pushstate H5 new feature, So using Pushstate to implement a web App page will cause the signature to fail, and this problem will be fixed in Android6.2.

That

Wx.config ({    debug:true,///Open debug mode, the return value of all API calls will come out at the client, to see the incoming parameters can be opened on the PC side, the parameter information will be typed through log, only on the PC side will be printed.    appId: ',//required, public number unique identification    timestamp:,//required, generate signature timestamp    noncestr: ',//required, generate a signed random string    signature: ',//required, sign Name, see Appendix 1    jsapilist: []//required, the JS interface list to use, all JS interface list see appendix 2});

1. Payment Class wechatpay.php

<?phpnamespace api\sdk;use yii;class wechatpay{public Function getsignpackage ($url) {$jsapiTicket = Self::g        Etjsapiticket ();        $timestamp = time ();        $NONCESTR = Self::createnoncestr (); The order of the parameters here is sorted by the ASCII code of the key value in ascending order $string = "jsapi_ticket=". $jsapiTicket. " &noncestr= ". $nonceStr." &timestamp= ". $timestamp."        &url= ". $url;        $signature = SHA1 ($string); $signPackage = Array ("appId" = $this->appid, "noncestr" + $nonceStr, "Ti Mestamp "+ $timestamp," url "and" signature "," Rawstri "and" $signature "        ng "= $string);    return $signPackage;        } public static function Getjsapiticket () {//using Redis cache Jsapi_ticket $redis = Yii:: $app->redis;        $redis _ticket = $redis->get (' Wechat:jsapi_ticket ');        if ($redis _ticket) {$ticket = $redis _ticket; } else {$accessToken = SELf::getaccesstoken ();            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=". $accessToken;            $res = Json_decode (Self::curlget ($url));            $ticket = $res->ticket;                if ($ticket) {$redis->set (' Wechat:jsapi_ticket ', $ticket);            $redis->expire (' Wechat:jsapi_ticket ', 7000);    }} return $ticket;        } public static function Getaccesstoken () {//using Redis cache Access_token $redis = Yii:: $app->redis;        $redis _token = $redis->get (' Wechat:access_token ');        if ($redis _token) {$access _token = $redis _token;            } else {$appid = Yii:: $app->params[' WeChat ' [' AppID '];            $appsecret = Yii:: $app->params[' WeChat ' [' Appsecret ']; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". $appid. "            &secret= ". $appsecret; $res = Json_decode (Self::curlget ($url));            $access _token = $res->access_token;                if ($access _token) {$redis->set (' Wechat:access_token ', $access _token);            $redis->expire (' Wechat:access_token ', 7000);    }} return $access _token;        public static function Curlget ($url = ", $options = Array ()) {$ch = Curl_init ($url);        curl_setopt ($ch, Curlopt_returntransfer, 1);        curl_setopt ($ch, Curlopt_timeout, 30);        if (!empty ($options)) {Curl_setopt_array ($ch, $options);        }//https request does not validate the certificate and host curl_setopt ($ch, Curlopt_ssl_verifypeer, false);        curl_setopt ($ch, Curlopt_ssl_verifyhost, false);        $data = curl_exec ($ch);        Curl_close ($ch);    return $data;            public static function Curlpost ($url = ", $postData =", $options = Array ()) {if (Is_array ($postData)) {        $postData = Http_build_query ($postData);        } $ch = Curl_init (); curl_setopt ($ch, Curlopt_url, $url);        curl_setopt ($ch, Curlopt_returntransfer, 1);        curl_setopt ($ch, Curlopt_post, 1);        curl_setopt ($ch, Curlopt_postfields, $postData); curl_setopt ($ch, Curlopt_timeout, 30);        Sets the maximum number of seconds that curl allows to execute if (!empty ($options)) {Curl_setopt_array ($ch, $options);        }//https request does not validate the certificate and host curl_setopt ($ch, Curlopt_ssl_verifypeer, false);        curl_setopt ($ch, Curlopt_ssl_verifyhost, false);        $data = curl_exec ($ch);        Curl_close ($ch);    return $data; } public static function createnoncestr ($length = +) {$chars = ' Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu        VWXYZ0123456789 ';        $str = ";        for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);    } return $STR; }}

2. Get the Config parameter interface

Public Function Actionconfig () {if (Isset ($_request[' url ')) {$url = $_request[' url ');//payment parameter $appid = Yii:: $app->para ms[' WeChat ' [' AppID ']; $mchid = Yii:: $app->params[' WeChat ' [' Mchid ']; $key = Yii:: $app->params[' WeChat ' [' Key ']; $WX _pay = new Wechatpay ($mchid, $appid, $key); $package = $wx _pay->getsignpackage ($url); $result [' error '] = 0; $result [' msg '] = ' get success '; $result [' config '] = $package; } else {$result [' error '] = 1; $result [' msg '] = ' parameter error ';} return $result;}

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.