Opencart API : Issue with session app_id (how to get api_id) - php

I am working on Opencart API (opencart v2.3) and I follow this link for documentation (Opencart ) . But there is no data on opencart APIs and how to use it, So I follow steps from other websites and using that code I receive this message when call login api, Success: API session successfully started!
But whenever I use another API for add product in cart or view cart or add order, I receive permission issue. I debug code and found that it required session app_id and when I check, it store only token, not app_id
I use following code which I found by googling.
common.php
<?php
function do_curl_request($url, $params=array()) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'E:\practice\oc2.3\tmp\apicookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'E:\practice\oc2.3\tmp\apicookie.txt');
$params_string = '';
if (is_array($params) && count($params)) {
foreach($params as $key=>$value) {
$params_string .= $key.'='.$value.'&';
}
rtrim($params_string, '&');
curl_setopt($ch,CURLOPT_POST, count($params));
curl_setopt($ch,CURLOPT_POSTFIELDS, $params_string);
}
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}
login.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/login';
$fields = array(
'key' => 'FpafURRNAHgVcaUXZozahVdEOV7mtp1Q0ejvAMAIAfiZyVqIptqZ2uV9eQvT3PytlzELULH1vQwLKikFGBOm3yky1rTuFO6sEi0eBkH1y6WgpaNWIsB0ZMiRCCbGCBZZak2uR1CBg0TpOzcbevXWGStvoUsaKgl0B3OKRoHk6mRj7e6S63HJQzQksbbz0JfCuZsY9cvhY4ArQPzNf3XfrdgE3nTG5hYQCXaKPVqtS3R2Vqr4sazwjgXYajy7h6Dv',
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
if (isset($data->token)) {
$token = $data->token;
}
var_dump($data);
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);
customer api
public function index() {
$this->load->language('api/customer');
// Delete past customer in case there is an error
unset($this->session->data['customer']);
$json = array();
if (!isset($this->session->data['api_id'])) {
$json['error']['warning'] = $this->language->get('error_permission');
} else {
// Add keys for missing post vars
$keys = array(
'customer_id',
'customer_group_id',
'firstname',
'lastname',
'email',
'telephone',
'fax'
);
foreach ($keys as $key) {
if (!isset($this->request->post[$key])) {
$this->request->post[$key] = '';
}
}
// Customer
if ($this->request->post['customer_id']) {
$this->load->model('account/customer');
$customer_info = $this->model_account_customer->getCustomer($this->request->post['customer_id']);
if (!$customer_info || !$this->customer->login($customer_info['email'], '', true)) {
$json['error']['warning'] = $this->language->get('error_customer');
}
}
if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
$json['error']['firstname'] = $this->language->get('error_firstname');
}
if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
$json['error']['lastname'] = $this->language->get('error_lastname');
}
if ((utf8_strlen($this->request->post['email']) > 96) || (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL))) {
$json['error']['email'] = $this->language->get('error_email');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$json['error']['telephone'] = $this->language->get('error_telephone');
}
// Customer Group
if (is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
// Custom field validation
$this->load->model('account/custom_field');
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
if (($custom_field['location'] == 'account') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
} elseif (($custom_field['location'] == 'account') && ($custom_field['type'] == 'text') && !empty($custom_field['validation']) && !filter_var($this->request->post['custom_field'][$custom_field['custom_field_id']], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $custom_field['validation'])))) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
}
}
if (!$json) {
$this->session->data['customer'] = array(
'customer_id' => $this->request->post['customer_id'],
'customer_group_id' => $customer_group_id,
'firstname' => $this->request->post['firstname'],
'lastname' => $this->request->post['lastname'],
'email' => $this->request->post['email'],
'telephone' => $this->request->post['telephone'],
'fax' => $this->request->post['fax'],
'custom_field' => isset($this->request->post['custom_field']) ? $this->request->post['custom_field'] : array()
);
$json['success'] = $this->language->get('text_success');
}
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}

Put the token right after your request URL will make it works.
Assume token returned by api/login is KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo.
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct&token=KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);

Make sure server's IP address is added to the allowed IP addresses.
To check that, go to System → Users → API then edit the Default one.
Once there, click on IP Address tab and insert the server IP address.
To get the server IP address, you can use the following command line:
$ curl ipinfo.io/ip

Related

how do i integrate paynow zimbabwe api with a localhost system?

Can you please help me to integrate paynow zimbabwe gateway with my localhost system.I have tried to follow their documentation https://developers.paynow.co.zw/docs/quickstart.html but I failed. I want the user to be redirected to the paynow page to pay penalties.Also the result or status must be obtained in order to update the system database. Is it possible to link a localhost system to the paynow api or my system have to be live?. Thank you in advance
<?php
include "./includes/tables_header.php";
include "./includes/db.php";
require_once "./paynow/autoloader.php";
use Paynow\Payments\Paynow;
if(isset($_POST['Paynow']))
{
class Payow{
public function paynows($amount)
{
$siteurl="http://localhost/online_offenceTracking_system/payment1.php?";//substitute with your own return url
define('ps_error', 'Error');
define('ps_ok','Ok');
define('ps_created_but_not_paid','created but not paid');
define('ps_cancelled','cancelled');
define('ps_failed','failed');
define('ps_paid','paid');
define('ps_awaiting_delivery','awaiting delivery');
define('ps_delivered','delivered');
define('ps_awaiting_redirect','awaiting redirect');
define('site_url', $siteurl);
$int_key="###########";//get from paynow.co.zw
$int_id=#######;//get from paynow.co.zw, it should be an intenger
$paymentid="testID1234hs";
$url="https://www.paynow.co.zw/interface/initiatetransaction/?";
$reference=sha1(Paynow\Payments\Paynow::$app->user->identity->email);
$amount=6.25;
$returnurl="http://localhost/online_offenceTracking_system/payment1.php?r=credit/index"; //substitute with your own return urls
$resulturl="http://localhost/online_offenceTracking_system/payment1.php?r=credit/index"; //substitute with your own return urls
$authemail="acmwamuka#gmail.com";//This is the buyer's email address
$additionalinfo="Paying for canteen meals.";
$concat=$int_key.$int_id.$paymentid.$url.$reference.$returnurl.$resulturl.$authemail.$additionalinfo;
$concat=$concat.$int_key;
$values = array('resulturl' => $resulturl,
'returnurl' => $returnurl,
'reference' => $reference,
'amount' => $amount,
'id' => $int_id,
'additionalinfo' => $additionalinfo,
'authemail' => $authemail,
'authphone' => "07777777777",
'status' => 'Message'); //just a simple message
$fields_string = $this->CreateMsg($values,$int_key);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); //need fixing
$result = curl_exec($ch);
if($result)
{
$msg = $this->ParseMsg($result);
if ($msg["status"] == ps_error){
header("Location: $checkout_url");
exit;
}
else if ($msg["status"] == "Ok"){
$validateHash = $this->CreateHash($msg, $int_key);
if($validateHash != $msg["hash"]){
$error = "Paynow reply hashes do not match : " . $validateHash . " - " . $msg["hash"];
echo $error;
}
else
{
$theProcessUrl = $msg["browserurl"];
//echo $theProcessUrl;
//header("Location: ".$theProcessUrl);
Paynow\Payments\Paynow::$app->response->redirect($theProcessUrl);
$orders_array = array();
}
}
else {
//unknown status or one you dont want to handle locally
$error = "Invalid status from Paynow, cannot continue.";
}
}
else
{
$error = curl_error($ch);
echo $error;
}
//print_r($result);
//close connection
curl_close($ch);
}
public function ParseMsg($msg) {
$parts = explode("&",$msg);
$result = array();
foreach($parts as $i => $value) {
$bits = explode("=", $value, 2);
$result[$bits[0]] = urldecode($bits[1]);
}
return $result;
}
function CreateMsg($values, $MerchantKey){
$fields = array();
foreach($values as $key=>$value) {
$fields[$key] = urlencode($value);
}
$fields["hash"] = urlencode($this->CreateHash($values, $MerchantKey));
$fields_string = $this->UrlIfy($fields);
return $fields_string;
}
public function UrlIfy($fields) {
$delim = "";
$fields_string = "";
foreach($fields as $key=>$value) {
$fields_string .= $delim . $key . '=' . $value;
$delim = "&";
}
return $fields_string;
}
public function CreateHash($values, $MerchantKey){
$string = "";
foreach($values as $key=>$value) {
if( strtoupper($key) != "HASH" ){
$string .= $value;
}
}
$string .= $MerchantKey;
$hash = hash("sha512", $string);
return strtoupper($hash);
}
}}
?>
You can use a free service like ngrok to expose your localhost environment to the world wide web. Just make sure your returnurl and resulturl are using your ngrok address so that Paynow can callback your application.

How to send variable value from one function to other function in a different page

I'm new to php oop and I wanted to send the variable value from one function to another in a different page. So, currently I have this one function in one page that I want to send the data to the other function in a different page. Is that even possible perhaps?
Here's the first function in sendData.php
public function main($data) {
$settings = new Settings();
$hash_code = md5('standard' . '10068' . '08f94110d5697a2497511594c31704d0' .'3.00');
$std_post = array(
'apitype'=>'standard', //fix value
'apiid'=>'10068', //your api id from ibill
'apiorderid'=>'OPC0001#00000282', //your order id
'apihashcode'=>$hash_code, //generate hash code as above
'apiamount'=>'3.00', //your customer transaction amount
'apiemail'=>'alif4arsenal97#gmail.com'); //your customer email
$callbackJSON = json_encode($std_post);
$url = 'https://ibill.my/merchant/?ng=callback_api'; //link need to send data
$ch = curl_init($url); // where to post
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $callbackJSON);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = "Cache-Control: no-cache";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$results = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
//echo $results;
$objJSON = json_decode($results); //decode json result
//should return 'SUCCESS'
$callback_status = $objJSON->{'callback_status'}; //callback Status
$message = $objJSON->{'message'}; //callback Message
//Refer on statuspage.php
$std_status_code = $objJSON->{'std_status_code'}; //payment status code
$std_status = $objJSON->{'std_status'}; //payment status
$std_order_id = $objJSON->{'std_order_id'}; //your order id
$std_purchase_code = $objJSON->{'std_purchase_code'}; //ibill transaction id
$std_amount = $objJSON->{'std_amount'}; //transaction amount
$std_datepaid = $objJSON->{'std_datepaid'}; //transaction date time
//Hash code for security
$std_hash_code = $objJSON->{'std_hash_code'}; //Hash code
$hash_code = md5('08f94110d5697a2497511594c31704d0'.'10068'.$std_order_id.$std_amount); //hash code format
$data = [
'callback_status' => $callback_status,
'message' => $message,
'std_status_code' => $std_status_code,
'std_status' => $std_status,
'std_order_id' => $std_order_id,
'std_purchase_code' => $std_purchase_code,
'std_amount' => $std_amount,
'std_datepaid' => $std_datepaid,
'std_hash_code' => $std_hash_code,
'hash_code' => $hash_code
];
processPayment($data);
}
Here's the second function in a different that I wanted the data in the first page to be send to which is test.php
public function processPayment($data)
{
if (!isset($data['std_status_code'])) return false;
if (!isset($data['std_hash_code'])) return false;
$settings = new Settings();
$sale_id = (int) substr($data['std_order_id'], 8);
$sale = Sales::get($sale_id);
if (empty($sale)) return false;
if ($sale['status'] == 1) return $sale;
if ($sale['payment_method'] !== 'ibill' || $sale['status'] != 0) return false;
$sale_uid = $sale['uid'];
$sale_method = $sale['method'];
$paid_amount = bcadd($sale['total_amount'], $sale['handling_charge'], 2);
// Verify the data integrity sent by iBill
$hash = md5($settings->ibill_secret_key . $settings->ibill_merchant_id . $data['std_order_id'] . $data['std_amount']);
$payment_processor_status = -1;
$sale_status = 0;
// Check provided hash and status
if ($hash === $data['std_hash_code'] && $data['std_status_code'] == 00) {
$payment_processor_status = 1;
$sale_status = 1;
}
if ($sale_status === 0) {
if ($data['std_status_code'] != 00) {
$data['std_status'] = '<span style="color: red">' . $data['std_status'] . '</span>';
}
if ($data['std_hash_code'] !== $hash) {
$data['std_hash_code'] = '<span style="color: red">' . $data['std_hash_code'] . '</span>';
}
}
// Prepare updated sale data
$now = new DateTime();
$sale = [
'payment_processor_status' => $payment_processor_status,
'payment_processor_data' => $data,
'payment_time' => $now->format('g:i:s A'),
'payment_date' => $now->format('d-m-Y')
];
Sales::update($sale_id, $sale);
if ($sale_status === 1) {
Sales::confirmSale($sale_id, false);
}
return ['uid' => $sale_uid, 'method' => $sale_method];
}
Those functions are class methods, not only functions.
you can use them (or pass data from one to another) by creating instances of their classes. for example something like this:
class one {
public function f1($data) {
// do something
$instance = new two();
$instance->f2($data);
}
}
class two {
public function f2($data) {
// do something else
}
}
I hope it would work for you.

Wordpress wp_insert_post fire multiple times on mobile devices

I have built a custom front-end multipage donation form on Wordpress, saving the data via session variables across the pages. I then use save_post hook to run a function to redirect the user, after submitting the form, to an online payment portal. The problem is, when users access the form via mobile, the function wp_insert_post fires multiple time.
This is the code that I have on the php page used for processing the data from the form.
<?php
header('Cache-Control: no cache'); //no cache
session_cache_limiter('private_no_expire'); // works
//session_cache_limiter('public'); // works too
//let's start the session
session_start();
require_once 'library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
//LISTING ALL VARIABLES AVAILABLE FROM FRONTEND FORM
$negara = $_SESSION['negara'];
$binatang = $_SESSION['binatang'];
if($_SESSION['ekor']) {
$ekorBahagian = $_SESSION['ekor'];
} else {
$ekorBahagian = $_SESSION['bahagian'];
}
$nama1 = $_SESSION['nama'];
$kp1 = $_SESSION['kp'];
$telefon1 = $_SESSION['telefon'];
$emel1 = $_SESSION['emel'];
$alamat11 = $_SESSION['alamat1'];
$alamat21 = $_SESSION['alamat2'];
$poskod1 = $_SESSION['poskod'];
$bandar1 = $_SESSION['bandar'];
$negeri1 = $_SESSION['negeri'];
$peserta1 = $_SESSION['peserta'];
$kempen = $_POST['kempen'];
$bank = $_POST['bank'];
if($telefon1) {
$mobile = preg_replace("/[^0-9]/", "", $telefon1);
$custTel = $mobile;
$custTel2 = substr($mobile, 0, 1);
if ($custTel2 == '+') {
$custTel3 = substr($mobile, 1, 1);
if ($custTel3 != '6') {
$custTel = "+6" . $mobile;
}
} elseif ($custTel2 == '6') {
} else {
if ($custTel != '') {
$custTel = "+6" . $mobile;
}
}
}
//purifying the texts
$nama = $purifier->purify($nama1);
$kp = $purifier->purify($kp1);
$telefon = $purifier->purify($custTel);
$emel = $purifier->purify($emel1);
$alamat1 = $purifier->purify($alamat11);
$alamat2 = $purifier->purify($alamat21);
$poskod = $purifier->purify($poskod1);
$bandar = $purifier->purify($bandar1);
$negeri = $purifier->purify($negeri1);
$peserta = $purifier->purify($peserta1);
if($_SESSION['ekor']) {
$bil = $_SESSION['ekor']; //capturing bilangan ekor into a var
switch ($_SESSION['negara']){
case 'Malaysia':
$jumlahHarga = $bil*(650*7);
break;
case 'ASEAN':
$jumlahHarga = $bil*(450*7);
break;
case 'Timur Tengah':
$jumlahHarga = $bil*(1300*7);
break;
case 'Afrika':
$jumlahHarga = $bil*(350*7);
break;
default:
}
} else {
$bil = $_SESSION['bahagian']; //capturing bilangan bahagian into a var
switch ($_SESSION['negara']){
case 'Malaysia':
$jumlahHarga = $bil*650;
break;
case 'ASEAN':
$jumlahHarga = $bil*450;
break;
case 'Timur Tengah':
$jumlahHarga = $bil*1300;
break;
case 'Afrika':
$jumlahHarga = $bil*350;
break;
default:
}
}
$post = array(
'post_title' => wp_strip_all_tags( $nama ),
'post_status' => 'publish',
'post_type' => 'qurban',
'meta_input' => array(
'pilihan_negara' => $negara,
'pilihan_lembu' => $binatang,
'bilangan_ekorbahagian' => $ekorBahagian,
'jumlah_bayaran' => $jumlahHarga,
'nama_penuh' => $nama,
'nombor_kad_pengenalan' => $kp,
'nombor_telefon' => $telefon,
'emel' => $emel,
'alamat_rumah_1' => $alamat1,
'alamat_rumah_2' => $alamat2,
'poskod' => $poskod,
'bandar' => $bandar,
'negeri' => $negeri,
'senarai_nama_peserta' => $peserta,
'bank' => $bank,
'kempen' => $kempen
)
);
$post_id = wp_insert_post($post);
get_header();
?>
<?php
get_footer();
?>
Below is the code that uses save_post to redirect the user to external payment site:
?php
require_once "Mobile_Detect.php";
////////////////////////////
//// PAYMENT REDIRECTION FUNCTION
////////////////////////////
function my_save_post_iq( $post_id ) {
debug_to_console( "save post function fired" );
$billplzApi = get_field('iq_secret_key', 'option');
$billplzId = get_field('iq_collection_id', 'option');
// bail early if not a donation post
if( get_post_type($post_id) !== 'qurban' ) {
return;
}
// bail early if editing in admin
if( is_admin() ) {
return;
}
$post = get_post( $post_id);
$jumlah_bayaran_iq = get_field('jumlah_bayaran', $post_id);
//check & update user device type
$detect = new Mobile_Detect;
if($detect->isMobile()){
update_field('devices', 'mobile' , $post);
} else {
update_field('devices', 'desktop', $post);
}
$name = get_field('nama_penuh', $post);
$email = get_field('emel', $post);
$mobile = get_field('nombor_telefon', $post);
$bank = get_field('bank', $post);
$billplz_data = array(
'amount' => $jumlah_bayaran_iq * 100,
'name' => $name,
'mobile' => $mobile,
'email' => $email,
'collection_id' => $billplzId,
'deliver' => false,
'reference_1_label' => 'Bank Code',
'reference_1' => $bank,
'reference_2_label' => 'Post ID',
'reference_2' => $post_id,
'description' => 'xxx',
'redirect_url' => home_url('qurbanv2/paymentredirectv2'),
'callback_url' => home_url('paymentcallback')
);
$process = curl_init('https://www.billplz.com/api/v3/bills/');
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $billplzApi . ":");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($billplz_data));
$return = curl_exec($process);
curl_close($process);
$arr = json_decode($return, true);
$billplz_url = $arr['url'];
$billplz_id = $arr['id'];
//update payment status
update_field('billplz_iq', $billplz_id , $post);
//$hzpost_name = array(
// 'ID' = $post,
// 'post_name' = $billplz_url
//);
//
//wp_update_post($hzpost_name);
header('Location: '. $billplz_url . '?auto_submit=true');
exit();
}
add_action('save_post', 'my_save_post_iq', 10, 1);
I am new to Wordpress development, so please help.
Found the bug. It's got to do with how the payment gateway treats mobile number. I've added a line to add '+' in front of the numbers, and the duplication stops.
if($telefon1) {
$mobile = preg_replace("/[^0-9]/", "", $telefon1);
$custTel = $mobile;
$custTel2 = substr($mobile, 0, 1);
if ($custTel2 == '+') {
$custTel3 = substr($mobile, 1, 1);
if ($custTel3 != '6') {
$custTel = "+6" . $mobile;
}
} elseif ($custTel2 == '6') {
$custTel = "+" . $mobile; //added this line.
} else {
if ($custTel != '') {
$custTel = "+6" . $mobile;
}
}
}

login to local and server

how to log on localhost mark must be changed at the server login below to log in the server , and ENVIRONMENT == "development " is not called server and ENVIRONMENT == " test " called Server , without change of ENVIRONMENT == " test "?
if($email == NULL || $pass == NULL) return array("success"=>0,"msg"=>"Email dan password harus diisi");
else
{
if (ENVIRONMENT == "development")
{
$data['result'] =Array
(
'message' => 'Success',
'code' => 00,
'obj' => Array ('loginTried' => 0,
'email' => 'maheswara#gmail.com',
'phoneNumber' => 089615378878,
'name' => 'Dika',
'point' => 10, ));
return array("success"=>1,"msg"=>"Logged in");
}
else
{
$pass = md5($pass);
$url = "http://tooz.co.";
$post = json_encode(array('email' => $email, 'userPassword' => $pass));
$fields_string = "";
$fields = array(
'logintikiid' => $post
);
//url-ify the data for the POST
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 30);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$data = json_decode($result,TRUE);
if($data['code']=="00")
{
$this->CI->session->user_email = $data['obj']['email'];
$this->CI->session->user_phone = $data['obj']['phoneNumber'];
$this->CI->session->user_name = $data['obj']['name'];
$this->CI->session->tooz_point = $data['obj']['point'];
return array("success"=>1,"msg"=>"Logged in");
}
else
{
return array("success"=>0,"msg"=>"Email dan password salah");
}
}
}
}
this is controler
public function index($from=NULL)
{
$data = array();
switch ($from) {
case 'pickup':
$redirect = base_url("pickup");
set_top_msg("Untuk mengakses fitur pickup, silahkan login terlebih dahulu");
break;
case 'book':
$redirect = base_url("book");
set_top_msg("Untuk mengakses fitur booking, silahkan login terlebih dahulu");
break;
default:
$redirect = base_url();
break;
}
if ($this->session->user_email)
{
header("location:". base_url("tooz"));
die();
}
else if($this->input->post())
{
$this->load->library("login_library");
$email = $this->input->post("email");
$pass = $this->input->post("pass");
$return = $this->login_library->login($email,$pass);
if($return['success']==1)header('Location:'. $redirect);
else set_top_msg($return["msg"],"warning");
}
load_page($data);
}

Get array from mysql and pass it to a method

Hi I am sending the push notification using below code. I've a problem in this code.
<?php
class GCMPushMessage
{
var $url = 'http://android.googleapis.com/gcm/send';
var $serverApiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
var $devices = array();
function setDevices($deviceIds)
{
if (is_array($deviceIds)) {
$this->devices = $deviceIds;
} else {
$this->devices = array(
$deviceIds
);
}
}
function send($message)
{
if (!is_array($this->devices) || count($this->devices) == 0) {
$this->error("No devices set");
}
if (strlen($this->serverApiKey) < 8) {
$this->error("Server API Key not set");
}
$fields = array(
'registration_ids' => $this->devices,
'data' => array(
"msg" => $message
)
);
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
$this->StripResponseFromGCM(json_decode($result));
// Close connection
curl_close($ch);
return $result;
}
function error($msg)
{
echo "Android send notification failed with error:";
echo "\t" . $msg;
exit(1);
}
function StripResponseFromGCM($response)
{
//canonicalID's are the
if ($response->failure == 0 && $response->canonical_ids == 0)
return;
for ($i = 0; $i < sizeof($response->results); $i++) {
if (isset($response->results[$i]->registration_id)) { //if new registrationID is sent as canonicalID
//update this registrationID in the database
} else if ($response->results[$i]->error == "Unavailable") {
// user with index == $i is unavailable
} else if ($response->results[$i]->error == "InvalidRegistration") {
// user with index == $i has InvalidRegistration ID
} else if ($response->results[$i]->error == "NotRegistered") {
// user with index == $i is not registered
}
}
}
}
$msg = array(
'data' => array(
'msg' => 'just a simple message'
)
);
require_once('connection.php');
$sql = mysql_query("select gcmid from gcmid");
$new_array = mysql_fetch_array($sql);
print_r($new_array);
$obj = new GCMPushMessage();
$obj->setDevices($new_array);
$obj->send($msg);
?>
If i put a single id in setDevices method then it is working fine but if i
fetching the gcm ids from database and passing it to method setDevices then the code is not working.It suppose to send push notification to devices but it is not working.

Categories